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::SETCC, MVT::f32, Custom);
156 setOperationAction(ISD::SETCC, MVT::f64, Custom);
157 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
158 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
159 setOperationAction(ISD::VASTART, MVT::Other, Custom);
160 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
161 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
162 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
163 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
164 setOperationAction(ISD::LOAD, MVT::i32, Custom);
165 setOperationAction(ISD::STORE, MVT::i32, Custom);
167 if (!TM.Options.NoNaNsFPMath) {
168 setOperationAction(ISD::FABS, MVT::f32, Custom);
169 setOperationAction(ISD::FABS, MVT::f64, Custom);
173 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
174 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
175 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
176 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
177 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
178 setOperationAction(ISD::SELECT, MVT::i64, Custom);
179 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
180 setOperationAction(ISD::LOAD, MVT::i64, Custom);
181 setOperationAction(ISD::STORE, MVT::i64, Custom);
185 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
186 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
187 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
190 setOperationAction(ISD::SDIV, MVT::i32, Expand);
191 setOperationAction(ISD::SREM, MVT::i32, Expand);
192 setOperationAction(ISD::UDIV, MVT::i32, Expand);
193 setOperationAction(ISD::UREM, MVT::i32, Expand);
194 setOperationAction(ISD::SDIV, MVT::i64, Expand);
195 setOperationAction(ISD::SREM, MVT::i64, Expand);
196 setOperationAction(ISD::UDIV, MVT::i64, Expand);
197 setOperationAction(ISD::UREM, MVT::i64, Expand);
199 // Operations not directly supported by Mips.
200 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
201 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
202 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
203 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
204 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
205 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
206 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
208 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
209 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
210 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
211 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
212 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
214 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
215 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::ROTL, MVT::i32, Expand);
217 setOperationAction(ISD::ROTL, MVT::i64, Expand);
219 if (!Subtarget->hasMips32r2())
220 setOperationAction(ISD::ROTR, MVT::i32, Expand);
222 if (!Subtarget->hasMips64r2())
223 setOperationAction(ISD::ROTR, MVT::i64, Expand);
225 setOperationAction(ISD::FSIN, MVT::f32, Expand);
226 setOperationAction(ISD::FSIN, MVT::f64, Expand);
227 setOperationAction(ISD::FCOS, MVT::f32, Expand);
228 setOperationAction(ISD::FCOS, MVT::f64, Expand);
229 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
230 setOperationAction(ISD::FPOW, MVT::f32, Expand);
231 setOperationAction(ISD::FPOW, MVT::f64, Expand);
232 setOperationAction(ISD::FLOG, MVT::f32, Expand);
233 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
234 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
235 setOperationAction(ISD::FEXP, MVT::f32, Expand);
236 setOperationAction(ISD::FMA, MVT::f32, Expand);
237 setOperationAction(ISD::FMA, MVT::f64, Expand);
238 setOperationAction(ISD::FREM, MVT::f32, Expand);
239 setOperationAction(ISD::FREM, MVT::f64, Expand);
241 if (!TM.Options.NoNaNsFPMath) {
242 setOperationAction(ISD::FNEG, MVT::f32, Expand);
243 setOperationAction(ISD::FNEG, MVT::f64, Expand);
246 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
247 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
248 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
249 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
251 setOperationAction(ISD::VAARG, MVT::Other, Expand);
252 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
253 setOperationAction(ISD::VAEND, MVT::Other, Expand);
255 // Use the default for now
256 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
259 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
260 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
261 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
262 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
264 setInsertFencesForAtomic(true);
266 if (Subtarget->isSingleFloat())
267 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
269 if (!Subtarget->hasSEInReg()) {
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
271 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
274 if (!Subtarget->hasBitCount()) {
275 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
276 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
279 if (!Subtarget->hasSwap()) {
280 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
281 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
285 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
286 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
287 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
288 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
291 setTargetDAGCombine(ISD::ADDE);
292 setTargetDAGCombine(ISD::SUBE);
293 setTargetDAGCombine(ISD::SDIVREM);
294 setTargetDAGCombine(ISD::UDIVREM);
295 setTargetDAGCombine(ISD::SELECT);
296 setTargetDAGCombine(ISD::AND);
297 setTargetDAGCombine(ISD::OR);
298 setTargetDAGCombine(ISD::ADD);
300 setMinFunctionAlignment(HasMips64 ? 3 : 2);
302 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
303 computeRegisterProperties();
305 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
306 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
308 maxStoresPerMemcpy = 16;
311 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
312 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
319 return Subtarget->hasMips32r2Or64();
325 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
330 // Transforms a subgraph in CurDAG if the following pattern is found:
331 // (addc multLo, Lo0), (adde multHi, Hi0),
333 // multHi/Lo: product of multiplication
334 // Lo0: initial value of Lo register
335 // Hi0: initial value of Hi register
336 // Return true if pattern matching was successful.
337 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
338 // ADDENode's second operand must be a flag output of an ADDC node in order
339 // for the matching to be successful.
340 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
342 if (ADDCNode->getOpcode() != ISD::ADDC)
345 SDValue MultHi = ADDENode->getOperand(0);
346 SDValue MultLo = ADDCNode->getOperand(0);
347 SDNode* MultNode = MultHi.getNode();
348 unsigned MultOpc = MultHi.getOpcode();
350 // MultHi and MultLo must be generated by the same node,
351 if (MultLo.getNode() != MultNode)
354 // and it must be a multiplication.
355 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
358 // MultLo amd MultHi must be the first and second output of MultNode
360 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
363 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
364 // of the values of MultNode, in which case MultNode will be removed in later
366 // If there exist users other than ADDENode or ADDCNode, this function returns
367 // here, which will result in MultNode being mapped to a single MULT
368 // instruction node rather than a pair of MULT and MADD instructions being
370 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
373 SDValue Chain = CurDAG->getEntryNode();
374 DebugLoc dl = ADDENode->getDebugLoc();
376 // create MipsMAdd(u) node
377 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
379 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
380 MultNode->getOperand(0),// Factor 0
381 MultNode->getOperand(1),// Factor 1
382 ADDCNode->getOperand(1),// Lo0
383 ADDENode->getOperand(1));// Hi0
385 // create CopyFromReg nodes
386 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
388 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
390 CopyFromLo.getValue(2));
392 // replace uses of adde and addc here
393 if (!SDValue(ADDCNode, 0).use_empty())
394 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
396 if (!SDValue(ADDENode, 0).use_empty())
397 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
403 // Transforms a subgraph in CurDAG if the following pattern is found:
404 // (addc Lo0, multLo), (sube Hi0, multHi),
406 // multHi/Lo: product of multiplication
407 // Lo0: initial value of Lo register
408 // Hi0: initial value of Hi register
409 // Return true if pattern matching was successful.
410 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
411 // SUBENode's second operand must be a flag output of an SUBC node in order
412 // for the matching to be successful.
413 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
415 if (SUBCNode->getOpcode() != ISD::SUBC)
418 SDValue MultHi = SUBENode->getOperand(1);
419 SDValue MultLo = SUBCNode->getOperand(1);
420 SDNode* MultNode = MultHi.getNode();
421 unsigned MultOpc = MultHi.getOpcode();
423 // MultHi and MultLo must be generated by the same node,
424 if (MultLo.getNode() != MultNode)
427 // and it must be a multiplication.
428 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
431 // MultLo amd MultHi must be the first and second output of MultNode
433 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
436 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
437 // of the values of MultNode, in which case MultNode will be removed in later
439 // If there exist users other than SUBENode or SUBCNode, this function returns
440 // here, which will result in MultNode being mapped to a single MULT
441 // instruction node rather than a pair of MULT and MSUB instructions being
443 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
446 SDValue Chain = CurDAG->getEntryNode();
447 DebugLoc dl = SUBENode->getDebugLoc();
449 // create MipsSub(u) node
450 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
452 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
453 MultNode->getOperand(0),// Factor 0
454 MultNode->getOperand(1),// Factor 1
455 SUBCNode->getOperand(0),// Lo0
456 SUBENode->getOperand(0));// Hi0
458 // create CopyFromReg nodes
459 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
461 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
463 CopyFromLo.getValue(2));
465 // replace uses of sube and subc here
466 if (!SDValue(SUBCNode, 0).use_empty())
467 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
469 if (!SDValue(SUBENode, 0).use_empty())
470 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
475 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
476 TargetLowering::DAGCombinerInfo &DCI,
477 const MipsSubtarget* Subtarget) {
478 if (DCI.isBeforeLegalize())
481 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
483 return SDValue(N, 0);
488 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
489 TargetLowering::DAGCombinerInfo &DCI,
490 const MipsSubtarget* Subtarget) {
491 if (DCI.isBeforeLegalize())
494 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
496 return SDValue(N, 0);
501 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
502 TargetLowering::DAGCombinerInfo &DCI,
503 const MipsSubtarget* Subtarget) {
504 if (DCI.isBeforeLegalizeOps())
507 EVT Ty = N->getValueType(0);
508 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
509 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
510 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
512 DebugLoc dl = N->getDebugLoc();
514 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
515 N->getOperand(0), N->getOperand(1));
516 SDValue InChain = DAG.getEntryNode();
517 SDValue InGlue = DivRem;
520 if (N->hasAnyUseOfValue(0)) {
521 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
523 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
524 InChain = CopyFromLo.getValue(1);
525 InGlue = CopyFromLo.getValue(2);
529 if (N->hasAnyUseOfValue(1)) {
530 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
532 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
538 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
540 default: llvm_unreachable("Unknown fp condition code!");
542 case ISD::SETOEQ: return Mips::FCOND_OEQ;
543 case ISD::SETUNE: return Mips::FCOND_UNE;
545 case ISD::SETOLT: return Mips::FCOND_OLT;
547 case ISD::SETOGT: return Mips::FCOND_OGT;
549 case ISD::SETOLE: return Mips::FCOND_OLE;
551 case ISD::SETOGE: return Mips::FCOND_OGE;
552 case ISD::SETULT: return Mips::FCOND_ULT;
553 case ISD::SETULE: return Mips::FCOND_ULE;
554 case ISD::SETUGT: return Mips::FCOND_UGT;
555 case ISD::SETUGE: return Mips::FCOND_UGE;
556 case ISD::SETUO: return Mips::FCOND_UN;
557 case ISD::SETO: return Mips::FCOND_OR;
559 case ISD::SETONE: return Mips::FCOND_ONE;
560 case ISD::SETUEQ: return Mips::FCOND_UEQ;
565 // Returns true if condition code has to be inverted.
566 static bool InvertFPCondCode(Mips::CondCode CC) {
567 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
570 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
571 "Illegal Condition Code");
576 // Creates and returns an FPCmp node from a setcc node.
577 // Returns Op if setcc is not a floating point comparison.
578 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
579 // must be a SETCC node
580 if (Op.getOpcode() != ISD::SETCC)
583 SDValue LHS = Op.getOperand(0);
585 if (!LHS.getValueType().isFloatingPoint())
588 SDValue RHS = Op.getOperand(1);
589 DebugLoc dl = Op.getDebugLoc();
591 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
592 // node if necessary.
593 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
595 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
596 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
599 // Creates and returns a CMovFPT/F node.
600 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
601 SDValue False, DebugLoc DL) {
602 bool invert = InvertFPCondCode((Mips::CondCode)
603 cast<ConstantSDNode>(Cond.getOperand(2))
606 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
607 True.getValueType(), True, False, Cond);
610 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
611 TargetLowering::DAGCombinerInfo &DCI,
612 const MipsSubtarget* Subtarget) {
613 if (DCI.isBeforeLegalizeOps())
616 SDValue SetCC = N->getOperand(0);
618 if ((SetCC.getOpcode() != ISD::SETCC) ||
619 !SetCC.getOperand(0).getValueType().isInteger())
622 SDValue False = N->getOperand(2);
623 EVT FalseTy = False.getValueType();
625 if (!FalseTy.isInteger())
628 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
630 if (!CN || CN->getZExtValue())
633 const DebugLoc DL = N->getDebugLoc();
634 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
635 SDValue True = N->getOperand(1);
637 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
638 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
640 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
643 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
644 TargetLowering::DAGCombinerInfo &DCI,
645 const MipsSubtarget* Subtarget) {
646 // Pattern match EXT.
647 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
648 // => ext $dst, $src, size, pos
649 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
652 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
653 unsigned ShiftRightOpc = ShiftRight.getOpcode();
655 // Op's first operand must be a shift right.
656 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
659 // The second operand of the shift must be an immediate.
661 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
664 uint64_t Pos = CN->getZExtValue();
665 uint64_t SMPos, SMSize;
667 // Op's second operand must be a shifted mask.
668 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
669 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
672 // Return if the shifted mask does not start at bit 0 or the sum of its size
673 // and Pos exceeds the word's size.
674 EVT ValTy = N->getValueType(0);
675 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
678 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
679 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
680 DAG.getConstant(SMSize, MVT::i32));
683 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
684 TargetLowering::DAGCombinerInfo &DCI,
685 const MipsSubtarget* Subtarget) {
686 // Pattern match INS.
687 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
688 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
689 // => ins $dst, $src, size, pos, $src1
690 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
693 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
694 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
697 // See if Op's first operand matches (and $src1 , mask0).
698 if (And0.getOpcode() != ISD::AND)
701 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
702 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
705 // See if Op's second operand matches (and (shl $src, pos), mask1).
706 if (And1.getOpcode() != ISD::AND)
709 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
710 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
713 // The shift masks must have the same position and size.
714 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
717 SDValue Shl = And1.getOperand(0);
718 if (Shl.getOpcode() != ISD::SHL)
721 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
724 unsigned Shamt = CN->getZExtValue();
726 // Return if the shift amount and the first bit position of mask are not the
728 EVT ValTy = N->getValueType(0);
729 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
732 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
733 DAG.getConstant(SMPos0, MVT::i32),
734 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
737 static SDValue PerformADDCombine(SDNode *N, SelectionDAG& DAG,
738 TargetLowering::DAGCombinerInfo &DCI,
739 const MipsSubtarget* Subtarget) {
740 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
742 if (DCI.isBeforeLegalizeOps())
745 SDValue Add = N->getOperand(1);
747 if (Add.getOpcode() != ISD::ADD)
750 SDValue Lo = Add.getOperand(1);
752 if ((Lo.getOpcode() != MipsISD::Lo) ||
753 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
756 EVT ValTy = N->getValueType(0);
757 DebugLoc DL = N->getDebugLoc();
759 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
761 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
764 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
766 SelectionDAG &DAG = DCI.DAG;
767 unsigned opc = N->getOpcode();
772 return PerformADDECombine(N, DAG, DCI, Subtarget);
774 return PerformSUBECombine(N, DAG, DCI, Subtarget);
777 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
779 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
781 return PerformANDCombine(N, DAG, DCI, Subtarget);
783 return PerformORCombine(N, DAG, DCI, Subtarget);
785 return PerformADDCombine(N, DAG, DCI, Subtarget);
791 SDValue MipsTargetLowering::
792 LowerOperation(SDValue Op, SelectionDAG &DAG) const
794 switch (Op.getOpcode())
796 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
797 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
798 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
799 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
800 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
801 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
802 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
803 case ISD::SELECT: return LowerSELECT(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::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
810 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
811 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
812 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
813 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
814 case ISD::LOAD: return LowerLOAD(Op, DAG);
815 case ISD::STORE: return LowerSTORE(Op, DAG);
820 //===----------------------------------------------------------------------===//
821 // Lower helper functions
822 //===----------------------------------------------------------------------===//
824 // AddLiveIn - This helper function adds the specified physical register to the
825 // MachineFunction as a live in value. It also creates a corresponding
826 // virtual register for it.
828 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
830 assert(RC->contains(PReg) && "Not the correct regclass!");
831 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
832 MF.getRegInfo().addLiveIn(PReg, VReg);
836 // Get fp branch code (not opcode) from condition code.
837 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
838 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
839 return Mips::BRANCH_T;
841 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
842 "Invalid CondCode.");
844 return Mips::BRANCH_F;
848 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
850 const MipsSubtarget* Subtarget,
851 const TargetInstrInfo *TII,
852 bool isFPCmp, unsigned Opc) {
853 // There is no need to expand CMov instructions if target has
854 // conditional moves.
855 if (Subtarget->hasCondMov())
858 // To "insert" a SELECT_CC instruction, we actually have to insert the
859 // diamond control-flow pattern. The incoming instruction knows the
860 // destination vreg to set, the condition code register to branch on, the
861 // true/false values to select between, and a branch opcode to use.
862 const BasicBlock *LLVM_BB = BB->getBasicBlock();
863 MachineFunction::iterator It = BB;
870 // bNE r1, r0, copy1MBB
871 // fallthrough --> copy0MBB
872 MachineBasicBlock *thisMBB = BB;
873 MachineFunction *F = BB->getParent();
874 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
875 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
876 F->insert(It, copy0MBB);
877 F->insert(It, sinkMBB);
879 // Transfer the remainder of BB and its successor edges to sinkMBB.
880 sinkMBB->splice(sinkMBB->begin(), BB,
881 llvm::next(MachineBasicBlock::iterator(MI)),
883 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
885 // Next, add the true and fallthrough blocks as its successors.
886 BB->addSuccessor(copy0MBB);
887 BB->addSuccessor(sinkMBB);
889 // Emit the right instruction according to the type of the operands compared
891 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
893 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
894 .addReg(Mips::ZERO).addMBB(sinkMBB);
898 // # fallthrough to sinkMBB
901 // Update machine-CFG edges
902 BB->addSuccessor(sinkMBB);
905 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
910 BuildMI(*BB, BB->begin(), dl,
911 TII->get(Mips::PHI), MI->getOperand(0).getReg())
912 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
913 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
915 BuildMI(*BB, BB->begin(), dl,
916 TII->get(Mips::PHI), MI->getOperand(0).getReg())
917 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
918 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
920 MI->eraseFromParent(); // The pseudo instruction is gone now.
925 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
926 MachineBasicBlock *BB) const {
927 switch (MI->getOpcode()) {
928 default: llvm_unreachable("Unexpected instr type to insert");
929 case Mips::ATOMIC_LOAD_ADD_I8:
930 case Mips::ATOMIC_LOAD_ADD_I8_P8:
931 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
932 case Mips::ATOMIC_LOAD_ADD_I16:
933 case Mips::ATOMIC_LOAD_ADD_I16_P8:
934 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
935 case Mips::ATOMIC_LOAD_ADD_I32:
936 case Mips::ATOMIC_LOAD_ADD_I32_P8:
937 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
938 case Mips::ATOMIC_LOAD_ADD_I64:
939 case Mips::ATOMIC_LOAD_ADD_I64_P8:
940 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
942 case Mips::ATOMIC_LOAD_AND_I8:
943 case Mips::ATOMIC_LOAD_AND_I8_P8:
944 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
945 case Mips::ATOMIC_LOAD_AND_I16:
946 case Mips::ATOMIC_LOAD_AND_I16_P8:
947 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
948 case Mips::ATOMIC_LOAD_AND_I32:
949 case Mips::ATOMIC_LOAD_AND_I32_P8:
950 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
951 case Mips::ATOMIC_LOAD_AND_I64:
952 case Mips::ATOMIC_LOAD_AND_I64_P8:
953 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
955 case Mips::ATOMIC_LOAD_OR_I8:
956 case Mips::ATOMIC_LOAD_OR_I8_P8:
957 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
958 case Mips::ATOMIC_LOAD_OR_I16:
959 case Mips::ATOMIC_LOAD_OR_I16_P8:
960 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
961 case Mips::ATOMIC_LOAD_OR_I32:
962 case Mips::ATOMIC_LOAD_OR_I32_P8:
963 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
964 case Mips::ATOMIC_LOAD_OR_I64:
965 case Mips::ATOMIC_LOAD_OR_I64_P8:
966 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
968 case Mips::ATOMIC_LOAD_XOR_I8:
969 case Mips::ATOMIC_LOAD_XOR_I8_P8:
970 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
971 case Mips::ATOMIC_LOAD_XOR_I16:
972 case Mips::ATOMIC_LOAD_XOR_I16_P8:
973 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
974 case Mips::ATOMIC_LOAD_XOR_I32:
975 case Mips::ATOMIC_LOAD_XOR_I32_P8:
976 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
977 case Mips::ATOMIC_LOAD_XOR_I64:
978 case Mips::ATOMIC_LOAD_XOR_I64_P8:
979 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
981 case Mips::ATOMIC_LOAD_NAND_I8:
982 case Mips::ATOMIC_LOAD_NAND_I8_P8:
983 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
984 case Mips::ATOMIC_LOAD_NAND_I16:
985 case Mips::ATOMIC_LOAD_NAND_I16_P8:
986 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
987 case Mips::ATOMIC_LOAD_NAND_I32:
988 case Mips::ATOMIC_LOAD_NAND_I32_P8:
989 return EmitAtomicBinary(MI, BB, 4, 0, true);
990 case Mips::ATOMIC_LOAD_NAND_I64:
991 case Mips::ATOMIC_LOAD_NAND_I64_P8:
992 return EmitAtomicBinary(MI, BB, 8, 0, true);
994 case Mips::ATOMIC_LOAD_SUB_I8:
995 case Mips::ATOMIC_LOAD_SUB_I8_P8:
996 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
997 case Mips::ATOMIC_LOAD_SUB_I16:
998 case Mips::ATOMIC_LOAD_SUB_I16_P8:
999 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1000 case Mips::ATOMIC_LOAD_SUB_I32:
1001 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1002 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1003 case Mips::ATOMIC_LOAD_SUB_I64:
1004 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1005 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1007 case Mips::ATOMIC_SWAP_I8:
1008 case Mips::ATOMIC_SWAP_I8_P8:
1009 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1010 case Mips::ATOMIC_SWAP_I16:
1011 case Mips::ATOMIC_SWAP_I16_P8:
1012 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1013 case Mips::ATOMIC_SWAP_I32:
1014 case Mips::ATOMIC_SWAP_I32_P8:
1015 return EmitAtomicBinary(MI, BB, 4, 0);
1016 case Mips::ATOMIC_SWAP_I64:
1017 case Mips::ATOMIC_SWAP_I64_P8:
1018 return EmitAtomicBinary(MI, BB, 8, 0);
1020 case Mips::ATOMIC_CMP_SWAP_I8:
1021 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1022 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1023 case Mips::ATOMIC_CMP_SWAP_I16:
1024 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1025 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1026 case Mips::ATOMIC_CMP_SWAP_I32:
1027 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1028 return EmitAtomicCmpSwap(MI, BB, 4);
1029 case Mips::ATOMIC_CMP_SWAP_I64:
1030 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1031 return EmitAtomicCmpSwap(MI, BB, 8);
1035 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1036 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1038 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1039 unsigned Size, unsigned BinOpcode,
1041 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1043 MachineFunction *MF = BB->getParent();
1044 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1045 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1046 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1047 DebugLoc dl = MI->getDebugLoc();
1048 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1051 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1052 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1059 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1060 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1063 ZERO = Mips::ZERO_64;
1067 unsigned OldVal = MI->getOperand(0).getReg();
1068 unsigned Ptr = MI->getOperand(1).getReg();
1069 unsigned Incr = MI->getOperand(2).getReg();
1071 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1072 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1073 unsigned Success = RegInfo.createVirtualRegister(RC);
1075 // insert new blocks after the current block
1076 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1077 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1078 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1079 MachineFunction::iterator It = BB;
1081 MF->insert(It, loopMBB);
1082 MF->insert(It, exitMBB);
1084 // Transfer the remainder of BB and its successor edges to exitMBB.
1085 exitMBB->splice(exitMBB->begin(), BB,
1086 llvm::next(MachineBasicBlock::iterator(MI)),
1088 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1092 // fallthrough --> loopMBB
1093 BB->addSuccessor(loopMBB);
1094 loopMBB->addSuccessor(loopMBB);
1095 loopMBB->addSuccessor(exitMBB);
1098 // ll oldval, 0(ptr)
1099 // <binop> storeval, oldval, incr
1100 // sc success, storeval, 0(ptr)
1101 // beq success, $0, loopMBB
1103 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1105 // and andres, oldval, incr
1106 // nor storeval, $0, andres
1107 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1108 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1109 } else if (BinOpcode) {
1110 // <binop> storeval, oldval, incr
1111 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1115 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1116 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1118 MI->eraseFromParent(); // The instruction is gone now.
1124 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1125 MachineBasicBlock *BB,
1126 unsigned Size, unsigned BinOpcode,
1128 assert((Size == 1 || Size == 2) &&
1129 "Unsupported size for EmitAtomicBinaryPartial.");
1131 MachineFunction *MF = BB->getParent();
1132 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1133 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1134 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1135 DebugLoc dl = MI->getDebugLoc();
1136 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1137 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1139 unsigned Dest = MI->getOperand(0).getReg();
1140 unsigned Ptr = MI->getOperand(1).getReg();
1141 unsigned Incr = MI->getOperand(2).getReg();
1143 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1144 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1145 unsigned Mask = RegInfo.createVirtualRegister(RC);
1146 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1147 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1148 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1149 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1150 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1151 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1152 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1153 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1154 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1155 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1156 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1157 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1158 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1159 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1160 unsigned Success = RegInfo.createVirtualRegister(RC);
1162 // insert new blocks after the current block
1163 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1164 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1165 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1166 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1167 MachineFunction::iterator It = BB;
1169 MF->insert(It, loopMBB);
1170 MF->insert(It, sinkMBB);
1171 MF->insert(It, exitMBB);
1173 // Transfer the remainder of BB and its successor edges to exitMBB.
1174 exitMBB->splice(exitMBB->begin(), BB,
1175 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1176 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1178 BB->addSuccessor(loopMBB);
1179 loopMBB->addSuccessor(loopMBB);
1180 loopMBB->addSuccessor(sinkMBB);
1181 sinkMBB->addSuccessor(exitMBB);
1184 // addiu masklsb2,$0,-4 # 0xfffffffc
1185 // and alignedaddr,ptr,masklsb2
1186 // andi ptrlsb2,ptr,3
1187 // sll shiftamt,ptrlsb2,3
1188 // ori maskupper,$0,255 # 0xff
1189 // sll mask,maskupper,shiftamt
1190 // nor mask2,$0,mask
1191 // sll incr2,incr,shiftamt
1193 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1194 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1195 .addReg(Mips::ZERO).addImm(-4);
1196 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1197 .addReg(Ptr).addReg(MaskLSB2);
1198 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1199 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1200 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1201 .addReg(Mips::ZERO).addImm(MaskImm);
1202 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1203 .addReg(ShiftAmt).addReg(MaskUpper);
1204 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1205 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1207 // atomic.load.binop
1209 // ll oldval,0(alignedaddr)
1210 // binop binopres,oldval,incr2
1211 // and newval,binopres,mask
1212 // and maskedoldval0,oldval,mask2
1213 // or storeval,maskedoldval0,newval
1214 // sc success,storeval,0(alignedaddr)
1215 // beq success,$0,loopMBB
1219 // ll oldval,0(alignedaddr)
1220 // and newval,incr2,mask
1221 // and maskedoldval0,oldval,mask2
1222 // or storeval,maskedoldval0,newval
1223 // sc success,storeval,0(alignedaddr)
1224 // beq success,$0,loopMBB
1227 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1229 // and andres, oldval, incr2
1230 // nor binopres, $0, andres
1231 // and newval, binopres, mask
1232 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1233 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1234 .addReg(Mips::ZERO).addReg(AndRes);
1235 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1236 } else if (BinOpcode) {
1237 // <binop> binopres, oldval, incr2
1238 // and newval, binopres, mask
1239 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1240 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1241 } else {// atomic.swap
1242 // and newval, incr2, mask
1243 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1246 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1247 .addReg(OldVal).addReg(Mask2);
1248 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1249 .addReg(MaskedOldVal0).addReg(NewVal);
1250 BuildMI(BB, dl, TII->get(SC), Success)
1251 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1252 BuildMI(BB, dl, TII->get(Mips::BEQ))
1253 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1256 // and maskedoldval1,oldval,mask
1257 // srl srlres,maskedoldval1,shiftamt
1258 // sll sllres,srlres,24
1259 // sra dest,sllres,24
1261 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1263 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1264 .addReg(OldVal).addReg(Mask);
1265 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1266 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1267 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1268 .addReg(SrlRes).addImm(ShiftImm);
1269 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1270 .addReg(SllRes).addImm(ShiftImm);
1272 MI->eraseFromParent(); // The instruction is gone now.
1278 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1279 MachineBasicBlock *BB,
1280 unsigned Size) const {
1281 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1283 MachineFunction *MF = BB->getParent();
1284 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1285 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1286 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1287 DebugLoc dl = MI->getDebugLoc();
1288 unsigned LL, SC, ZERO, BNE, BEQ;
1291 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1292 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1298 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1299 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1300 ZERO = Mips::ZERO_64;
1305 unsigned Dest = MI->getOperand(0).getReg();
1306 unsigned Ptr = MI->getOperand(1).getReg();
1307 unsigned OldVal = MI->getOperand(2).getReg();
1308 unsigned NewVal = MI->getOperand(3).getReg();
1310 unsigned Success = RegInfo.createVirtualRegister(RC);
1312 // insert new blocks after the current block
1313 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1314 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1315 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1316 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1317 MachineFunction::iterator It = BB;
1319 MF->insert(It, loop1MBB);
1320 MF->insert(It, loop2MBB);
1321 MF->insert(It, exitMBB);
1323 // Transfer the remainder of BB and its successor edges to exitMBB.
1324 exitMBB->splice(exitMBB->begin(), BB,
1325 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1326 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1330 // fallthrough --> loop1MBB
1331 BB->addSuccessor(loop1MBB);
1332 loop1MBB->addSuccessor(exitMBB);
1333 loop1MBB->addSuccessor(loop2MBB);
1334 loop2MBB->addSuccessor(loop1MBB);
1335 loop2MBB->addSuccessor(exitMBB);
1339 // bne dest, oldval, exitMBB
1341 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1342 BuildMI(BB, dl, TII->get(BNE))
1343 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1346 // sc success, newval, 0(ptr)
1347 // beq success, $0, loop1MBB
1349 BuildMI(BB, dl, TII->get(SC), Success)
1350 .addReg(NewVal).addReg(Ptr).addImm(0);
1351 BuildMI(BB, dl, TII->get(BEQ))
1352 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1354 MI->eraseFromParent(); // The instruction is gone now.
1360 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1361 MachineBasicBlock *BB,
1362 unsigned Size) const {
1363 assert((Size == 1 || Size == 2) &&
1364 "Unsupported size for EmitAtomicCmpSwapPartial.");
1366 MachineFunction *MF = BB->getParent();
1367 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1368 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1369 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1370 DebugLoc dl = MI->getDebugLoc();
1371 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1372 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1374 unsigned Dest = MI->getOperand(0).getReg();
1375 unsigned Ptr = MI->getOperand(1).getReg();
1376 unsigned CmpVal = MI->getOperand(2).getReg();
1377 unsigned NewVal = MI->getOperand(3).getReg();
1379 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1380 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1381 unsigned Mask = RegInfo.createVirtualRegister(RC);
1382 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1383 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1384 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1385 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1386 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1387 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1388 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1389 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1390 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1391 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1392 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1393 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1394 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1395 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1396 unsigned Success = RegInfo.createVirtualRegister(RC);
1398 // insert new blocks after the current block
1399 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1400 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1401 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1402 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1403 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1404 MachineFunction::iterator It = BB;
1406 MF->insert(It, loop1MBB);
1407 MF->insert(It, loop2MBB);
1408 MF->insert(It, sinkMBB);
1409 MF->insert(It, exitMBB);
1411 // Transfer the remainder of BB and its successor edges to exitMBB.
1412 exitMBB->splice(exitMBB->begin(), BB,
1413 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1414 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1416 BB->addSuccessor(loop1MBB);
1417 loop1MBB->addSuccessor(sinkMBB);
1418 loop1MBB->addSuccessor(loop2MBB);
1419 loop2MBB->addSuccessor(loop1MBB);
1420 loop2MBB->addSuccessor(sinkMBB);
1421 sinkMBB->addSuccessor(exitMBB);
1423 // FIXME: computation of newval2 can be moved to loop2MBB.
1425 // addiu masklsb2,$0,-4 # 0xfffffffc
1426 // and alignedaddr,ptr,masklsb2
1427 // andi ptrlsb2,ptr,3
1428 // sll shiftamt,ptrlsb2,3
1429 // ori maskupper,$0,255 # 0xff
1430 // sll mask,maskupper,shiftamt
1431 // nor mask2,$0,mask
1432 // andi maskedcmpval,cmpval,255
1433 // sll shiftedcmpval,maskedcmpval,shiftamt
1434 // andi maskednewval,newval,255
1435 // sll shiftednewval,maskednewval,shiftamt
1436 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1437 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1438 .addReg(Mips::ZERO).addImm(-4);
1439 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1440 .addReg(Ptr).addReg(MaskLSB2);
1441 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1442 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1443 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1444 .addReg(Mips::ZERO).addImm(MaskImm);
1445 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1446 .addReg(ShiftAmt).addReg(MaskUpper);
1447 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1448 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1449 .addReg(CmpVal).addImm(MaskImm);
1450 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1451 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1452 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1453 .addReg(NewVal).addImm(MaskImm);
1454 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1455 .addReg(ShiftAmt).addReg(MaskedNewVal);
1458 // ll oldval,0(alginedaddr)
1459 // and maskedoldval0,oldval,mask
1460 // bne maskedoldval0,shiftedcmpval,sinkMBB
1462 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1463 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1464 .addReg(OldVal).addReg(Mask);
1465 BuildMI(BB, dl, TII->get(Mips::BNE))
1466 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1469 // and maskedoldval1,oldval,mask2
1470 // or storeval,maskedoldval1,shiftednewval
1471 // sc success,storeval,0(alignedaddr)
1472 // beq success,$0,loop1MBB
1474 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1475 .addReg(OldVal).addReg(Mask2);
1476 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1477 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1478 BuildMI(BB, dl, TII->get(SC), Success)
1479 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1480 BuildMI(BB, dl, TII->get(Mips::BEQ))
1481 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1484 // srl srlres,maskedoldval0,shiftamt
1485 // sll sllres,srlres,24
1486 // sra dest,sllres,24
1488 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1490 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1491 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1492 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1493 .addReg(SrlRes).addImm(ShiftImm);
1494 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1495 .addReg(SllRes).addImm(ShiftImm);
1497 MI->eraseFromParent(); // The instruction is gone now.
1502 //===----------------------------------------------------------------------===//
1503 // Misc Lower Operation implementation
1504 //===----------------------------------------------------------------------===//
1505 SDValue MipsTargetLowering::
1506 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1508 MachineFunction &MF = DAG.getMachineFunction();
1509 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1510 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1512 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1513 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1514 "Cannot lower if the alignment of the allocated space is larger than \
1515 that of the stack.");
1517 SDValue Chain = Op.getOperand(0);
1518 SDValue Size = Op.getOperand(1);
1519 DebugLoc dl = Op.getDebugLoc();
1521 // Get a reference from Mips stack pointer
1522 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1524 // Subtract the dynamic size from the actual stack size to
1525 // obtain the new stack size.
1526 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1528 // The Sub result contains the new stack start address, so it
1529 // must be placed in the stack pointer register.
1530 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1532 // This node always has two return values: a new stack pointer
1533 // value and a chain
1534 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1535 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1536 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1538 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1541 SDValue MipsTargetLowering::
1542 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1544 // The first operand is the chain, the second is the condition, the third is
1545 // the block to branch to if the condition is true.
1546 SDValue Chain = Op.getOperand(0);
1547 SDValue Dest = Op.getOperand(2);
1548 DebugLoc dl = Op.getDebugLoc();
1550 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1552 // Return if flag is not set by a floating point comparison.
1553 if (CondRes.getOpcode() != MipsISD::FPCmp)
1556 SDValue CCNode = CondRes.getOperand(2);
1558 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1559 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1561 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1565 SDValue MipsTargetLowering::
1566 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1568 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1570 // Return if flag is not set by a floating point comparison.
1571 if (Cond.getOpcode() != MipsISD::FPCmp)
1574 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1578 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1579 SDValue Cond = CreateFPCmp(DAG, Op);
1581 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1582 "Floating point operand expected.");
1584 SDValue True = DAG.getConstant(1, MVT::i32);
1585 SDValue False = DAG.getConstant(0, MVT::i32);
1587 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1590 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1591 SelectionDAG &DAG) const {
1592 // FIXME there isn't actually debug info here
1593 DebugLoc dl = Op.getDebugLoc();
1594 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1596 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1597 SDVTList VTs = DAG.getVTList(MVT::i32);
1599 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1601 // %gp_rel relocation
1602 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1603 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1605 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1606 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1607 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1609 // %hi/%lo relocation
1610 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1612 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1614 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1615 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1616 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1619 EVT ValTy = Op.getValueType();
1620 bool HasGotOfst = (GV->hasInternalLinkage() ||
1621 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1622 unsigned GotFlag = HasMips64 ?
1623 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1624 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1625 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1626 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1627 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1628 MachinePointerInfo(), false, false, false, 0);
1629 // On functions and global targets not internal linked only
1630 // a load from got/GP is necessary for PIC to work.
1633 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1634 HasMips64 ? MipsII::MO_GOT_OFST :
1636 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1637 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1640 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1641 SelectionDAG &DAG) const {
1642 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1643 // FIXME there isn't actually debug info here
1644 DebugLoc dl = Op.getDebugLoc();
1646 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1647 // %hi/%lo relocation
1648 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1649 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1650 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1651 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1652 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1655 EVT ValTy = Op.getValueType();
1656 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1657 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1658 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1659 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1660 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1661 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1662 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1663 MachinePointerInfo(), false, false, false, 0);
1664 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1665 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1668 SDValue MipsTargetLowering::
1669 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1671 // If the relocation model is PIC, use the General Dynamic TLS Model or
1672 // Local Dynamic TLS model, otherwise use the Initial Exec or
1673 // Local Exec TLS Model.
1675 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1676 DebugLoc dl = GA->getDebugLoc();
1677 const GlobalValue *GV = GA->getGlobal();
1678 EVT PtrVT = getPointerTy();
1680 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1682 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1683 // General Dynamic and Local Dynamic TLS Model.
1684 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1687 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1688 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1689 GetGlobalReg(DAG, PtrVT), TGA);
1690 unsigned PtrSize = PtrVT.getSizeInBits();
1691 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1693 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1697 Entry.Node = Argument;
1699 Args.push_back(Entry);
1701 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1702 false, false, false, false, 0, CallingConv::C,
1703 /*isTailCall=*/false, /*doesNotRet=*/false,
1704 /*isReturnValueUsed=*/true,
1705 TlsGetAddr, Args, DAG, dl);
1706 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1708 SDValue Ret = CallResult.first;
1710 if (model != TLSModel::LocalDynamic)
1713 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1714 MipsII::MO_DTPREL_HI);
1715 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1716 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1717 MipsII::MO_DTPREL_LO);
1718 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1719 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1720 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1724 if (model == TLSModel::InitialExec) {
1725 // Initial Exec TLS Model
1726 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1727 MipsII::MO_GOTTPREL);
1728 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1730 Offset = DAG.getLoad(PtrVT, dl,
1731 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1732 false, false, false, 0);
1734 // Local Exec TLS Model
1735 assert(model == TLSModel::LocalExec);
1736 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1737 MipsII::MO_TPREL_HI);
1738 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1739 MipsII::MO_TPREL_LO);
1740 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1741 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1742 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1745 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1746 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1749 SDValue MipsTargetLowering::
1750 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1752 SDValue HiPart, JTI, JTILo;
1753 // FIXME there isn't actually debug info here
1754 DebugLoc dl = Op.getDebugLoc();
1755 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1756 EVT PtrVT = Op.getValueType();
1757 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1759 if (!IsPIC && !IsN64) {
1760 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1761 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1762 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1763 } else {// Emit Load from Global Pointer
1764 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1765 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1766 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1767 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1769 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1770 MachinePointerInfo(), false, false, false, 0);
1771 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1774 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1775 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1778 SDValue MipsTargetLowering::
1779 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1782 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1783 const Constant *C = N->getConstVal();
1784 // FIXME there isn't actually debug info here
1785 DebugLoc dl = Op.getDebugLoc();
1787 // gp_rel relocation
1788 // FIXME: we should reference the constant pool using small data sections,
1789 // but the asm printer currently doesn't support this feature without
1790 // hacking it. This feature should come soon so we can uncomment the
1792 //if (IsInSmallSection(C->getType())) {
1793 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1794 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1795 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1797 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1798 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1799 N->getOffset(), MipsII::MO_ABS_HI);
1800 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1801 N->getOffset(), MipsII::MO_ABS_LO);
1802 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1803 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1804 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1806 EVT ValTy = Op.getValueType();
1807 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1808 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1809 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1810 N->getOffset(), GOTFlag);
1811 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1812 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1813 MachinePointerInfo::getConstantPool(), false,
1815 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1816 N->getOffset(), OFSTFlag);
1817 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1818 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1824 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1825 MachineFunction &MF = DAG.getMachineFunction();
1826 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1828 DebugLoc dl = Op.getDebugLoc();
1829 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1832 // vastart just stores the address of the VarArgsFrameIndex slot into the
1833 // memory location argument.
1834 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1835 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1836 MachinePointerInfo(SV), false, false, 0);
1839 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1840 EVT TyX = Op.getOperand(0).getValueType();
1841 EVT TyY = Op.getOperand(1).getValueType();
1842 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1843 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1844 DebugLoc DL = Op.getDebugLoc();
1847 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1849 SDValue X = (TyX == MVT::f32) ?
1850 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1851 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1853 SDValue Y = (TyY == MVT::f32) ?
1854 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1855 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1859 // ext E, Y, 31, 1 ; extract bit31 of Y
1860 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1861 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1862 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1865 // srl SrlX, SllX, 1
1867 // sll SllY, SrlX, 31
1868 // or Or, SrlX, SllY
1869 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1870 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1871 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1872 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1873 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1876 if (TyX == MVT::f32)
1877 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1879 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1880 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1881 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1884 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1885 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1886 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1887 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1888 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1889 DebugLoc DL = Op.getDebugLoc();
1891 // Bitcast to integer nodes.
1892 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1893 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1896 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1897 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1898 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1899 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1901 if (WidthX > WidthY)
1902 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1903 else if (WidthY > WidthX)
1904 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1906 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1907 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1908 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1911 // (d)sll SllX, X, 1
1912 // (d)srl SrlX, SllX, 1
1913 // (d)srl SrlY, Y, width(Y)-1
1914 // (d)sll SllY, SrlX, width(Y)-1
1915 // or Or, SrlX, SllY
1916 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1917 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1918 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1919 DAG.getConstant(WidthY - 1, MVT::i32));
1921 if (WidthX > WidthY)
1922 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1923 else if (WidthY > WidthX)
1924 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1926 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1927 DAG.getConstant(WidthX - 1, MVT::i32));
1928 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1929 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1933 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1934 if (Subtarget->hasMips64())
1935 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1937 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1940 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1941 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1942 DebugLoc DL = Op.getDebugLoc();
1944 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1946 SDValue X = (Op.getValueType() == MVT::f32) ?
1947 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1948 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1953 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1954 DAG.getRegister(Mips::ZERO, MVT::i32),
1955 DAG.getConstant(31, MVT::i32), Const1, X);
1957 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1958 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1961 if (Op.getValueType() == MVT::f32)
1962 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1964 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1965 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1966 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1969 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1970 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1971 DebugLoc DL = Op.getDebugLoc();
1973 // Bitcast to integer node.
1974 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1978 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1979 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1980 DAG.getConstant(63, MVT::i32), Const1, X);
1982 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1983 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1986 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1990 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
1991 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1992 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1994 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1997 SDValue MipsTargetLowering::
1998 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2000 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2001 "Frame address can only be determined for current frame.");
2003 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2004 MFI->setFrameAddressIsTaken(true);
2005 EVT VT = Op.getValueType();
2006 DebugLoc dl = Op.getDebugLoc();
2007 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2008 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2012 // TODO: set SType according to the desired memory barrier behavior.
2014 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
2016 DebugLoc dl = Op.getDebugLoc();
2017 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2018 DAG.getConstant(SType, MVT::i32));
2021 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2022 SelectionDAG& DAG) const {
2023 // FIXME: Need pseudo-fence for 'singlethread' fences
2024 // FIXME: Set SType for weaker fences where supported/appropriate.
2026 DebugLoc dl = Op.getDebugLoc();
2027 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2028 DAG.getConstant(SType, MVT::i32));
2031 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2032 SelectionDAG& DAG) const {
2033 DebugLoc DL = Op.getDebugLoc();
2034 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2035 SDValue Shamt = Op.getOperand(2);
2038 // lo = (shl lo, shamt)
2039 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2042 // hi = (shl lo, shamt[4:0])
2043 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2044 DAG.getConstant(-1, MVT::i32));
2045 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2046 DAG.getConstant(1, MVT::i32));
2047 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2049 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2050 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2051 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2052 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2053 DAG.getConstant(0x20, MVT::i32));
2054 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, DAG.getConstant(0, MVT::i32),
2056 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2058 SDValue Ops[2] = {Lo, Hi};
2059 return DAG.getMergeValues(Ops, 2, DL);
2062 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG& DAG,
2064 DebugLoc DL = Op.getDebugLoc();
2065 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2066 SDValue Shamt = Op.getOperand(2);
2069 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2071 // hi = (sra hi, shamt)
2073 // hi = (srl hi, shamt)
2076 // lo = (sra hi, shamt[4:0])
2077 // hi = (sra hi, 31)
2079 // lo = (srl hi, shamt[4:0])
2081 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2082 DAG.getConstant(-1, MVT::i32));
2083 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2084 DAG.getConstant(1, MVT::i32));
2085 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2086 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2087 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2088 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2090 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2091 DAG.getConstant(0x20, MVT::i32));
2092 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2093 DAG.getConstant(31, MVT::i32));
2094 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2095 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2096 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2099 SDValue Ops[2] = {Lo, Hi};
2100 return DAG.getMergeValues(Ops, 2, DL);
2103 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2104 SDValue Chain, SDValue Src, unsigned Offset) {
2105 SDValue Ptr = LD->getBasePtr();
2106 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2107 EVT BasePtrVT = Ptr.getValueType();
2108 DebugLoc DL = LD->getDebugLoc();
2109 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2112 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2113 DAG.getConstant(Offset, BasePtrVT));
2115 SDValue Ops[] = { Chain, Ptr, Src };
2116 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2117 LD->getMemOperand());
2120 // Expand an unaligned 32 or 64-bit integer load node.
2121 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2122 LoadSDNode *LD = cast<LoadSDNode>(Op);
2123 EVT MemVT = LD->getMemoryVT();
2125 // Return if load is aligned or if MemVT is neither i32 nor i64.
2126 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2127 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2130 bool IsLittle = Subtarget->isLittle();
2131 EVT VT = Op.getValueType();
2132 ISD::LoadExtType ExtType = LD->getExtensionType();
2133 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2135 assert((VT == MVT::i32) || (VT == MVT::i64));
2138 // (set dst, (i64 (load baseptr)))
2140 // (set tmp, (ldl (add baseptr, 7), undef))
2141 // (set dst, (ldr baseptr, tmp))
2142 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2143 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2145 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2149 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2151 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2155 // (set dst, (i32 (load baseptr))) or
2156 // (set dst, (i64 (sextload baseptr))) or
2157 // (set dst, (i64 (extload baseptr)))
2159 // (set tmp, (lwl (add baseptr, 3), undef))
2160 // (set dst, (lwr baseptr, tmp))
2161 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2162 (ExtType == ISD::EXTLOAD))
2165 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2168 // (set dst, (i64 (zextload baseptr)))
2170 // (set tmp0, (lwl (add baseptr, 3), undef))
2171 // (set tmp1, (lwr baseptr, tmp0))
2172 // (set tmp2, (shl tmp1, 32))
2173 // (set dst, (srl tmp2, 32))
2174 DebugLoc DL = LD->getDebugLoc();
2175 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2176 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2177 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2178 SDValue Ops[] = { SRL, LWR.getValue(1) };
2179 return DAG.getMergeValues(Ops, 2, DL);
2182 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2183 SDValue Chain, unsigned Offset) {
2184 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2185 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2186 DebugLoc DL = SD->getDebugLoc();
2187 SDVTList VTList = DAG.getVTList(MVT::Other);
2190 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2191 DAG.getConstant(Offset, BasePtrVT));
2193 SDValue Ops[] = { Chain, Value, Ptr };
2194 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2195 SD->getMemOperand());
2198 // Expand an unaligned 32 or 64-bit integer store node.
2199 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2200 StoreSDNode *SD = cast<StoreSDNode>(Op);
2201 EVT MemVT = SD->getMemoryVT();
2203 // Return if store is aligned or if MemVT is neither i32 nor i64.
2204 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2205 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2208 bool IsLittle = Subtarget->isLittle();
2209 SDValue Value = SD->getValue(), Chain = SD->getChain();
2210 EVT VT = Value.getValueType();
2213 // (store val, baseptr) or
2214 // (truncstore val, baseptr)
2216 // (swl val, (add baseptr, 3))
2217 // (swr val, baseptr)
2218 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2219 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2221 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2224 assert(VT == MVT::i64);
2227 // (store val, baseptr)
2229 // (sdl val, (add baseptr, 7))
2230 // (sdr val, baseptr)
2231 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2232 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2235 //===----------------------------------------------------------------------===//
2236 // Calling Convention Implementation
2237 //===----------------------------------------------------------------------===//
2239 //===----------------------------------------------------------------------===//
2240 // TODO: Implement a generic logic using tblgen that can support this.
2241 // Mips O32 ABI rules:
2243 // i32 - Passed in A0, A1, A2, A3 and stack
2244 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2245 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2246 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2247 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2248 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2251 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2252 //===----------------------------------------------------------------------===//
2254 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2255 MVT LocVT, CCValAssign::LocInfo LocInfo,
2256 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2258 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2260 static const uint16_t IntRegs[] = {
2261 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2263 static const uint16_t F32Regs[] = {
2264 Mips::F12, Mips::F14
2266 static const uint16_t F64Regs[] = {
2271 if (ArgFlags.isByVal()) {
2272 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2273 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2274 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2275 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2276 r < std::min(IntRegsSize, NextReg); ++r)
2277 State.AllocateReg(IntRegs[r]);
2281 // Promote i8 and i16
2282 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2284 if (ArgFlags.isSExt())
2285 LocInfo = CCValAssign::SExt;
2286 else if (ArgFlags.isZExt())
2287 LocInfo = CCValAssign::ZExt;
2289 LocInfo = CCValAssign::AExt;
2294 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2295 // is true: function is vararg, argument is 3rd or higher, there is previous
2296 // argument which is not f32 or f64.
2297 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2298 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2299 unsigned OrigAlign = ArgFlags.getOrigAlign();
2300 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2302 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2303 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2304 // If this is the first part of an i64 arg,
2305 // the allocated register must be either A0 or A2.
2306 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2307 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2309 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2310 // Allocate int register and shadow next int register. If first
2311 // available register is Mips::A1 or Mips::A3, shadow it too.
2312 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2313 if (Reg == Mips::A1 || Reg == Mips::A3)
2314 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2315 State.AllocateReg(IntRegs, IntRegsSize);
2317 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2318 // we are guaranteed to find an available float register
2319 if (ValVT == MVT::f32) {
2320 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2321 // Shadow int register
2322 State.AllocateReg(IntRegs, IntRegsSize);
2324 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2325 // Shadow int registers
2326 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2327 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2328 State.AllocateReg(IntRegs, IntRegsSize);
2329 State.AllocateReg(IntRegs, IntRegsSize);
2332 llvm_unreachable("Cannot handle this ValVT.");
2334 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2335 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2338 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2340 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2342 return false; // CC must always match
2345 static const uint16_t Mips64IntRegs[8] =
2346 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2347 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2348 static const uint16_t Mips64DPRegs[8] =
2349 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2350 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2352 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2353 CCValAssign::LocInfo LocInfo,
2354 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2355 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2356 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
2357 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2359 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2361 // If byval is 16-byte aligned, the first arg register must be even.
2362 if ((Align == 16) && (FirstIdx % 2)) {
2363 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2367 // Mark the registers allocated.
2368 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2369 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2371 // Allocate space on caller's stack.
2372 unsigned Offset = State.AllocateStack(Size, Align);
2375 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2378 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2383 #include "MipsGenCallingConv.inc"
2386 AnalyzeMips64CallOperands(CCState &CCInfo,
2387 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2388 unsigned NumOps = Outs.size();
2389 for (unsigned i = 0; i != NumOps; ++i) {
2390 MVT ArgVT = Outs[i].VT;
2391 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2394 if (Outs[i].IsFixed)
2395 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2397 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2401 dbgs() << "Call operand #" << i << " has unhandled type "
2402 << EVT(ArgVT).getEVTString();
2404 llvm_unreachable(0);
2409 //===----------------------------------------------------------------------===//
2410 // Call Calling Convention Implementation
2411 //===----------------------------------------------------------------------===//
2413 static const unsigned O32IntRegsSize = 4;
2415 static const uint16_t O32IntRegs[] = {
2416 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2419 // Return next O32 integer argument register.
2420 static unsigned getNextIntArgReg(unsigned Reg) {
2421 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2422 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2425 // Write ByVal Arg to arg registers and stack.
2427 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2428 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2429 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2430 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2431 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2432 MVT PtrType, bool isLittle) {
2433 unsigned LocMemOffset = VA.getLocMemOffset();
2434 unsigned Offset = 0;
2435 uint32_t RemainingSize = Flags.getByValSize();
2436 unsigned ByValAlign = Flags.getByValAlign();
2438 // Copy the first 4 words of byval arg to registers A0 - A3.
2439 // FIXME: Use a stricter alignment if it enables better optimization in passes
2441 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2442 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2443 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2444 DAG.getConstant(Offset, MVT::i32));
2445 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2446 MachinePointerInfo(), false, false, false,
2447 std::min(ByValAlign, (unsigned )4));
2448 MemOpChains.push_back(LoadVal.getValue(1));
2449 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2450 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2453 if (RemainingSize == 0)
2456 // If there still is a register available for argument passing, write the
2457 // remaining part of the structure to it using subword loads and shifts.
2458 if (LocMemOffset < 4 * 4) {
2459 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2460 "There must be one to three bytes remaining.");
2461 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2462 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2463 DAG.getConstant(Offset, MVT::i32));
2464 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2465 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2466 LoadPtr, MachinePointerInfo(),
2467 MVT::getIntegerVT(LoadSize * 8), false,
2469 MemOpChains.push_back(LoadVal.getValue(1));
2471 // If target is big endian, shift it to the most significant half-word or
2474 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2475 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2478 RemainingSize -= LoadSize;
2480 // Read second subword if necessary.
2481 if (RemainingSize != 0) {
2482 assert(RemainingSize == 1 && "There must be one byte remaining.");
2483 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2484 DAG.getConstant(Offset, MVT::i32));
2485 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2486 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2487 LoadPtr, MachinePointerInfo(),
2488 MVT::i8, false, false, Alignment);
2489 MemOpChains.push_back(Subword.getValue(1));
2490 // Insert the loaded byte to LoadVal.
2491 // FIXME: Use INS if supported by target.
2492 unsigned ShiftAmt = isLittle ? 16 : 8;
2493 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2494 DAG.getConstant(ShiftAmt, MVT::i32));
2495 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2498 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2499 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2503 // Create a fixed object on stack at offset LocMemOffset and copy
2504 // remaining part of byval arg to it using memcpy.
2505 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2506 DAG.getConstant(Offset, MVT::i32));
2507 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2508 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2509 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2510 DAG.getConstant(RemainingSize, MVT::i32),
2511 std::min(ByValAlign, (unsigned)4),
2512 /*isVolatile=*/false, /*AlwaysInline=*/false,
2513 MachinePointerInfo(0), MachinePointerInfo(0));
2516 // Copy Mips64 byVal arg to registers and stack.
2518 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2519 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2520 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2521 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2522 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2523 EVT PtrTy, bool isLittle) {
2524 unsigned ByValSize = Flags.getByValSize();
2525 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2526 bool IsRegLoc = VA.isRegLoc();
2527 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2528 unsigned LocMemOffset = 0;
2529 unsigned MemCpySize = ByValSize;
2532 LocMemOffset = VA.getLocMemOffset();
2534 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2536 const uint16_t *RegEnd = Mips64IntRegs + 8;
2538 // Copy double words to registers.
2539 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2540 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2541 DAG.getConstant(Offset, PtrTy));
2542 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2543 MachinePointerInfo(), false, false, false,
2545 MemOpChains.push_back(LoadVal.getValue(1));
2546 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2549 // Return if the struct has been fully copied.
2550 if (!(MemCpySize = ByValSize - Offset))
2553 // If there is an argument register available, copy the remainder of the
2554 // byval argument with sub-doubleword loads and shifts.
2555 if (Reg != RegEnd) {
2556 assert((ByValSize < Offset + 8) &&
2557 "Size of the remainder should be smaller than 8-byte.");
2559 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2560 unsigned RemSize = ByValSize - Offset;
2562 if (RemSize < LoadSize)
2565 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2566 DAG.getConstant(Offset, PtrTy));
2568 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2569 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2570 false, false, Alignment);
2571 MemOpChains.push_back(LoadVal.getValue(1));
2573 // Offset in number of bits from double word boundary.
2574 unsigned OffsetDW = (Offset % 8) * 8;
2575 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2576 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2577 DAG.getConstant(Shamt, MVT::i32));
2579 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2582 Alignment = std::min(Alignment, LoadSize);
2585 RegsToPass.push_back(std::make_pair(*Reg, Val));
2590 assert(MemCpySize && "MemCpySize must not be zero.");
2592 // Create a fixed object on stack at offset LocMemOffset and copy
2593 // remainder of byval arg to it with memcpy.
2594 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2595 DAG.getConstant(Offset, PtrTy));
2596 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2597 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2598 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2599 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2600 /*isVolatile=*/false, /*AlwaysInline=*/false,
2601 MachinePointerInfo(0), MachinePointerInfo(0));
2604 /// LowerCall - functions arguments are copied from virtual regs to
2605 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2606 /// TODO: isTailCall.
2608 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2609 SmallVectorImpl<SDValue> &InVals) const {
2610 SelectionDAG &DAG = CLI.DAG;
2611 DebugLoc &dl = CLI.DL;
2612 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2613 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2614 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2615 SDValue InChain = CLI.Chain;
2616 SDValue Callee = CLI.Callee;
2617 bool &isTailCall = CLI.IsTailCall;
2618 CallingConv::ID CallConv = CLI.CallConv;
2619 bool isVarArg = CLI.IsVarArg;
2621 // MIPs target does not yet support tail call optimization.
2624 MachineFunction &MF = DAG.getMachineFunction();
2625 MachineFrameInfo *MFI = MF.getFrameInfo();
2626 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2627 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2628 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2630 // Analyze operands of the call, assigning locations to each operand.
2631 SmallVector<CCValAssign, 16> ArgLocs;
2632 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2633 getTargetMachine(), ArgLocs, *DAG.getContext());
2635 if (CallConv == CallingConv::Fast)
2636 CCInfo.AnalyzeCallOperands(Outs, CC_Mips_FastCC);
2638 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2640 AnalyzeMips64CallOperands(CCInfo, Outs);
2642 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2644 // Get a count of how many bytes are to be pushed on the stack.
2645 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2647 // Chain is the output chain of the last Load/Store or CopyToReg node.
2648 // ByValChain is the output chain of the last Memcpy node created for copying
2649 // byval arguments to the stack.
2650 SDValue Chain, CallSeqStart, ByValChain;
2651 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2652 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2653 ByValChain = InChain;
2655 // Get the frame index of the stack frame object that points to the location
2656 // of dynamically allocated area on the stack.
2657 int DynAllocFI = MipsFI->getDynAllocFI();
2659 // Update size of the maximum argument space.
2660 // For O32, a minimum of four words (16 bytes) of argument space is
2662 if (IsO32 && (CallConv != CallingConv::Fast))
2663 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2665 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2667 if (MaxCallFrameSize < NextStackOffset) {
2668 MipsFI->setMaxCallFrameSize(NextStackOffset);
2670 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2671 // allocated stack space. These offsets must be aligned to a boundary
2672 // determined by the stack alignment of the ABI.
2673 unsigned StackAlignment = TFL->getStackAlignment();
2674 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2675 StackAlignment * StackAlignment;
2677 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2680 // With EABI is it possible to have 16 args on registers.
2681 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2682 SmallVector<SDValue, 8> MemOpChains;
2684 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2686 // Walk the register/memloc assignments, inserting copies/loads.
2687 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2688 SDValue Arg = OutVals[i];
2689 CCValAssign &VA = ArgLocs[i];
2690 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2691 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2694 if (Flags.isByVal()) {
2695 assert(Flags.getByValSize() &&
2696 "ByVal args of size 0 should have been ignored by front-end.");
2698 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2699 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2700 Subtarget->isLittle());
2702 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2703 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2704 Subtarget->isLittle());
2708 // Promote the value if needed.
2709 switch (VA.getLocInfo()) {
2710 default: llvm_unreachable("Unknown loc info!");
2711 case CCValAssign::Full:
2712 if (VA.isRegLoc()) {
2713 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2714 (ValVT == MVT::f64 && LocVT == MVT::i64))
2715 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2716 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2717 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2718 Arg, DAG.getConstant(0, MVT::i32));
2719 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2720 Arg, DAG.getConstant(1, MVT::i32));
2721 if (!Subtarget->isLittle())
2723 unsigned LocRegLo = VA.getLocReg();
2724 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2725 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2726 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2731 case CCValAssign::SExt:
2732 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2734 case CCValAssign::ZExt:
2735 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2737 case CCValAssign::AExt:
2738 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2742 // Arguments that can be passed on register must be kept at
2743 // RegsToPass vector
2744 if (VA.isRegLoc()) {
2745 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2749 // Register can't get to this point...
2750 assert(VA.isMemLoc());
2752 // Create the frame index object for this incoming parameter
2753 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2754 VA.getLocMemOffset(), true);
2755 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2757 // emit ISD::STORE whichs stores the
2758 // parameter value to a stack Location
2759 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2760 MachinePointerInfo(), false, false, 0));
2763 // Extend range of indices of frame objects for outgoing arguments that were
2764 // created during this function call. Skip this step if no such objects were
2767 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2769 // If a memcpy has been created to copy a byval arg to a stack, replace the
2770 // chain input of CallSeqStart with ByValChain.
2771 if (InChain != ByValChain)
2772 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2773 NextStackOffsetVal);
2775 // Transform all store nodes into one single node because all store
2776 // nodes are independent of each other.
2777 if (!MemOpChains.empty())
2778 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2779 &MemOpChains[0], MemOpChains.size());
2781 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2782 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2783 // node so that legalize doesn't hack it.
2784 unsigned char OpFlag;
2785 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2786 bool GlobalOrExternal = false;
2789 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2790 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2791 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2792 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2793 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2795 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2798 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2799 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2800 getPointerTy(), 0, OpFlag);
2803 GlobalOrExternal = true;
2805 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2806 if (IsN64 || (!IsO32 && IsPIC))
2807 OpFlag = MipsII::MO_GOT_DISP;
2808 else if (!IsPIC) // !N64 && static
2809 OpFlag = MipsII::MO_NO_FLAG;
2811 OpFlag = MipsII::MO_GOT_CALL;
2812 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2814 GlobalOrExternal = true;
2819 // Create nodes that load address of callee and copy it to T9
2821 if (GlobalOrExternal) {
2822 // Load callee address
2823 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2824 GetGlobalReg(DAG, getPointerTy()), Callee);
2825 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2826 Callee, MachinePointerInfo::getGOT(),
2827 false, false, false, 0);
2829 // Use GOT+LO if callee has internal linkage.
2830 if (CalleeLo.getNode()) {
2831 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2832 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2838 // T9 should contain the address of the callee function if
2839 // -reloction-model=pic or it is an indirect call.
2840 if (IsPICCall || !GlobalOrExternal) {
2842 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2843 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2844 InFlag = Chain.getValue(1);
2845 Callee = DAG.getRegister(T9Reg, getPointerTy());
2848 // Insert node "GP copy globalreg" before call to function.
2849 // Lazy-binding stubs require GP to point to the GOT.
2851 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2852 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2853 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2856 // Build a sequence of copy-to-reg nodes chained together with token
2857 // chain and flag operands which copy the outgoing args into registers.
2858 // The InFlag in necessary since all emitted instructions must be
2860 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2861 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2862 RegsToPass[i].second, InFlag);
2863 InFlag = Chain.getValue(1);
2866 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2867 // = Chain, Callee, Reg#1, Reg#2, ...
2869 // Returns a chain & a flag for retval copy to use.
2870 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2871 SmallVector<SDValue, 8> Ops;
2872 Ops.push_back(Chain);
2873 Ops.push_back(Callee);
2875 // Add argument registers to the end of the list so that they are
2876 // known live into the call.
2877 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2878 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2879 RegsToPass[i].second.getValueType()));
2881 // Add a register mask operand representing the call-preserved registers.
2882 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2883 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2884 assert(Mask && "Missing call preserved mask for calling convention");
2885 Ops.push_back(DAG.getRegisterMask(Mask));
2887 if (InFlag.getNode())
2888 Ops.push_back(InFlag);
2890 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2891 InFlag = Chain.getValue(1);
2893 // Create the CALLSEQ_END node.
2894 Chain = DAG.getCALLSEQ_END(Chain,
2895 DAG.getIntPtrConstant(NextStackOffset, true),
2896 DAG.getIntPtrConstant(0, true), InFlag);
2897 InFlag = Chain.getValue(1);
2899 // Handle result values, copying them out of physregs into vregs that we
2901 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902 Ins, dl, DAG, InVals);
2905 /// LowerCallResult - Lower the result values of a call into the
2906 /// appropriate copies out of appropriate physical registers.
2908 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2909 CallingConv::ID CallConv, bool isVarArg,
2910 const SmallVectorImpl<ISD::InputArg> &Ins,
2911 DebugLoc dl, SelectionDAG &DAG,
2912 SmallVectorImpl<SDValue> &InVals) const {
2913 // Assign locations to each value returned by this call.
2914 SmallVector<CCValAssign, 16> RVLocs;
2915 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2916 getTargetMachine(), RVLocs, *DAG.getContext());
2918 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2920 // Copy all of the result registers out of their specified physreg.
2921 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2922 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2923 RVLocs[i].getValVT(), InFlag).getValue(1);
2924 InFlag = Chain.getValue(2);
2925 InVals.push_back(Chain.getValue(0));
2931 //===----------------------------------------------------------------------===//
2932 // Formal Arguments Calling Convention Implementation
2933 //===----------------------------------------------------------------------===//
2934 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2935 std::vector<SDValue>& OutChains,
2936 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2937 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2938 const Argument *FuncArg) {
2939 unsigned LocMem = VA.getLocMemOffset();
2940 unsigned FirstWord = LocMem / 4;
2942 // copy register A0 - A3 to frame object
2943 for (unsigned i = 0; i < NumWords; ++i) {
2944 unsigned CurWord = FirstWord + i;
2945 if (CurWord >= O32IntRegsSize)
2948 unsigned SrcReg = O32IntRegs[CurWord];
2949 unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
2950 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2951 DAG.getConstant(i * 4, MVT::i32));
2952 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2953 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2955 OutChains.push_back(Store);
2959 // Create frame object on stack and copy registers used for byval passing to it.
2961 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2962 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2963 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2964 MachineFrameInfo *MFI, bool IsRegLoc,
2965 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2966 EVT PtrTy, const Argument *FuncArg) {
2967 const uint16_t *Reg = Mips64IntRegs + 8;
2968 int FOOffset; // Frame object offset from virtual frame pointer.
2971 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2972 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2975 FOOffset = VA.getLocMemOffset();
2977 // Create frame object.
2978 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2979 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2980 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2981 InVals.push_back(FIN);
2983 // Copy arg registers.
2984 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2986 unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
2987 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2988 DAG.getConstant(I * 8, PtrTy));
2989 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2990 StorePtr, MachinePointerInfo(FuncArg, I * 8),
2992 OutChains.push_back(Store);
2998 /// LowerFormalArguments - transform physical registers into virtual registers
2999 /// and generate load operations for arguments places on the stack.
3001 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3002 CallingConv::ID CallConv,
3004 const SmallVectorImpl<ISD::InputArg> &Ins,
3005 DebugLoc dl, SelectionDAG &DAG,
3006 SmallVectorImpl<SDValue> &InVals)
3008 MachineFunction &MF = DAG.getMachineFunction();
3009 MachineFrameInfo *MFI = MF.getFrameInfo();
3010 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3012 MipsFI->setVarArgsFrameIndex(0);
3014 // Used with vargs to acumulate store chains.
3015 std::vector<SDValue> OutChains;
3017 // Assign locations to all of the incoming arguments.
3018 SmallVector<CCValAssign, 16> ArgLocs;
3019 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3020 getTargetMachine(), ArgLocs, *DAG.getContext());
3022 if (CallConv == CallingConv::Fast)
3023 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FastCC);
3025 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
3027 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
3029 Function::const_arg_iterator FuncArg =
3030 DAG.getMachineFunction().getFunction()->arg_begin();
3031 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
3033 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
3034 CCValAssign &VA = ArgLocs[i];
3035 EVT ValVT = VA.getValVT();
3036 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3037 bool IsRegLoc = VA.isRegLoc();
3039 if (Flags.isByVal()) {
3040 assert(Flags.getByValSize() &&
3041 "ByVal args of size 0 should have been ignored by front-end.");
3043 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
3044 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
3046 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3047 InVals.push_back(FIN);
3048 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
3051 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
3052 MFI, IsRegLoc, InVals, MipsFI,
3053 getPointerTy(), &*FuncArg);
3057 // Arguments stored on registers
3059 EVT RegVT = VA.getLocVT();
3060 unsigned ArgReg = VA.getLocReg();
3061 const TargetRegisterClass *RC;
3063 if (RegVT == MVT::i32)
3064 RC = &Mips::CPURegsRegClass;
3065 else if (RegVT == MVT::i64)
3066 RC = &Mips::CPU64RegsRegClass;
3067 else if (RegVT == MVT::f32)
3068 RC = &Mips::FGR32RegClass;
3069 else if (RegVT == MVT::f64)
3070 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3072 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3074 // Transform the arguments stored on
3075 // physical registers into virtual ones
3076 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3077 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3079 // If this is an 8 or 16-bit value, it has been passed promoted
3080 // to 32 bits. Insert an assert[sz]ext to capture this, then
3081 // truncate to the right size.
3082 if (VA.getLocInfo() != CCValAssign::Full) {
3083 unsigned Opcode = 0;
3084 if (VA.getLocInfo() == CCValAssign::SExt)
3085 Opcode = ISD::AssertSext;
3086 else if (VA.getLocInfo() == CCValAssign::ZExt)
3087 Opcode = ISD::AssertZext;
3089 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3090 DAG.getValueType(ValVT));
3091 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3094 // Handle floating point arguments passed in integer registers.
3095 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3096 (RegVT == MVT::i64 && ValVT == MVT::f64))
3097 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3098 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3099 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3100 getNextIntArgReg(ArgReg), RC);
3101 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3102 if (!Subtarget->isLittle())
3103 std::swap(ArgValue, ArgValue2);
3104 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3105 ArgValue, ArgValue2);
3108 InVals.push_back(ArgValue);
3109 } else { // VA.isRegLoc()
3112 assert(VA.isMemLoc());
3114 // The stack pointer offset is relative to the caller stack frame.
3115 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3116 VA.getLocMemOffset(), true);
3118 // Create load nodes to retrieve arguments from the stack
3119 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3120 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3121 MachinePointerInfo::getFixedStack(LastFI),
3122 false, false, false, 0));
3126 // The mips ABIs for returning structs by value requires that we copy
3127 // the sret argument into $v0 for the return. Save the argument into
3128 // a virtual register so that we can access it from the return points.
3129 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3130 unsigned Reg = MipsFI->getSRetReturnReg();
3132 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
3133 MipsFI->setSRetReturnReg(Reg);
3135 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3136 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3140 unsigned NumOfRegs = IsO32 ? 4 : 8;
3141 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
3142 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
3143 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
3144 const TargetRegisterClass *RC = IsO32 ?
3145 (const TargetRegisterClass*)&Mips::CPURegsRegClass :
3146 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
3147 unsigned RegSize = RC->getSize();
3148 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
3150 // Offset of the first variable argument from stack pointer.
3151 int FirstVaArgOffset;
3153 if (IsO32 || (Idx == NumOfRegs)) {
3155 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
3157 FirstVaArgOffset = RegSlotOffset;
3159 // Record the frame index of the first variable argument
3160 // which is a value necessary to VASTART.
3161 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
3162 MipsFI->setVarArgsFrameIndex(LastFI);
3164 // Copy the integer registers that have not been used for argument passing
3165 // to the argument register save area. For O32, the save area is allocated
3166 // in the caller's stack frame, while for N32/64, it is allocated in the
3167 // callee's stack frame.
3168 for (int StackOffset = RegSlotOffset;
3169 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
3170 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
3171 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3172 MVT::getIntegerVT(RegSize * 8));
3173 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
3174 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
3175 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
3176 MachinePointerInfo(), false, false, 0));
3180 MipsFI->setLastInArgFI(LastFI);
3182 // All stores are grouped in one node to allow the matching between
3183 // the size of Ins and InVals. This only happens when on varg functions
3184 if (!OutChains.empty()) {
3185 OutChains.push_back(Chain);
3186 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3187 &OutChains[0], OutChains.size());
3193 //===----------------------------------------------------------------------===//
3194 // Return Value Calling Convention Implementation
3195 //===----------------------------------------------------------------------===//
3198 MipsTargetLowering::LowerReturn(SDValue Chain,
3199 CallingConv::ID CallConv, bool isVarArg,
3200 const SmallVectorImpl<ISD::OutputArg> &Outs,
3201 const SmallVectorImpl<SDValue> &OutVals,
3202 DebugLoc dl, SelectionDAG &DAG) const {
3204 // CCValAssign - represent the assignment of
3205 // the return value to a location
3206 SmallVector<CCValAssign, 16> RVLocs;
3208 // CCState - Info about the registers and stack slot.
3209 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3210 getTargetMachine(), RVLocs, *DAG.getContext());
3212 // Analize return values.
3213 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3215 // If this is the first return lowered for this function, add
3216 // the regs to the liveout set for the function.
3217 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3218 for (unsigned i = 0; i != RVLocs.size(); ++i)
3219 if (RVLocs[i].isRegLoc())
3220 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3225 // Copy the result values into the output registers.
3226 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3227 CCValAssign &VA = RVLocs[i];
3228 assert(VA.isRegLoc() && "Can only return in registers!");
3230 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3232 // guarantee that all emitted copies are
3233 // stuck together, avoiding something bad
3234 Flag = Chain.getValue(1);
3237 // The mips ABIs for returning structs by value requires that we copy
3238 // the sret argument into $v0 for the return. We saved the argument into
3239 // a virtual register in the entry block, so now we copy the value out
3241 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3242 MachineFunction &MF = DAG.getMachineFunction();
3243 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3244 unsigned Reg = MipsFI->getSRetReturnReg();
3247 llvm_unreachable("sret virtual register not created in the entry block");
3248 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3250 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3251 Flag = Chain.getValue(1);
3254 // Return on Mips is always a "jr $ra"
3256 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3257 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
3259 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3260 Chain, DAG.getRegister(Mips::RA, MVT::i32));
3263 //===----------------------------------------------------------------------===//
3264 // Mips Inline Assembly Support
3265 //===----------------------------------------------------------------------===//
3267 /// getConstraintType - Given a constraint letter, return the type of
3268 /// constraint it is for this target.
3269 MipsTargetLowering::ConstraintType MipsTargetLowering::
3270 getConstraintType(const std::string &Constraint) const
3272 // Mips specific constrainy
3273 // GCC config/mips/constraints.md
3275 // 'd' : An address register. Equivalent to r
3276 // unless generating MIPS16 code.
3277 // 'y' : Equivalent to r; retained for
3278 // backwards compatibility.
3279 // 'c' : A register suitable for use in an indirect
3280 // jump. This will always be $25 for -mabicalls.
3281 // 'l' : The lo register. 1 word storage.
3282 // 'x' : The hilo register pair. Double word storage.
3283 if (Constraint.size() == 1) {
3284 switch (Constraint[0]) {
3292 return C_RegisterClass;
3295 return TargetLowering::getConstraintType(Constraint);
3298 /// Examine constraint type and operand type and determine a weight value.
3299 /// This object must already have been set up with the operand type
3300 /// and the current alternative constraint selected.
3301 TargetLowering::ConstraintWeight
3302 MipsTargetLowering::getSingleConstraintMatchWeight(
3303 AsmOperandInfo &info, const char *constraint) const {
3304 ConstraintWeight weight = CW_Invalid;
3305 Value *CallOperandVal = info.CallOperandVal;
3306 // If we don't have a value, we can't do a match,
3307 // but allow it at the lowest weight.
3308 if (CallOperandVal == NULL)
3310 Type *type = CallOperandVal->getType();
3311 // Look at the constraint type.
3312 switch (*constraint) {
3314 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3318 if (type->isIntegerTy())
3319 weight = CW_Register;
3322 if (type->isFloatTy())
3323 weight = CW_Register;
3325 case 'c': // $25 for indirect jumps
3326 case 'l': // lo register
3327 case 'x': // hilo register pair
3328 if (type->isIntegerTy())
3329 weight = CW_SpecificReg;
3331 case 'I': // signed 16 bit immediate
3332 case 'J': // integer zero
3333 case 'K': // unsigned 16 bit immediate
3334 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3335 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3336 case 'O': // signed 15 bit immediate (+- 16383)
3337 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3338 if (isa<ConstantInt>(CallOperandVal))
3339 weight = CW_Constant;
3345 /// Given a register class constraint, like 'r', if this corresponds directly
3346 /// to an LLVM register class, return a register of 0 and the register class
3348 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3349 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3351 if (Constraint.size() == 1) {
3352 switch (Constraint[0]) {
3353 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3354 case 'y': // Same as 'r'. Exists for compatibility.
3356 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3357 return std::make_pair(0U, &Mips::CPURegsRegClass);
3358 if (VT == MVT::i64 && HasMips64)
3359 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3360 // This will generate an error message
3361 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3364 return std::make_pair(0U, &Mips::FGR32RegClass);
3365 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3366 if (Subtarget->isFP64bit())
3367 return std::make_pair(0U, &Mips::FGR64RegClass);
3368 return std::make_pair(0U, &Mips::AFGR64RegClass);
3371 case 'c': // register suitable for indirect jump
3373 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3374 assert(VT == MVT::i64 && "Unexpected type.");
3375 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3376 case 'l': // register suitable for indirect jump
3378 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3379 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3380 case 'x': // register suitable for indirect jump
3381 // Fixme: Not triggering the use of both hi and low
3382 // This will generate an error message
3383 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3386 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3389 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3390 /// vector. If it is invalid, don't add anything to Ops.
3391 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3392 std::string &Constraint,
3393 std::vector<SDValue>&Ops,
3394 SelectionDAG &DAG) const {
3395 SDValue Result(0, 0);
3397 // Only support length 1 constraints for now.
3398 if (Constraint.length() > 1) return;
3400 char ConstraintLetter = Constraint[0];
3401 switch (ConstraintLetter) {
3402 default: break; // This will fall through to the generic implementation
3403 case 'I': // Signed 16 bit constant
3404 // If this fails, the parent routine will give an error
3405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3406 EVT Type = Op.getValueType();
3407 int64_t Val = C->getSExtValue();
3408 if (isInt<16>(Val)) {
3409 Result = DAG.getTargetConstant(Val, Type);
3414 case 'J': // integer zero
3415 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3416 EVT Type = Op.getValueType();
3417 int64_t Val = C->getZExtValue();
3419 Result = DAG.getTargetConstant(0, Type);
3424 case 'K': // unsigned 16 bit immediate
3425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3426 EVT Type = Op.getValueType();
3427 uint64_t Val = (uint64_t)C->getZExtValue();
3428 if (isUInt<16>(Val)) {
3429 Result = DAG.getTargetConstant(Val, Type);
3434 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3435 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3436 EVT Type = Op.getValueType();
3437 int64_t Val = C->getSExtValue();
3438 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3439 Result = DAG.getTargetConstant(Val, Type);
3444 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3446 EVT Type = Op.getValueType();
3447 int64_t Val = C->getSExtValue();
3448 if ((Val >= -65535) && (Val <= -1)) {
3449 Result = DAG.getTargetConstant(Val, Type);
3454 case 'O': // signed 15 bit immediate
3455 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3456 EVT Type = Op.getValueType();
3457 int64_t Val = C->getSExtValue();
3458 if ((isInt<15>(Val))) {
3459 Result = DAG.getTargetConstant(Val, Type);
3464 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3466 EVT Type = Op.getValueType();
3467 int64_t Val = C->getSExtValue();
3468 if ((Val <= 65535) && (Val >= 1)) {
3469 Result = DAG.getTargetConstant(Val, Type);
3476 if (Result.getNode()) {
3477 Ops.push_back(Result);
3481 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3485 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3486 // The Mips target isn't yet aware of offsets.
3490 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3491 unsigned SrcAlign, bool IsZeroVal,
3493 MachineFunction &MF) const {
3494 if (Subtarget->hasMips64())
3500 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3501 if (VT != MVT::f32 && VT != MVT::f64)
3503 if (Imm.isNegZero())
3505 return Imm.isZero();
3508 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3510 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3512 return TargetLowering::getJumpTableEncoding();