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);
299 setMinFunctionAlignment(HasMips64 ? 3 : 2);
301 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
302 computeRegisterProperties();
304 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
305 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
308 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
309 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
316 return Subtarget->hasMips32r2Or64();
322 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
327 // Transforms a subgraph in CurDAG if the following pattern is found:
328 // (addc multLo, Lo0), (adde multHi, Hi0),
330 // multHi/Lo: product of multiplication
331 // Lo0: initial value of Lo register
332 // Hi0: initial value of Hi register
333 // Return true if pattern matching was successful.
334 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
335 // ADDENode's second operand must be a flag output of an ADDC node in order
336 // for the matching to be successful.
337 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
339 if (ADDCNode->getOpcode() != ISD::ADDC)
342 SDValue MultHi = ADDENode->getOperand(0);
343 SDValue MultLo = ADDCNode->getOperand(0);
344 SDNode* MultNode = MultHi.getNode();
345 unsigned MultOpc = MultHi.getOpcode();
347 // MultHi and MultLo must be generated by the same node,
348 if (MultLo.getNode() != MultNode)
351 // and it must be a multiplication.
352 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
355 // MultLo amd MultHi must be the first and second output of MultNode
357 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
360 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
361 // of the values of MultNode, in which case MultNode will be removed in later
363 // If there exist users other than ADDENode or ADDCNode, this function returns
364 // here, which will result in MultNode being mapped to a single MULT
365 // instruction node rather than a pair of MULT and MADD instructions being
367 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
370 SDValue Chain = CurDAG->getEntryNode();
371 DebugLoc dl = ADDENode->getDebugLoc();
373 // create MipsMAdd(u) node
374 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
376 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
377 MultNode->getOperand(0),// Factor 0
378 MultNode->getOperand(1),// Factor 1
379 ADDCNode->getOperand(1),// Lo0
380 ADDENode->getOperand(1));// Hi0
382 // create CopyFromReg nodes
383 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
385 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
387 CopyFromLo.getValue(2));
389 // replace uses of adde and addc here
390 if (!SDValue(ADDCNode, 0).use_empty())
391 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
393 if (!SDValue(ADDENode, 0).use_empty())
394 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
400 // Transforms a subgraph in CurDAG if the following pattern is found:
401 // (addc Lo0, multLo), (sube Hi0, multHi),
403 // multHi/Lo: product of multiplication
404 // Lo0: initial value of Lo register
405 // Hi0: initial value of Hi register
406 // Return true if pattern matching was successful.
407 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
408 // SUBENode's second operand must be a flag output of an SUBC node in order
409 // for the matching to be successful.
410 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
412 if (SUBCNode->getOpcode() != ISD::SUBC)
415 SDValue MultHi = SUBENode->getOperand(1);
416 SDValue MultLo = SUBCNode->getOperand(1);
417 SDNode* MultNode = MultHi.getNode();
418 unsigned MultOpc = MultHi.getOpcode();
420 // MultHi and MultLo must be generated by the same node,
421 if (MultLo.getNode() != MultNode)
424 // and it must be a multiplication.
425 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
428 // MultLo amd MultHi must be the first and second output of MultNode
430 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
433 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
434 // of the values of MultNode, in which case MultNode will be removed in later
436 // If there exist users other than SUBENode or SUBCNode, this function returns
437 // here, which will result in MultNode being mapped to a single MULT
438 // instruction node rather than a pair of MULT and MSUB instructions being
440 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
443 SDValue Chain = CurDAG->getEntryNode();
444 DebugLoc dl = SUBENode->getDebugLoc();
446 // create MipsSub(u) node
447 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
449 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
450 MultNode->getOperand(0),// Factor 0
451 MultNode->getOperand(1),// Factor 1
452 SUBCNode->getOperand(0),// Lo0
453 SUBENode->getOperand(0));// Hi0
455 // create CopyFromReg nodes
456 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
458 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
460 CopyFromLo.getValue(2));
462 // replace uses of sube and subc here
463 if (!SDValue(SUBCNode, 0).use_empty())
464 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
466 if (!SDValue(SUBENode, 0).use_empty())
467 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
472 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
473 TargetLowering::DAGCombinerInfo &DCI,
474 const MipsSubtarget* Subtarget) {
475 if (DCI.isBeforeLegalize())
478 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
480 return SDValue(N, 0);
485 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
486 TargetLowering::DAGCombinerInfo &DCI,
487 const MipsSubtarget* Subtarget) {
488 if (DCI.isBeforeLegalize())
491 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
493 return SDValue(N, 0);
498 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
499 TargetLowering::DAGCombinerInfo &DCI,
500 const MipsSubtarget* Subtarget) {
501 if (DCI.isBeforeLegalizeOps())
504 EVT Ty = N->getValueType(0);
505 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
506 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
507 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
509 DebugLoc dl = N->getDebugLoc();
511 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
512 N->getOperand(0), N->getOperand(1));
513 SDValue InChain = DAG.getEntryNode();
514 SDValue InGlue = DivRem;
517 if (N->hasAnyUseOfValue(0)) {
518 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
520 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
521 InChain = CopyFromLo.getValue(1);
522 InGlue = CopyFromLo.getValue(2);
526 if (N->hasAnyUseOfValue(1)) {
527 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
529 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
535 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
537 default: llvm_unreachable("Unknown fp condition code!");
539 case ISD::SETOEQ: return Mips::FCOND_OEQ;
540 case ISD::SETUNE: return Mips::FCOND_UNE;
542 case ISD::SETOLT: return Mips::FCOND_OLT;
544 case ISD::SETOGT: return Mips::FCOND_OGT;
546 case ISD::SETOLE: return Mips::FCOND_OLE;
548 case ISD::SETOGE: return Mips::FCOND_OGE;
549 case ISD::SETULT: return Mips::FCOND_ULT;
550 case ISD::SETULE: return Mips::FCOND_ULE;
551 case ISD::SETUGT: return Mips::FCOND_UGT;
552 case ISD::SETUGE: return Mips::FCOND_UGE;
553 case ISD::SETUO: return Mips::FCOND_UN;
554 case ISD::SETO: return Mips::FCOND_OR;
556 case ISD::SETONE: return Mips::FCOND_ONE;
557 case ISD::SETUEQ: return Mips::FCOND_UEQ;
562 // Returns true if condition code has to be inverted.
563 static bool InvertFPCondCode(Mips::CondCode CC) {
564 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
567 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
568 "Illegal Condition Code");
573 // Creates and returns an FPCmp node from a setcc node.
574 // Returns Op if setcc is not a floating point comparison.
575 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
576 // must be a SETCC node
577 if (Op.getOpcode() != ISD::SETCC)
580 SDValue LHS = Op.getOperand(0);
582 if (!LHS.getValueType().isFloatingPoint())
585 SDValue RHS = Op.getOperand(1);
586 DebugLoc dl = Op.getDebugLoc();
588 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
589 // node if necessary.
590 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
592 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
593 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
596 // Creates and returns a CMovFPT/F node.
597 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
598 SDValue False, DebugLoc DL) {
599 bool invert = InvertFPCondCode((Mips::CondCode)
600 cast<ConstantSDNode>(Cond.getOperand(2))
603 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
604 True.getValueType(), True, False, Cond);
607 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
608 TargetLowering::DAGCombinerInfo &DCI,
609 const MipsSubtarget* Subtarget) {
610 if (DCI.isBeforeLegalizeOps())
613 SDValue SetCC = N->getOperand(0);
615 if ((SetCC.getOpcode() != ISD::SETCC) ||
616 !SetCC.getOperand(0).getValueType().isInteger())
619 SDValue False = N->getOperand(2);
620 EVT FalseTy = False.getValueType();
622 if (!FalseTy.isInteger())
625 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
627 if (!CN || CN->getZExtValue())
630 const DebugLoc DL = N->getDebugLoc();
631 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
632 SDValue True = N->getOperand(1);
634 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
635 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
637 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
640 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
641 TargetLowering::DAGCombinerInfo &DCI,
642 const MipsSubtarget* Subtarget) {
643 // Pattern match EXT.
644 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
645 // => ext $dst, $src, size, pos
646 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
649 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
650 unsigned ShiftRightOpc = ShiftRight.getOpcode();
652 // Op's first operand must be a shift right.
653 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
656 // The second operand of the shift must be an immediate.
658 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
661 uint64_t Pos = CN->getZExtValue();
662 uint64_t SMPos, SMSize;
664 // Op's second operand must be a shifted mask.
665 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
666 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
669 // Return if the shifted mask does not start at bit 0 or the sum of its size
670 // and Pos exceeds the word's size.
671 EVT ValTy = N->getValueType(0);
672 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
675 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
676 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
677 DAG.getConstant(SMSize, MVT::i32));
680 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
681 TargetLowering::DAGCombinerInfo &DCI,
682 const MipsSubtarget* Subtarget) {
683 // Pattern match INS.
684 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
685 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
686 // => ins $dst, $src, size, pos, $src1
687 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
690 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
691 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
694 // See if Op's first operand matches (and $src1 , mask0).
695 if (And0.getOpcode() != ISD::AND)
698 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
699 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
702 // See if Op's second operand matches (and (shl $src, pos), mask1).
703 if (And1.getOpcode() != ISD::AND)
706 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
707 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
710 // The shift masks must have the same position and size.
711 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
714 SDValue Shl = And1.getOperand(0);
715 if (Shl.getOpcode() != ISD::SHL)
718 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
721 unsigned Shamt = CN->getZExtValue();
723 // Return if the shift amount and the first bit position of mask are not the
725 EVT ValTy = N->getValueType(0);
726 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
729 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
730 DAG.getConstant(SMPos0, MVT::i32),
731 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
734 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
736 SelectionDAG &DAG = DCI.DAG;
737 unsigned opc = N->getOpcode();
742 return PerformADDECombine(N, DAG, DCI, Subtarget);
744 return PerformSUBECombine(N, DAG, DCI, Subtarget);
747 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
749 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
751 return PerformANDCombine(N, DAG, DCI, Subtarget);
753 return PerformORCombine(N, DAG, DCI, Subtarget);
759 SDValue MipsTargetLowering::
760 LowerOperation(SDValue Op, SelectionDAG &DAG) const
762 switch (Op.getOpcode())
764 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
765 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
766 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
767 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
768 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
769 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
770 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
771 case ISD::SELECT: return LowerSELECT(Op, DAG);
772 case ISD::SETCC: return LowerSETCC(Op, DAG);
773 case ISD::VASTART: return LowerVASTART(Op, DAG);
774 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
775 case ISD::FABS: return LowerFABS(Op, DAG);
776 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
777 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
778 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
779 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
780 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
781 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
782 case ISD::LOAD: return LowerLOAD(Op, DAG);
783 case ISD::STORE: return LowerSTORE(Op, DAG);
788 //===----------------------------------------------------------------------===//
789 // Lower helper functions
790 //===----------------------------------------------------------------------===//
792 // AddLiveIn - This helper function adds the specified physical register to the
793 // MachineFunction as a live in value. It also creates a corresponding
794 // virtual register for it.
796 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
798 assert(RC->contains(PReg) && "Not the correct regclass!");
799 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
800 MF.getRegInfo().addLiveIn(PReg, VReg);
804 // Get fp branch code (not opcode) from condition code.
805 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
806 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
807 return Mips::BRANCH_T;
809 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
810 "Invalid CondCode.");
812 return Mips::BRANCH_F;
816 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
818 const MipsSubtarget* Subtarget,
819 const TargetInstrInfo *TII,
820 bool isFPCmp, unsigned Opc) {
821 // There is no need to expand CMov instructions if target has
822 // conditional moves.
823 if (Subtarget->hasCondMov())
826 // To "insert" a SELECT_CC instruction, we actually have to insert the
827 // diamond control-flow pattern. The incoming instruction knows the
828 // destination vreg to set, the condition code register to branch on, the
829 // true/false values to select between, and a branch opcode to use.
830 const BasicBlock *LLVM_BB = BB->getBasicBlock();
831 MachineFunction::iterator It = BB;
838 // bNE r1, r0, copy1MBB
839 // fallthrough --> copy0MBB
840 MachineBasicBlock *thisMBB = BB;
841 MachineFunction *F = BB->getParent();
842 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
843 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
844 F->insert(It, copy0MBB);
845 F->insert(It, sinkMBB);
847 // Transfer the remainder of BB and its successor edges to sinkMBB.
848 sinkMBB->splice(sinkMBB->begin(), BB,
849 llvm::next(MachineBasicBlock::iterator(MI)),
851 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
853 // Next, add the true and fallthrough blocks as its successors.
854 BB->addSuccessor(copy0MBB);
855 BB->addSuccessor(sinkMBB);
857 // Emit the right instruction according to the type of the operands compared
859 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
861 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
862 .addReg(Mips::ZERO).addMBB(sinkMBB);
866 // # fallthrough to sinkMBB
869 // Update machine-CFG edges
870 BB->addSuccessor(sinkMBB);
873 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
878 BuildMI(*BB, BB->begin(), dl,
879 TII->get(Mips::PHI), MI->getOperand(0).getReg())
880 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
881 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
883 BuildMI(*BB, BB->begin(), dl,
884 TII->get(Mips::PHI), MI->getOperand(0).getReg())
885 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
886 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
888 MI->eraseFromParent(); // The pseudo instruction is gone now.
893 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
894 MachineBasicBlock *BB) const {
895 switch (MI->getOpcode()) {
896 default: llvm_unreachable("Unexpected instr type to insert");
897 case Mips::ATOMIC_LOAD_ADD_I8:
898 case Mips::ATOMIC_LOAD_ADD_I8_P8:
899 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
900 case Mips::ATOMIC_LOAD_ADD_I16:
901 case Mips::ATOMIC_LOAD_ADD_I16_P8:
902 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
903 case Mips::ATOMIC_LOAD_ADD_I32:
904 case Mips::ATOMIC_LOAD_ADD_I32_P8:
905 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
906 case Mips::ATOMIC_LOAD_ADD_I64:
907 case Mips::ATOMIC_LOAD_ADD_I64_P8:
908 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
910 case Mips::ATOMIC_LOAD_AND_I8:
911 case Mips::ATOMIC_LOAD_AND_I8_P8:
912 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
913 case Mips::ATOMIC_LOAD_AND_I16:
914 case Mips::ATOMIC_LOAD_AND_I16_P8:
915 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
916 case Mips::ATOMIC_LOAD_AND_I32:
917 case Mips::ATOMIC_LOAD_AND_I32_P8:
918 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
919 case Mips::ATOMIC_LOAD_AND_I64:
920 case Mips::ATOMIC_LOAD_AND_I64_P8:
921 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
923 case Mips::ATOMIC_LOAD_OR_I8:
924 case Mips::ATOMIC_LOAD_OR_I8_P8:
925 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
926 case Mips::ATOMIC_LOAD_OR_I16:
927 case Mips::ATOMIC_LOAD_OR_I16_P8:
928 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
929 case Mips::ATOMIC_LOAD_OR_I32:
930 case Mips::ATOMIC_LOAD_OR_I32_P8:
931 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
932 case Mips::ATOMIC_LOAD_OR_I64:
933 case Mips::ATOMIC_LOAD_OR_I64_P8:
934 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
936 case Mips::ATOMIC_LOAD_XOR_I8:
937 case Mips::ATOMIC_LOAD_XOR_I8_P8:
938 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
939 case Mips::ATOMIC_LOAD_XOR_I16:
940 case Mips::ATOMIC_LOAD_XOR_I16_P8:
941 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
942 case Mips::ATOMIC_LOAD_XOR_I32:
943 case Mips::ATOMIC_LOAD_XOR_I32_P8:
944 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
945 case Mips::ATOMIC_LOAD_XOR_I64:
946 case Mips::ATOMIC_LOAD_XOR_I64_P8:
947 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
949 case Mips::ATOMIC_LOAD_NAND_I8:
950 case Mips::ATOMIC_LOAD_NAND_I8_P8:
951 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
952 case Mips::ATOMIC_LOAD_NAND_I16:
953 case Mips::ATOMIC_LOAD_NAND_I16_P8:
954 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
955 case Mips::ATOMIC_LOAD_NAND_I32:
956 case Mips::ATOMIC_LOAD_NAND_I32_P8:
957 return EmitAtomicBinary(MI, BB, 4, 0, true);
958 case Mips::ATOMIC_LOAD_NAND_I64:
959 case Mips::ATOMIC_LOAD_NAND_I64_P8:
960 return EmitAtomicBinary(MI, BB, 8, 0, true);
962 case Mips::ATOMIC_LOAD_SUB_I8:
963 case Mips::ATOMIC_LOAD_SUB_I8_P8:
964 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
965 case Mips::ATOMIC_LOAD_SUB_I16:
966 case Mips::ATOMIC_LOAD_SUB_I16_P8:
967 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
968 case Mips::ATOMIC_LOAD_SUB_I32:
969 case Mips::ATOMIC_LOAD_SUB_I32_P8:
970 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
971 case Mips::ATOMIC_LOAD_SUB_I64:
972 case Mips::ATOMIC_LOAD_SUB_I64_P8:
973 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
975 case Mips::ATOMIC_SWAP_I8:
976 case Mips::ATOMIC_SWAP_I8_P8:
977 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
978 case Mips::ATOMIC_SWAP_I16:
979 case Mips::ATOMIC_SWAP_I16_P8:
980 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
981 case Mips::ATOMIC_SWAP_I32:
982 case Mips::ATOMIC_SWAP_I32_P8:
983 return EmitAtomicBinary(MI, BB, 4, 0);
984 case Mips::ATOMIC_SWAP_I64:
985 case Mips::ATOMIC_SWAP_I64_P8:
986 return EmitAtomicBinary(MI, BB, 8, 0);
988 case Mips::ATOMIC_CMP_SWAP_I8:
989 case Mips::ATOMIC_CMP_SWAP_I8_P8:
990 return EmitAtomicCmpSwapPartword(MI, BB, 1);
991 case Mips::ATOMIC_CMP_SWAP_I16:
992 case Mips::ATOMIC_CMP_SWAP_I16_P8:
993 return EmitAtomicCmpSwapPartword(MI, BB, 2);
994 case Mips::ATOMIC_CMP_SWAP_I32:
995 case Mips::ATOMIC_CMP_SWAP_I32_P8:
996 return EmitAtomicCmpSwap(MI, BB, 4);
997 case Mips::ATOMIC_CMP_SWAP_I64:
998 case Mips::ATOMIC_CMP_SWAP_I64_P8:
999 return EmitAtomicCmpSwap(MI, BB, 8);
1003 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1004 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1006 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1007 unsigned Size, unsigned BinOpcode,
1009 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1011 MachineFunction *MF = BB->getParent();
1012 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1013 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1014 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1015 DebugLoc dl = MI->getDebugLoc();
1016 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1019 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1020 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1027 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1028 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1031 ZERO = Mips::ZERO_64;
1035 unsigned OldVal = MI->getOperand(0).getReg();
1036 unsigned Ptr = MI->getOperand(1).getReg();
1037 unsigned Incr = MI->getOperand(2).getReg();
1039 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1040 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1041 unsigned Success = RegInfo.createVirtualRegister(RC);
1043 // insert new blocks after the current block
1044 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1045 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1046 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1047 MachineFunction::iterator It = BB;
1049 MF->insert(It, loopMBB);
1050 MF->insert(It, exitMBB);
1052 // Transfer the remainder of BB and its successor edges to exitMBB.
1053 exitMBB->splice(exitMBB->begin(), BB,
1054 llvm::next(MachineBasicBlock::iterator(MI)),
1056 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1060 // fallthrough --> loopMBB
1061 BB->addSuccessor(loopMBB);
1062 loopMBB->addSuccessor(loopMBB);
1063 loopMBB->addSuccessor(exitMBB);
1066 // ll oldval, 0(ptr)
1067 // <binop> storeval, oldval, incr
1068 // sc success, storeval, 0(ptr)
1069 // beq success, $0, loopMBB
1071 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1073 // and andres, oldval, incr
1074 // nor storeval, $0, andres
1075 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1076 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1077 } else if (BinOpcode) {
1078 // <binop> storeval, oldval, incr
1079 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1083 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1084 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1086 MI->eraseFromParent(); // The instruction is gone now.
1092 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1093 MachineBasicBlock *BB,
1094 unsigned Size, unsigned BinOpcode,
1096 assert((Size == 1 || Size == 2) &&
1097 "Unsupported size for EmitAtomicBinaryPartial.");
1099 MachineFunction *MF = BB->getParent();
1100 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1101 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1102 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1103 DebugLoc dl = MI->getDebugLoc();
1104 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1105 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1107 unsigned Dest = MI->getOperand(0).getReg();
1108 unsigned Ptr = MI->getOperand(1).getReg();
1109 unsigned Incr = MI->getOperand(2).getReg();
1111 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1112 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1113 unsigned Mask = RegInfo.createVirtualRegister(RC);
1114 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1115 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1116 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1117 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1118 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1119 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1120 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1121 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1122 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1123 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1124 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1125 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1126 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1127 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1128 unsigned Success = RegInfo.createVirtualRegister(RC);
1130 // insert new blocks after the current block
1131 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1132 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1133 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1134 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1135 MachineFunction::iterator It = BB;
1137 MF->insert(It, loopMBB);
1138 MF->insert(It, sinkMBB);
1139 MF->insert(It, exitMBB);
1141 // Transfer the remainder of BB and its successor edges to exitMBB.
1142 exitMBB->splice(exitMBB->begin(), BB,
1143 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1144 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1146 BB->addSuccessor(loopMBB);
1147 loopMBB->addSuccessor(loopMBB);
1148 loopMBB->addSuccessor(sinkMBB);
1149 sinkMBB->addSuccessor(exitMBB);
1152 // addiu masklsb2,$0,-4 # 0xfffffffc
1153 // and alignedaddr,ptr,masklsb2
1154 // andi ptrlsb2,ptr,3
1155 // sll shiftamt,ptrlsb2,3
1156 // ori maskupper,$0,255 # 0xff
1157 // sll mask,maskupper,shiftamt
1158 // nor mask2,$0,mask
1159 // sll incr2,incr,shiftamt
1161 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1162 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1163 .addReg(Mips::ZERO).addImm(-4);
1164 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1165 .addReg(Ptr).addReg(MaskLSB2);
1166 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1167 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1168 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1169 .addReg(Mips::ZERO).addImm(MaskImm);
1170 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1171 .addReg(ShiftAmt).addReg(MaskUpper);
1172 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1173 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1175 // atomic.load.binop
1177 // ll oldval,0(alignedaddr)
1178 // binop binopres,oldval,incr2
1179 // and newval,binopres,mask
1180 // and maskedoldval0,oldval,mask2
1181 // or storeval,maskedoldval0,newval
1182 // sc success,storeval,0(alignedaddr)
1183 // beq success,$0,loopMBB
1187 // ll oldval,0(alignedaddr)
1188 // and newval,incr2,mask
1189 // and maskedoldval0,oldval,mask2
1190 // or storeval,maskedoldval0,newval
1191 // sc success,storeval,0(alignedaddr)
1192 // beq success,$0,loopMBB
1195 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1197 // and andres, oldval, incr2
1198 // nor binopres, $0, andres
1199 // and newval, binopres, mask
1200 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1201 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1202 .addReg(Mips::ZERO).addReg(AndRes);
1203 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1204 } else if (BinOpcode) {
1205 // <binop> binopres, oldval, incr2
1206 // and newval, binopres, mask
1207 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1208 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1209 } else {// atomic.swap
1210 // and newval, incr2, mask
1211 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1214 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1215 .addReg(OldVal).addReg(Mask2);
1216 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1217 .addReg(MaskedOldVal0).addReg(NewVal);
1218 BuildMI(BB, dl, TII->get(SC), Success)
1219 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1220 BuildMI(BB, dl, TII->get(Mips::BEQ))
1221 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1224 // and maskedoldval1,oldval,mask
1225 // srl srlres,maskedoldval1,shiftamt
1226 // sll sllres,srlres,24
1227 // sra dest,sllres,24
1229 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1231 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1232 .addReg(OldVal).addReg(Mask);
1233 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1234 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1235 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1236 .addReg(SrlRes).addImm(ShiftImm);
1237 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1238 .addReg(SllRes).addImm(ShiftImm);
1240 MI->eraseFromParent(); // The instruction is gone now.
1246 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1247 MachineBasicBlock *BB,
1248 unsigned Size) const {
1249 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1251 MachineFunction *MF = BB->getParent();
1252 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1253 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1254 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1255 DebugLoc dl = MI->getDebugLoc();
1256 unsigned LL, SC, ZERO, BNE, BEQ;
1259 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1260 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1266 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1267 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1268 ZERO = Mips::ZERO_64;
1273 unsigned Dest = MI->getOperand(0).getReg();
1274 unsigned Ptr = MI->getOperand(1).getReg();
1275 unsigned OldVal = MI->getOperand(2).getReg();
1276 unsigned NewVal = MI->getOperand(3).getReg();
1278 unsigned Success = RegInfo.createVirtualRegister(RC);
1280 // insert new blocks after the current block
1281 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1282 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1283 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1284 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1285 MachineFunction::iterator It = BB;
1287 MF->insert(It, loop1MBB);
1288 MF->insert(It, loop2MBB);
1289 MF->insert(It, exitMBB);
1291 // Transfer the remainder of BB and its successor edges to exitMBB.
1292 exitMBB->splice(exitMBB->begin(), BB,
1293 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1294 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1298 // fallthrough --> loop1MBB
1299 BB->addSuccessor(loop1MBB);
1300 loop1MBB->addSuccessor(exitMBB);
1301 loop1MBB->addSuccessor(loop2MBB);
1302 loop2MBB->addSuccessor(loop1MBB);
1303 loop2MBB->addSuccessor(exitMBB);
1307 // bne dest, oldval, exitMBB
1309 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1310 BuildMI(BB, dl, TII->get(BNE))
1311 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1314 // sc success, newval, 0(ptr)
1315 // beq success, $0, loop1MBB
1317 BuildMI(BB, dl, TII->get(SC), Success)
1318 .addReg(NewVal).addReg(Ptr).addImm(0);
1319 BuildMI(BB, dl, TII->get(BEQ))
1320 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1322 MI->eraseFromParent(); // The instruction is gone now.
1328 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1329 MachineBasicBlock *BB,
1330 unsigned Size) const {
1331 assert((Size == 1 || Size == 2) &&
1332 "Unsupported size for EmitAtomicCmpSwapPartial.");
1334 MachineFunction *MF = BB->getParent();
1335 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1336 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1337 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1338 DebugLoc dl = MI->getDebugLoc();
1339 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1340 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1342 unsigned Dest = MI->getOperand(0).getReg();
1343 unsigned Ptr = MI->getOperand(1).getReg();
1344 unsigned CmpVal = MI->getOperand(2).getReg();
1345 unsigned NewVal = MI->getOperand(3).getReg();
1347 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1348 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1349 unsigned Mask = RegInfo.createVirtualRegister(RC);
1350 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1351 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1352 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1353 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1354 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1355 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1356 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1357 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1358 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1359 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1360 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1361 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1362 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1363 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1364 unsigned Success = RegInfo.createVirtualRegister(RC);
1366 // insert new blocks after the current block
1367 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1368 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1369 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1370 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1371 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1372 MachineFunction::iterator It = BB;
1374 MF->insert(It, loop1MBB);
1375 MF->insert(It, loop2MBB);
1376 MF->insert(It, sinkMBB);
1377 MF->insert(It, exitMBB);
1379 // Transfer the remainder of BB and its successor edges to exitMBB.
1380 exitMBB->splice(exitMBB->begin(), BB,
1381 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1382 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1384 BB->addSuccessor(loop1MBB);
1385 loop1MBB->addSuccessor(sinkMBB);
1386 loop1MBB->addSuccessor(loop2MBB);
1387 loop2MBB->addSuccessor(loop1MBB);
1388 loop2MBB->addSuccessor(sinkMBB);
1389 sinkMBB->addSuccessor(exitMBB);
1391 // FIXME: computation of newval2 can be moved to loop2MBB.
1393 // addiu masklsb2,$0,-4 # 0xfffffffc
1394 // and alignedaddr,ptr,masklsb2
1395 // andi ptrlsb2,ptr,3
1396 // sll shiftamt,ptrlsb2,3
1397 // ori maskupper,$0,255 # 0xff
1398 // sll mask,maskupper,shiftamt
1399 // nor mask2,$0,mask
1400 // andi maskedcmpval,cmpval,255
1401 // sll shiftedcmpval,maskedcmpval,shiftamt
1402 // andi maskednewval,newval,255
1403 // sll shiftednewval,maskednewval,shiftamt
1404 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1405 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1406 .addReg(Mips::ZERO).addImm(-4);
1407 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1408 .addReg(Ptr).addReg(MaskLSB2);
1409 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1410 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1411 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1412 .addReg(Mips::ZERO).addImm(MaskImm);
1413 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1414 .addReg(ShiftAmt).addReg(MaskUpper);
1415 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1416 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1417 .addReg(CmpVal).addImm(MaskImm);
1418 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1419 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1420 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1421 .addReg(NewVal).addImm(MaskImm);
1422 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1423 .addReg(ShiftAmt).addReg(MaskedNewVal);
1426 // ll oldval,0(alginedaddr)
1427 // and maskedoldval0,oldval,mask
1428 // bne maskedoldval0,shiftedcmpval,sinkMBB
1430 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1431 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1432 .addReg(OldVal).addReg(Mask);
1433 BuildMI(BB, dl, TII->get(Mips::BNE))
1434 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1437 // and maskedoldval1,oldval,mask2
1438 // or storeval,maskedoldval1,shiftednewval
1439 // sc success,storeval,0(alignedaddr)
1440 // beq success,$0,loop1MBB
1442 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1443 .addReg(OldVal).addReg(Mask2);
1444 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1445 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1446 BuildMI(BB, dl, TII->get(SC), Success)
1447 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1448 BuildMI(BB, dl, TII->get(Mips::BEQ))
1449 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1452 // srl srlres,maskedoldval0,shiftamt
1453 // sll sllres,srlres,24
1454 // sra dest,sllres,24
1456 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1458 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1459 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1460 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1461 .addReg(SrlRes).addImm(ShiftImm);
1462 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1463 .addReg(SllRes).addImm(ShiftImm);
1465 MI->eraseFromParent(); // The instruction is gone now.
1470 //===----------------------------------------------------------------------===//
1471 // Misc Lower Operation implementation
1472 //===----------------------------------------------------------------------===//
1473 SDValue MipsTargetLowering::
1474 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1476 MachineFunction &MF = DAG.getMachineFunction();
1477 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1478 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1480 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1481 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1482 "Cannot lower if the alignment of the allocated space is larger than \
1483 that of the stack.");
1485 SDValue Chain = Op.getOperand(0);
1486 SDValue Size = Op.getOperand(1);
1487 DebugLoc dl = Op.getDebugLoc();
1489 // Get a reference from Mips stack pointer
1490 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1492 // Subtract the dynamic size from the actual stack size to
1493 // obtain the new stack size.
1494 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1496 // The Sub result contains the new stack start address, so it
1497 // must be placed in the stack pointer register.
1498 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1500 // This node always has two return values: a new stack pointer
1501 // value and a chain
1502 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1503 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1504 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1506 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1509 SDValue MipsTargetLowering::
1510 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1512 // The first operand is the chain, the second is the condition, the third is
1513 // the block to branch to if the condition is true.
1514 SDValue Chain = Op.getOperand(0);
1515 SDValue Dest = Op.getOperand(2);
1516 DebugLoc dl = Op.getDebugLoc();
1518 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1520 // Return if flag is not set by a floating point comparison.
1521 if (CondRes.getOpcode() != MipsISD::FPCmp)
1524 SDValue CCNode = CondRes.getOperand(2);
1526 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1527 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1529 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1533 SDValue MipsTargetLowering::
1534 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1536 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1538 // Return if flag is not set by a floating point comparison.
1539 if (Cond.getOpcode() != MipsISD::FPCmp)
1542 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1546 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1547 SDValue Cond = CreateFPCmp(DAG, Op);
1549 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1550 "Floating point operand expected.");
1552 SDValue True = DAG.getConstant(1, MVT::i32);
1553 SDValue False = DAG.getConstant(0, MVT::i32);
1555 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1558 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1559 SelectionDAG &DAG) const {
1560 // FIXME there isn't actually debug info here
1561 DebugLoc dl = Op.getDebugLoc();
1562 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1564 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1565 SDVTList VTs = DAG.getVTList(MVT::i32);
1567 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1569 // %gp_rel relocation
1570 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1571 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1573 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1574 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1575 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1577 // %hi/%lo relocation
1578 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1580 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1582 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1583 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1584 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1587 EVT ValTy = Op.getValueType();
1588 bool HasGotOfst = (GV->hasInternalLinkage() ||
1589 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1590 unsigned GotFlag = HasMips64 ?
1591 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1592 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1593 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1594 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1595 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1596 MachinePointerInfo(), false, false, false, 0);
1597 // On functions and global targets not internal linked only
1598 // a load from got/GP is necessary for PIC to work.
1601 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1602 HasMips64 ? MipsII::MO_GOT_OFST :
1604 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1605 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1608 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1609 SelectionDAG &DAG) const {
1610 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1611 // FIXME there isn't actually debug info here
1612 DebugLoc dl = Op.getDebugLoc();
1614 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1615 // %hi/%lo relocation
1616 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1617 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1618 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1619 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1620 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1623 EVT ValTy = Op.getValueType();
1624 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1625 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1626 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1627 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1628 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1629 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1630 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1631 MachinePointerInfo(), false, false, false, 0);
1632 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1633 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1636 SDValue MipsTargetLowering::
1637 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1639 // If the relocation model is PIC, use the General Dynamic TLS Model or
1640 // Local Dynamic TLS model, otherwise use the Initial Exec or
1641 // Local Exec TLS Model.
1643 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1644 DebugLoc dl = GA->getDebugLoc();
1645 const GlobalValue *GV = GA->getGlobal();
1646 EVT PtrVT = getPointerTy();
1648 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1650 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1651 // General Dynamic and Local Dynamic TLS Model.
1652 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1655 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1656 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1657 GetGlobalReg(DAG, PtrVT), TGA);
1658 unsigned PtrSize = PtrVT.getSizeInBits();
1659 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1661 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1665 Entry.Node = Argument;
1667 Args.push_back(Entry);
1669 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1670 false, false, false, false, 0, CallingConv::C,
1671 /*isTailCall=*/false, /*doesNotRet=*/false,
1672 /*isReturnValueUsed=*/true,
1673 TlsGetAddr, Args, DAG, dl);
1674 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1676 SDValue Ret = CallResult.first;
1678 if (model != TLSModel::LocalDynamic)
1681 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1682 MipsII::MO_DTPREL_HI);
1683 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1684 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1685 MipsII::MO_DTPREL_LO);
1686 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1687 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1688 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1692 if (model == TLSModel::InitialExec) {
1693 // Initial Exec TLS Model
1694 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1695 MipsII::MO_GOTTPREL);
1696 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1698 Offset = DAG.getLoad(PtrVT, dl,
1699 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1700 false, false, false, 0);
1702 // Local Exec TLS Model
1703 assert(model == TLSModel::LocalExec);
1704 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1705 MipsII::MO_TPREL_HI);
1706 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1707 MipsII::MO_TPREL_LO);
1708 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1709 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1710 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1713 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1714 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1717 SDValue MipsTargetLowering::
1718 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1720 SDValue HiPart, JTI, JTILo;
1721 // FIXME there isn't actually debug info here
1722 DebugLoc dl = Op.getDebugLoc();
1723 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1724 EVT PtrVT = Op.getValueType();
1725 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1727 if (!IsPIC && !IsN64) {
1728 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1729 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1730 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1731 } else {// Emit Load from Global Pointer
1732 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1733 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1734 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1735 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1737 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1738 MachinePointerInfo(), false, false, false, 0);
1739 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1742 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1743 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1746 SDValue MipsTargetLowering::
1747 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1750 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1751 const Constant *C = N->getConstVal();
1752 // FIXME there isn't actually debug info here
1753 DebugLoc dl = Op.getDebugLoc();
1755 // gp_rel relocation
1756 // FIXME: we should reference the constant pool using small data sections,
1757 // but the asm printer currently doesn't support this feature without
1758 // hacking it. This feature should come soon so we can uncomment the
1760 //if (IsInSmallSection(C->getType())) {
1761 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1762 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1763 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1765 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1766 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1767 N->getOffset(), MipsII::MO_ABS_HI);
1768 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1769 N->getOffset(), MipsII::MO_ABS_LO);
1770 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1771 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1772 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1774 EVT ValTy = Op.getValueType();
1775 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1776 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1777 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1778 N->getOffset(), GOTFlag);
1779 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1780 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1781 MachinePointerInfo::getConstantPool(), false,
1783 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1784 N->getOffset(), OFSTFlag);
1785 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1786 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1792 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1793 MachineFunction &MF = DAG.getMachineFunction();
1794 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1796 DebugLoc dl = Op.getDebugLoc();
1797 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1800 // vastart just stores the address of the VarArgsFrameIndex slot into the
1801 // memory location argument.
1802 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1803 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1804 MachinePointerInfo(SV), false, false, 0);
1807 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1808 EVT TyX = Op.getOperand(0).getValueType();
1809 EVT TyY = Op.getOperand(1).getValueType();
1810 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1811 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1812 DebugLoc DL = Op.getDebugLoc();
1815 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1817 SDValue X = (TyX == MVT::f32) ?
1818 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1819 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1821 SDValue Y = (TyY == MVT::f32) ?
1822 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1823 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1827 // ext E, Y, 31, 1 ; extract bit31 of Y
1828 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1829 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1830 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1833 // srl SrlX, SllX, 1
1835 // sll SllY, SrlX, 31
1836 // or Or, SrlX, SllY
1837 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1838 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1839 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1840 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1841 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1844 if (TyX == MVT::f32)
1845 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1847 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1848 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1849 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1852 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1853 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1854 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1855 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1856 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1857 DebugLoc DL = Op.getDebugLoc();
1859 // Bitcast to integer nodes.
1860 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1861 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1864 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1865 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1866 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1867 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1869 if (WidthX > WidthY)
1870 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1871 else if (WidthY > WidthX)
1872 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1874 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1875 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1876 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1879 // (d)sll SllX, X, 1
1880 // (d)srl SrlX, SllX, 1
1881 // (d)srl SrlY, Y, width(Y)-1
1882 // (d)sll SllY, SrlX, width(Y)-1
1883 // or Or, SrlX, SllY
1884 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1885 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1886 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1887 DAG.getConstant(WidthY - 1, MVT::i32));
1889 if (WidthX > WidthY)
1890 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1891 else if (WidthY > WidthX)
1892 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1894 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1895 DAG.getConstant(WidthX - 1, MVT::i32));
1896 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1897 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1901 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1902 if (Subtarget->hasMips64())
1903 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1905 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1908 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1909 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1910 DebugLoc DL = Op.getDebugLoc();
1912 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1914 SDValue X = (Op.getValueType() == MVT::f32) ?
1915 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1916 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1921 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1922 DAG.getRegister(Mips::ZERO, MVT::i32),
1923 DAG.getConstant(31, MVT::i32), Const1, X);
1925 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1926 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1929 if (Op.getValueType() == MVT::f32)
1930 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1932 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1933 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1934 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1937 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1938 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1939 DebugLoc DL = Op.getDebugLoc();
1941 // Bitcast to integer node.
1942 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1946 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1947 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1948 DAG.getConstant(63, MVT::i32), Const1, X);
1950 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1951 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1954 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1958 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
1959 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1960 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1962 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1965 SDValue MipsTargetLowering::
1966 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1968 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1969 "Frame address can only be determined for current frame.");
1971 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1972 MFI->setFrameAddressIsTaken(true);
1973 EVT VT = Op.getValueType();
1974 DebugLoc dl = Op.getDebugLoc();
1975 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1976 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1980 // TODO: set SType according to the desired memory barrier behavior.
1982 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1984 DebugLoc dl = Op.getDebugLoc();
1985 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1986 DAG.getConstant(SType, MVT::i32));
1989 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1990 SelectionDAG& DAG) const {
1991 // FIXME: Need pseudo-fence for 'singlethread' fences
1992 // FIXME: Set SType for weaker fences where supported/appropriate.
1994 DebugLoc dl = Op.getDebugLoc();
1995 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1996 DAG.getConstant(SType, MVT::i32));
1999 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2000 SelectionDAG& DAG) const {
2001 DebugLoc DL = Op.getDebugLoc();
2002 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2003 SDValue Shamt = Op.getOperand(2);
2006 // lo = (shl lo, shamt)
2007 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2010 // hi = (shl lo, shamt[4:0])
2011 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2012 DAG.getConstant(-1, MVT::i32));
2013 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2014 DAG.getConstant(1, MVT::i32));
2015 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2017 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2018 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2019 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2020 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2021 DAG.getConstant(0x20, MVT::i32));
2022 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, DAG.getConstant(0, MVT::i32),
2024 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2026 SDValue Ops[2] = {Lo, Hi};
2027 return DAG.getMergeValues(Ops, 2, DL);
2030 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG& DAG,
2032 DebugLoc DL = Op.getDebugLoc();
2033 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2034 SDValue Shamt = Op.getOperand(2);
2037 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2039 // hi = (sra hi, shamt)
2041 // hi = (srl hi, shamt)
2044 // lo = (sra hi, shamt[4:0])
2045 // hi = (sra hi, 31)
2047 // lo = (srl hi, shamt[4:0])
2049 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2050 DAG.getConstant(-1, MVT::i32));
2051 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2052 DAG.getConstant(1, MVT::i32));
2053 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2054 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2055 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2056 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2058 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2059 DAG.getConstant(0x20, MVT::i32));
2060 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2061 DAG.getConstant(31, MVT::i32));
2062 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2063 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2064 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2067 SDValue Ops[2] = {Lo, Hi};
2068 return DAG.getMergeValues(Ops, 2, DL);
2071 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2072 SDValue Chain, SDValue Src, unsigned Offset) {
2073 SDValue Ptr = LD->getBasePtr();
2074 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2075 EVT BasePtrVT = Ptr.getValueType();
2076 DebugLoc DL = LD->getDebugLoc();
2077 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2080 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2081 DAG.getConstant(Offset, BasePtrVT));
2083 SDValue Ops[] = { Chain, Ptr, Src };
2084 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2085 LD->getMemOperand());
2088 // Expand an unaligned 32 or 64-bit integer load node.
2089 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2090 LoadSDNode *LD = cast<LoadSDNode>(Op);
2091 EVT MemVT = LD->getMemoryVT();
2093 // Return if load is aligned or if MemVT is neither i32 nor i64.
2094 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2095 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2098 bool IsLittle = Subtarget->isLittle();
2099 EVT VT = Op.getValueType();
2100 ISD::LoadExtType ExtType = LD->getExtensionType();
2101 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2103 assert((VT == MVT::i32) || (VT == MVT::i64));
2106 // (set dst, (i64 (load baseptr)))
2108 // (set tmp, (ldl (add baseptr, 7), undef))
2109 // (set dst, (ldr baseptr, tmp))
2110 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2111 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2113 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2117 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2119 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2123 // (set dst, (i32 (load baseptr))) or
2124 // (set dst, (i64 (sextload baseptr))) or
2125 // (set dst, (i64 (extload baseptr)))
2127 // (set tmp, (lwl (add baseptr, 3), undef))
2128 // (set dst, (lwr baseptr, tmp))
2129 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2130 (ExtType == ISD::EXTLOAD))
2133 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2136 // (set dst, (i64 (zextload baseptr)))
2138 // (set tmp0, (lwl (add baseptr, 3), undef))
2139 // (set tmp1, (lwr baseptr, tmp0))
2140 // (set tmp2, (shl tmp1, 32))
2141 // (set dst, (srl tmp2, 32))
2142 DebugLoc DL = LD->getDebugLoc();
2143 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2144 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2145 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2146 SDValue Ops[] = { SRL, LWR.getValue(1) };
2147 return DAG.getMergeValues(Ops, 2, DL);
2150 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2151 SDValue Chain, unsigned Offset) {
2152 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2153 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2154 DebugLoc DL = SD->getDebugLoc();
2155 SDVTList VTList = DAG.getVTList(MVT::Other);
2158 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2159 DAG.getConstant(Offset, BasePtrVT));
2161 SDValue Ops[] = { Chain, Value, Ptr };
2162 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2163 SD->getMemOperand());
2166 // Expand an unaligned 32 or 64-bit integer store node.
2167 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2168 StoreSDNode *SD = cast<StoreSDNode>(Op);
2169 EVT MemVT = SD->getMemoryVT();
2171 // Return if store is aligned or if MemVT is neither i32 nor i64.
2172 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2173 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2176 bool IsLittle = Subtarget->isLittle();
2177 SDValue Value = SD->getValue(), Chain = SD->getChain();
2178 EVT VT = Value.getValueType();
2181 // (store val, baseptr) or
2182 // (truncstore val, baseptr)
2184 // (swl val, (add baseptr, 3))
2185 // (swr val, baseptr)
2186 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2187 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2189 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2192 assert(VT == MVT::i64);
2195 // (store val, baseptr)
2197 // (sdl val, (add baseptr, 7))
2198 // (sdr val, baseptr)
2199 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2200 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2203 //===----------------------------------------------------------------------===//
2204 // Calling Convention Implementation
2205 //===----------------------------------------------------------------------===//
2207 //===----------------------------------------------------------------------===//
2208 // TODO: Implement a generic logic using tblgen that can support this.
2209 // Mips O32 ABI rules:
2211 // i32 - Passed in A0, A1, A2, A3 and stack
2212 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2213 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2214 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2215 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2216 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2219 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2220 //===----------------------------------------------------------------------===//
2222 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2223 MVT LocVT, CCValAssign::LocInfo LocInfo,
2224 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2226 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2228 static const uint16_t IntRegs[] = {
2229 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2231 static const uint16_t F32Regs[] = {
2232 Mips::F12, Mips::F14
2234 static const uint16_t F64Regs[] = {
2239 if (ArgFlags.isByVal()) {
2240 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2241 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2242 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2243 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2244 r < std::min(IntRegsSize, NextReg); ++r)
2245 State.AllocateReg(IntRegs[r]);
2249 // Promote i8 and i16
2250 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2252 if (ArgFlags.isSExt())
2253 LocInfo = CCValAssign::SExt;
2254 else if (ArgFlags.isZExt())
2255 LocInfo = CCValAssign::ZExt;
2257 LocInfo = CCValAssign::AExt;
2262 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2263 // is true: function is vararg, argument is 3rd or higher, there is previous
2264 // argument which is not f32 or f64.
2265 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2266 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2267 unsigned OrigAlign = ArgFlags.getOrigAlign();
2268 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2270 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2271 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2272 // If this is the first part of an i64 arg,
2273 // the allocated register must be either A0 or A2.
2274 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2275 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2277 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2278 // Allocate int register and shadow next int register. If first
2279 // available register is Mips::A1 or Mips::A3, shadow it too.
2280 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2281 if (Reg == Mips::A1 || Reg == Mips::A3)
2282 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2283 State.AllocateReg(IntRegs, IntRegsSize);
2285 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2286 // we are guaranteed to find an available float register
2287 if (ValVT == MVT::f32) {
2288 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2289 // Shadow int register
2290 State.AllocateReg(IntRegs, IntRegsSize);
2292 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2293 // Shadow int registers
2294 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2295 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2296 State.AllocateReg(IntRegs, IntRegsSize);
2297 State.AllocateReg(IntRegs, IntRegsSize);
2300 llvm_unreachable("Cannot handle this ValVT.");
2302 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2303 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2306 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2308 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2310 return false; // CC must always match
2313 static const uint16_t Mips64IntRegs[8] =
2314 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2315 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2316 static const uint16_t Mips64DPRegs[8] =
2317 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2318 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2320 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2321 CCValAssign::LocInfo LocInfo,
2322 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2323 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2324 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
2325 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2327 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2329 // If byval is 16-byte aligned, the first arg register must be even.
2330 if ((Align == 16) && (FirstIdx % 2)) {
2331 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2335 // Mark the registers allocated.
2336 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2337 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2339 // Allocate space on caller's stack.
2340 unsigned Offset = State.AllocateStack(Size, Align);
2343 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2346 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2351 #include "MipsGenCallingConv.inc"
2354 AnalyzeMips64CallOperands(CCState &CCInfo,
2355 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2356 unsigned NumOps = Outs.size();
2357 for (unsigned i = 0; i != NumOps; ++i) {
2358 MVT ArgVT = Outs[i].VT;
2359 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2362 if (Outs[i].IsFixed)
2363 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2365 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2369 dbgs() << "Call operand #" << i << " has unhandled type "
2370 << EVT(ArgVT).getEVTString();
2372 llvm_unreachable(0);
2377 //===----------------------------------------------------------------------===//
2378 // Call Calling Convention Implementation
2379 //===----------------------------------------------------------------------===//
2381 static const unsigned O32IntRegsSize = 4;
2383 static const uint16_t O32IntRegs[] = {
2384 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2387 // Return next O32 integer argument register.
2388 static unsigned getNextIntArgReg(unsigned Reg) {
2389 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2390 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2393 // Write ByVal Arg to arg registers and stack.
2395 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2396 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2397 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2398 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2399 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2400 MVT PtrType, bool isLittle) {
2401 unsigned LocMemOffset = VA.getLocMemOffset();
2402 unsigned Offset = 0;
2403 uint32_t RemainingSize = Flags.getByValSize();
2404 unsigned ByValAlign = Flags.getByValAlign();
2406 // Copy the first 4 words of byval arg to registers A0 - A3.
2407 // FIXME: Use a stricter alignment if it enables better optimization in passes
2409 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2410 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2411 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2412 DAG.getConstant(Offset, MVT::i32));
2413 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2414 MachinePointerInfo(), false, false, false,
2415 std::min(ByValAlign, (unsigned )4));
2416 MemOpChains.push_back(LoadVal.getValue(1));
2417 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2418 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2421 if (RemainingSize == 0)
2424 // If there still is a register available for argument passing, write the
2425 // remaining part of the structure to it using subword loads and shifts.
2426 if (LocMemOffset < 4 * 4) {
2427 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2428 "There must be one to three bytes remaining.");
2429 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2430 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2431 DAG.getConstant(Offset, MVT::i32));
2432 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2433 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2434 LoadPtr, MachinePointerInfo(),
2435 MVT::getIntegerVT(LoadSize * 8), false,
2437 MemOpChains.push_back(LoadVal.getValue(1));
2439 // If target is big endian, shift it to the most significant half-word or
2442 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2443 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2446 RemainingSize -= LoadSize;
2448 // Read second subword if necessary.
2449 if (RemainingSize != 0) {
2450 assert(RemainingSize == 1 && "There must be one byte remaining.");
2451 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2452 DAG.getConstant(Offset, MVT::i32));
2453 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2454 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2455 LoadPtr, MachinePointerInfo(),
2456 MVT::i8, false, false, Alignment);
2457 MemOpChains.push_back(Subword.getValue(1));
2458 // Insert the loaded byte to LoadVal.
2459 // FIXME: Use INS if supported by target.
2460 unsigned ShiftAmt = isLittle ? 16 : 8;
2461 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2462 DAG.getConstant(ShiftAmt, MVT::i32));
2463 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2466 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2467 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2471 // Create a fixed object on stack at offset LocMemOffset and copy
2472 // remaining part of byval arg to it using memcpy.
2473 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2474 DAG.getConstant(Offset, MVT::i32));
2475 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2476 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2477 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2478 DAG.getConstant(RemainingSize, MVT::i32),
2479 std::min(ByValAlign, (unsigned)4),
2480 /*isVolatile=*/false, /*AlwaysInline=*/false,
2481 MachinePointerInfo(0), MachinePointerInfo(0));
2484 // Copy Mips64 byVal arg to registers and stack.
2486 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2487 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2488 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2489 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2490 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2491 EVT PtrTy, bool isLittle) {
2492 unsigned ByValSize = Flags.getByValSize();
2493 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2494 bool IsRegLoc = VA.isRegLoc();
2495 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2496 unsigned LocMemOffset = 0;
2497 unsigned MemCpySize = ByValSize;
2500 LocMemOffset = VA.getLocMemOffset();
2502 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2504 const uint16_t *RegEnd = Mips64IntRegs + 8;
2506 // Copy double words to registers.
2507 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2508 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2509 DAG.getConstant(Offset, PtrTy));
2510 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2511 MachinePointerInfo(), false, false, false,
2513 MemOpChains.push_back(LoadVal.getValue(1));
2514 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2517 // Return if the struct has been fully copied.
2518 if (!(MemCpySize = ByValSize - Offset))
2521 // If there is an argument register available, copy the remainder of the
2522 // byval argument with sub-doubleword loads and shifts.
2523 if (Reg != RegEnd) {
2524 assert((ByValSize < Offset + 8) &&
2525 "Size of the remainder should be smaller than 8-byte.");
2527 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2528 unsigned RemSize = ByValSize - Offset;
2530 if (RemSize < LoadSize)
2533 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2534 DAG.getConstant(Offset, PtrTy));
2536 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2537 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2538 false, false, Alignment);
2539 MemOpChains.push_back(LoadVal.getValue(1));
2541 // Offset in number of bits from double word boundary.
2542 unsigned OffsetDW = (Offset % 8) * 8;
2543 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2544 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2545 DAG.getConstant(Shamt, MVT::i32));
2547 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2550 Alignment = std::min(Alignment, LoadSize);
2553 RegsToPass.push_back(std::make_pair(*Reg, Val));
2558 assert(MemCpySize && "MemCpySize must not be zero.");
2560 // Create a fixed object on stack at offset LocMemOffset and copy
2561 // remainder of byval arg to it with memcpy.
2562 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2563 DAG.getConstant(Offset, PtrTy));
2564 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2565 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2566 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2567 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2568 /*isVolatile=*/false, /*AlwaysInline=*/false,
2569 MachinePointerInfo(0), MachinePointerInfo(0));
2572 /// LowerCall - functions arguments are copied from virtual regs to
2573 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2574 /// TODO: isTailCall.
2576 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2577 SmallVectorImpl<SDValue> &InVals) const {
2578 SelectionDAG &DAG = CLI.DAG;
2579 DebugLoc &dl = CLI.DL;
2580 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2581 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2582 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2583 SDValue InChain = CLI.Chain;
2584 SDValue Callee = CLI.Callee;
2585 bool &isTailCall = CLI.IsTailCall;
2586 CallingConv::ID CallConv = CLI.CallConv;
2587 bool isVarArg = CLI.IsVarArg;
2589 // MIPs target does not yet support tail call optimization.
2592 MachineFunction &MF = DAG.getMachineFunction();
2593 MachineFrameInfo *MFI = MF.getFrameInfo();
2594 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2595 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2596 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2598 // Analyze operands of the call, assigning locations to each operand.
2599 SmallVector<CCValAssign, 16> ArgLocs;
2600 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2601 getTargetMachine(), ArgLocs, *DAG.getContext());
2603 if (CallConv == CallingConv::Fast)
2604 CCInfo.AnalyzeCallOperands(Outs, CC_Mips_FastCC);
2606 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2608 AnalyzeMips64CallOperands(CCInfo, Outs);
2610 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2612 // Get a count of how many bytes are to be pushed on the stack.
2613 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2615 // Chain is the output chain of the last Load/Store or CopyToReg node.
2616 // ByValChain is the output chain of the last Memcpy node created for copying
2617 // byval arguments to the stack.
2618 SDValue Chain, CallSeqStart, ByValChain;
2619 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2620 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2621 ByValChain = InChain;
2623 // Get the frame index of the stack frame object that points to the location
2624 // of dynamically allocated area on the stack.
2625 int DynAllocFI = MipsFI->getDynAllocFI();
2627 // Update size of the maximum argument space.
2628 // For O32, a minimum of four words (16 bytes) of argument space is
2630 if (IsO32 && (CallConv != CallingConv::Fast))
2631 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2633 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2635 if (MaxCallFrameSize < NextStackOffset) {
2636 MipsFI->setMaxCallFrameSize(NextStackOffset);
2638 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2639 // allocated stack space. These offsets must be aligned to a boundary
2640 // determined by the stack alignment of the ABI.
2641 unsigned StackAlignment = TFL->getStackAlignment();
2642 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2643 StackAlignment * StackAlignment;
2645 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2648 // With EABI is it possible to have 16 args on registers.
2649 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2650 SmallVector<SDValue, 8> MemOpChains;
2652 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2654 // Walk the register/memloc assignments, inserting copies/loads.
2655 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2656 SDValue Arg = OutVals[i];
2657 CCValAssign &VA = ArgLocs[i];
2658 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2659 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2662 if (Flags.isByVal()) {
2663 assert(Flags.getByValSize() &&
2664 "ByVal args of size 0 should have been ignored by front-end.");
2666 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2667 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2668 Subtarget->isLittle());
2670 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2671 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2672 Subtarget->isLittle());
2676 // Promote the value if needed.
2677 switch (VA.getLocInfo()) {
2678 default: llvm_unreachable("Unknown loc info!");
2679 case CCValAssign::Full:
2680 if (VA.isRegLoc()) {
2681 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2682 (ValVT == MVT::f64 && LocVT == MVT::i64))
2683 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2684 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2685 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2686 Arg, DAG.getConstant(0, MVT::i32));
2687 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2688 Arg, DAG.getConstant(1, MVT::i32));
2689 if (!Subtarget->isLittle())
2691 unsigned LocRegLo = VA.getLocReg();
2692 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2693 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2694 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2699 case CCValAssign::SExt:
2700 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2702 case CCValAssign::ZExt:
2703 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2705 case CCValAssign::AExt:
2706 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2710 // Arguments that can be passed on register must be kept at
2711 // RegsToPass vector
2712 if (VA.isRegLoc()) {
2713 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2717 // Register can't get to this point...
2718 assert(VA.isMemLoc());
2720 // Create the frame index object for this incoming parameter
2721 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2722 VA.getLocMemOffset(), true);
2723 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2725 // emit ISD::STORE whichs stores the
2726 // parameter value to a stack Location
2727 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2728 MachinePointerInfo(), false, false, 0));
2731 // Extend range of indices of frame objects for outgoing arguments that were
2732 // created during this function call. Skip this step if no such objects were
2735 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2737 // If a memcpy has been created to copy a byval arg to a stack, replace the
2738 // chain input of CallSeqStart with ByValChain.
2739 if (InChain != ByValChain)
2740 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2741 NextStackOffsetVal);
2743 // Transform all store nodes into one single node because all store
2744 // nodes are independent of each other.
2745 if (!MemOpChains.empty())
2746 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2747 &MemOpChains[0], MemOpChains.size());
2749 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2750 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2751 // node so that legalize doesn't hack it.
2752 unsigned char OpFlag;
2753 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2754 bool GlobalOrExternal = false;
2757 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2758 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2759 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2760 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2761 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2763 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2766 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2767 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2768 getPointerTy(), 0, OpFlag);
2771 GlobalOrExternal = true;
2773 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2774 if (IsN64 || (!IsO32 && IsPIC))
2775 OpFlag = MipsII::MO_GOT_DISP;
2776 else if (!IsPIC) // !N64 && static
2777 OpFlag = MipsII::MO_NO_FLAG;
2779 OpFlag = MipsII::MO_GOT_CALL;
2780 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2782 GlobalOrExternal = true;
2787 // Create nodes that load address of callee and copy it to T9
2789 if (GlobalOrExternal) {
2790 // Load callee address
2791 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2792 GetGlobalReg(DAG, getPointerTy()), Callee);
2793 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2794 Callee, MachinePointerInfo::getGOT(),
2795 false, false, false, 0);
2797 // Use GOT+LO if callee has internal linkage.
2798 if (CalleeLo.getNode()) {
2799 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2800 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2806 // T9 should contain the address of the callee function if
2807 // -reloction-model=pic or it is an indirect call.
2808 if (IsPICCall || !GlobalOrExternal) {
2810 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2811 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2812 InFlag = Chain.getValue(1);
2813 Callee = DAG.getRegister(T9Reg, getPointerTy());
2816 // Insert node "GP copy globalreg" before call to function.
2817 // Lazy-binding stubs require GP to point to the GOT.
2819 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2820 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2821 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2824 // Build a sequence of copy-to-reg nodes chained together with token
2825 // chain and flag operands which copy the outgoing args into registers.
2826 // The InFlag in necessary since all emitted instructions must be
2828 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2829 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2830 RegsToPass[i].second, InFlag);
2831 InFlag = Chain.getValue(1);
2834 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2835 // = Chain, Callee, Reg#1, Reg#2, ...
2837 // Returns a chain & a flag for retval copy to use.
2838 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2839 SmallVector<SDValue, 8> Ops;
2840 Ops.push_back(Chain);
2841 Ops.push_back(Callee);
2843 // Add argument registers to the end of the list so that they are
2844 // known live into the call.
2845 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2846 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2847 RegsToPass[i].second.getValueType()));
2849 // Add a register mask operand representing the call-preserved registers.
2850 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2851 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2852 assert(Mask && "Missing call preserved mask for calling convention");
2853 Ops.push_back(DAG.getRegisterMask(Mask));
2855 if (InFlag.getNode())
2856 Ops.push_back(InFlag);
2858 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2859 InFlag = Chain.getValue(1);
2861 // Create the CALLSEQ_END node.
2862 Chain = DAG.getCALLSEQ_END(Chain,
2863 DAG.getIntPtrConstant(NextStackOffset, true),
2864 DAG.getIntPtrConstant(0, true), InFlag);
2865 InFlag = Chain.getValue(1);
2867 // Handle result values, copying them out of physregs into vregs that we
2869 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2870 Ins, dl, DAG, InVals);
2873 /// LowerCallResult - Lower the result values of a call into the
2874 /// appropriate copies out of appropriate physical registers.
2876 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2877 CallingConv::ID CallConv, bool isVarArg,
2878 const SmallVectorImpl<ISD::InputArg> &Ins,
2879 DebugLoc dl, SelectionDAG &DAG,
2880 SmallVectorImpl<SDValue> &InVals) const {
2881 // Assign locations to each value returned by this call.
2882 SmallVector<CCValAssign, 16> RVLocs;
2883 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2884 getTargetMachine(), RVLocs, *DAG.getContext());
2886 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2888 // Copy all of the result registers out of their specified physreg.
2889 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2890 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2891 RVLocs[i].getValVT(), InFlag).getValue(1);
2892 InFlag = Chain.getValue(2);
2893 InVals.push_back(Chain.getValue(0));
2899 //===----------------------------------------------------------------------===//
2900 // Formal Arguments Calling Convention Implementation
2901 //===----------------------------------------------------------------------===//
2902 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2903 std::vector<SDValue>& OutChains,
2904 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2905 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2906 const Argument *FuncArg) {
2907 unsigned LocMem = VA.getLocMemOffset();
2908 unsigned FirstWord = LocMem / 4;
2910 // copy register A0 - A3 to frame object
2911 for (unsigned i = 0; i < NumWords; ++i) {
2912 unsigned CurWord = FirstWord + i;
2913 if (CurWord >= O32IntRegsSize)
2916 unsigned SrcReg = O32IntRegs[CurWord];
2917 unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
2918 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2919 DAG.getConstant(i * 4, MVT::i32));
2920 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2921 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2923 OutChains.push_back(Store);
2927 // Create frame object on stack and copy registers used for byval passing to it.
2929 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2930 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2931 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2932 MachineFrameInfo *MFI, bool IsRegLoc,
2933 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2934 EVT PtrTy, const Argument *FuncArg) {
2935 const uint16_t *Reg = Mips64IntRegs + 8;
2936 int FOOffset; // Frame object offset from virtual frame pointer.
2939 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2940 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2943 FOOffset = VA.getLocMemOffset();
2945 // Create frame object.
2946 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2947 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2948 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2949 InVals.push_back(FIN);
2951 // Copy arg registers.
2952 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2954 unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
2955 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2956 DAG.getConstant(I * 8, PtrTy));
2957 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2958 StorePtr, MachinePointerInfo(FuncArg, I * 8),
2960 OutChains.push_back(Store);
2966 /// LowerFormalArguments - transform physical registers into virtual registers
2967 /// and generate load operations for arguments places on the stack.
2969 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2970 CallingConv::ID CallConv,
2972 const SmallVectorImpl<ISD::InputArg> &Ins,
2973 DebugLoc dl, SelectionDAG &DAG,
2974 SmallVectorImpl<SDValue> &InVals)
2976 MachineFunction &MF = DAG.getMachineFunction();
2977 MachineFrameInfo *MFI = MF.getFrameInfo();
2978 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2980 MipsFI->setVarArgsFrameIndex(0);
2982 // Used with vargs to acumulate store chains.
2983 std::vector<SDValue> OutChains;
2985 // Assign locations to all of the incoming arguments.
2986 SmallVector<CCValAssign, 16> ArgLocs;
2987 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2988 getTargetMachine(), ArgLocs, *DAG.getContext());
2990 if (CallConv == CallingConv::Fast)
2991 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FastCC);
2993 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2995 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2997 Function::const_arg_iterator FuncArg =
2998 DAG.getMachineFunction().getFunction()->arg_begin();
2999 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
3001 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
3002 CCValAssign &VA = ArgLocs[i];
3003 EVT ValVT = VA.getValVT();
3004 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3005 bool IsRegLoc = VA.isRegLoc();
3007 if (Flags.isByVal()) {
3008 assert(Flags.getByValSize() &&
3009 "ByVal args of size 0 should have been ignored by front-end.");
3011 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
3012 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
3014 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3015 InVals.push_back(FIN);
3016 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
3019 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
3020 MFI, IsRegLoc, InVals, MipsFI,
3021 getPointerTy(), &*FuncArg);
3025 // Arguments stored on registers
3027 EVT RegVT = VA.getLocVT();
3028 unsigned ArgReg = VA.getLocReg();
3029 const TargetRegisterClass *RC;
3031 if (RegVT == MVT::i32)
3032 RC = &Mips::CPURegsRegClass;
3033 else if (RegVT == MVT::i64)
3034 RC = &Mips::CPU64RegsRegClass;
3035 else if (RegVT == MVT::f32)
3036 RC = &Mips::FGR32RegClass;
3037 else if (RegVT == MVT::f64)
3038 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3040 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3042 // Transform the arguments stored on
3043 // physical registers into virtual ones
3044 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3045 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3047 // If this is an 8 or 16-bit value, it has been passed promoted
3048 // to 32 bits. Insert an assert[sz]ext to capture this, then
3049 // truncate to the right size.
3050 if (VA.getLocInfo() != CCValAssign::Full) {
3051 unsigned Opcode = 0;
3052 if (VA.getLocInfo() == CCValAssign::SExt)
3053 Opcode = ISD::AssertSext;
3054 else if (VA.getLocInfo() == CCValAssign::ZExt)
3055 Opcode = ISD::AssertZext;
3057 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3058 DAG.getValueType(ValVT));
3059 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3062 // Handle floating point arguments passed in integer registers.
3063 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3064 (RegVT == MVT::i64 && ValVT == MVT::f64))
3065 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3066 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3067 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3068 getNextIntArgReg(ArgReg), RC);
3069 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3070 if (!Subtarget->isLittle())
3071 std::swap(ArgValue, ArgValue2);
3072 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3073 ArgValue, ArgValue2);
3076 InVals.push_back(ArgValue);
3077 } else { // VA.isRegLoc()
3080 assert(VA.isMemLoc());
3082 // The stack pointer offset is relative to the caller stack frame.
3083 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3084 VA.getLocMemOffset(), true);
3086 // Create load nodes to retrieve arguments from the stack
3087 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3088 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3089 MachinePointerInfo::getFixedStack(LastFI),
3090 false, false, false, 0));
3094 // The mips ABIs for returning structs by value requires that we copy
3095 // the sret argument into $v0 for the return. Save the argument into
3096 // a virtual register so that we can access it from the return points.
3097 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3098 unsigned Reg = MipsFI->getSRetReturnReg();
3100 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
3101 MipsFI->setSRetReturnReg(Reg);
3103 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3104 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3108 unsigned NumOfRegs = IsO32 ? 4 : 8;
3109 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
3110 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
3111 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
3112 const TargetRegisterClass *RC = IsO32 ?
3113 (const TargetRegisterClass*)&Mips::CPURegsRegClass :
3114 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
3115 unsigned RegSize = RC->getSize();
3116 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
3118 // Offset of the first variable argument from stack pointer.
3119 int FirstVaArgOffset;
3121 if (IsO32 || (Idx == NumOfRegs)) {
3123 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
3125 FirstVaArgOffset = RegSlotOffset;
3127 // Record the frame index of the first variable argument
3128 // which is a value necessary to VASTART.
3129 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
3130 MipsFI->setVarArgsFrameIndex(LastFI);
3132 // Copy the integer registers that have not been used for argument passing
3133 // to the argument register save area. For O32, the save area is allocated
3134 // in the caller's stack frame, while for N32/64, it is allocated in the
3135 // callee's stack frame.
3136 for (int StackOffset = RegSlotOffset;
3137 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
3138 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
3139 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3140 MVT::getIntegerVT(RegSize * 8));
3141 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
3142 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
3143 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
3144 MachinePointerInfo(), false, false, 0));
3148 MipsFI->setLastInArgFI(LastFI);
3150 // All stores are grouped in one node to allow the matching between
3151 // the size of Ins and InVals. This only happens when on varg functions
3152 if (!OutChains.empty()) {
3153 OutChains.push_back(Chain);
3154 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3155 &OutChains[0], OutChains.size());
3161 //===----------------------------------------------------------------------===//
3162 // Return Value Calling Convention Implementation
3163 //===----------------------------------------------------------------------===//
3166 MipsTargetLowering::LowerReturn(SDValue Chain,
3167 CallingConv::ID CallConv, bool isVarArg,
3168 const SmallVectorImpl<ISD::OutputArg> &Outs,
3169 const SmallVectorImpl<SDValue> &OutVals,
3170 DebugLoc dl, SelectionDAG &DAG) const {
3172 // CCValAssign - represent the assignment of
3173 // the return value to a location
3174 SmallVector<CCValAssign, 16> RVLocs;
3176 // CCState - Info about the registers and stack slot.
3177 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3178 getTargetMachine(), RVLocs, *DAG.getContext());
3180 // Analize return values.
3181 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3183 // If this is the first return lowered for this function, add
3184 // the regs to the liveout set for the function.
3185 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3186 for (unsigned i = 0; i != RVLocs.size(); ++i)
3187 if (RVLocs[i].isRegLoc())
3188 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3193 // Copy the result values into the output registers.
3194 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3195 CCValAssign &VA = RVLocs[i];
3196 assert(VA.isRegLoc() && "Can only return in registers!");
3198 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3200 // guarantee that all emitted copies are
3201 // stuck together, avoiding something bad
3202 Flag = Chain.getValue(1);
3205 // The mips ABIs for returning structs by value requires that we copy
3206 // the sret argument into $v0 for the return. We saved the argument into
3207 // a virtual register in the entry block, so now we copy the value out
3209 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3210 MachineFunction &MF = DAG.getMachineFunction();
3211 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3212 unsigned Reg = MipsFI->getSRetReturnReg();
3215 llvm_unreachable("sret virtual register not created in the entry block");
3216 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3218 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3219 Flag = Chain.getValue(1);
3222 // Return on Mips is always a "jr $ra"
3224 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3225 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
3227 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3228 Chain, DAG.getRegister(Mips::RA, MVT::i32));
3231 //===----------------------------------------------------------------------===//
3232 // Mips Inline Assembly Support
3233 //===----------------------------------------------------------------------===//
3235 /// getConstraintType - Given a constraint letter, return the type of
3236 /// constraint it is for this target.
3237 MipsTargetLowering::ConstraintType MipsTargetLowering::
3238 getConstraintType(const std::string &Constraint) const
3240 // Mips specific constrainy
3241 // GCC config/mips/constraints.md
3243 // 'd' : An address register. Equivalent to r
3244 // unless generating MIPS16 code.
3245 // 'y' : Equivalent to r; retained for
3246 // backwards compatibility.
3247 // 'c' : A register suitable for use in an indirect
3248 // jump. This will always be $25 for -mabicalls.
3249 // 'l' : The lo register. 1 word storage.
3250 // 'x' : The hilo register pair. Double word storage.
3251 if (Constraint.size() == 1) {
3252 switch (Constraint[0]) {
3260 return C_RegisterClass;
3263 return TargetLowering::getConstraintType(Constraint);
3266 /// Examine constraint type and operand type and determine a weight value.
3267 /// This object must already have been set up with the operand type
3268 /// and the current alternative constraint selected.
3269 TargetLowering::ConstraintWeight
3270 MipsTargetLowering::getSingleConstraintMatchWeight(
3271 AsmOperandInfo &info, const char *constraint) const {
3272 ConstraintWeight weight = CW_Invalid;
3273 Value *CallOperandVal = info.CallOperandVal;
3274 // If we don't have a value, we can't do a match,
3275 // but allow it at the lowest weight.
3276 if (CallOperandVal == NULL)
3278 Type *type = CallOperandVal->getType();
3279 // Look at the constraint type.
3280 switch (*constraint) {
3282 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3286 if (type->isIntegerTy())
3287 weight = CW_Register;
3290 if (type->isFloatTy())
3291 weight = CW_Register;
3293 case 'c': // $25 for indirect jumps
3294 case 'l': // lo register
3295 case 'x': // hilo register pair
3296 if (type->isIntegerTy())
3297 weight = CW_SpecificReg;
3299 case 'I': // signed 16 bit immediate
3300 case 'J': // integer zero
3301 case 'K': // unsigned 16 bit immediate
3302 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3303 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3304 case 'O': // signed 15 bit immediate (+- 16383)
3305 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3306 if (isa<ConstantInt>(CallOperandVal))
3307 weight = CW_Constant;
3313 /// Given a register class constraint, like 'r', if this corresponds directly
3314 /// to an LLVM register class, return a register of 0 and the register class
3316 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3317 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3319 if (Constraint.size() == 1) {
3320 switch (Constraint[0]) {
3321 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3322 case 'y': // Same as 'r'. Exists for compatibility.
3324 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3325 return std::make_pair(0U, &Mips::CPURegsRegClass);
3326 if (VT == MVT::i64 && HasMips64)
3327 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3328 // This will generate an error message
3329 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3332 return std::make_pair(0U, &Mips::FGR32RegClass);
3333 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3334 if (Subtarget->isFP64bit())
3335 return std::make_pair(0U, &Mips::FGR64RegClass);
3336 return std::make_pair(0U, &Mips::AFGR64RegClass);
3339 case 'c': // register suitable for indirect jump
3341 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3342 assert(VT == MVT::i64 && "Unexpected type.");
3343 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3344 case 'l': // register suitable for indirect jump
3346 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3347 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3348 case 'x': // register suitable for indirect jump
3349 // Fixme: Not triggering the use of both hi and low
3350 // This will generate an error message
3351 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3354 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3357 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3358 /// vector. If it is invalid, don't add anything to Ops.
3359 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3360 std::string &Constraint,
3361 std::vector<SDValue>&Ops,
3362 SelectionDAG &DAG) const {
3363 SDValue Result(0, 0);
3365 // Only support length 1 constraints for now.
3366 if (Constraint.length() > 1) return;
3368 char ConstraintLetter = Constraint[0];
3369 switch (ConstraintLetter) {
3370 default: break; // This will fall through to the generic implementation
3371 case 'I': // Signed 16 bit constant
3372 // If this fails, the parent routine will give an error
3373 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3374 EVT Type = Op.getValueType();
3375 int64_t Val = C->getSExtValue();
3376 if (isInt<16>(Val)) {
3377 Result = DAG.getTargetConstant(Val, Type);
3382 case 'J': // integer zero
3383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3384 EVT Type = Op.getValueType();
3385 int64_t Val = C->getZExtValue();
3387 Result = DAG.getTargetConstant(0, Type);
3392 case 'K': // unsigned 16 bit immediate
3393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3394 EVT Type = Op.getValueType();
3395 uint64_t Val = (uint64_t)C->getZExtValue();
3396 if (isUInt<16>(Val)) {
3397 Result = DAG.getTargetConstant(Val, Type);
3402 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3404 EVT Type = Op.getValueType();
3405 int64_t Val = C->getSExtValue();
3406 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3407 Result = DAG.getTargetConstant(Val, Type);
3412 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3413 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3414 EVT Type = Op.getValueType();
3415 int64_t Val = C->getSExtValue();
3416 if ((Val >= -65535) && (Val <= -1)) {
3417 Result = DAG.getTargetConstant(Val, Type);
3422 case 'O': // signed 15 bit immediate
3423 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3424 EVT Type = Op.getValueType();
3425 int64_t Val = C->getSExtValue();
3426 if ((isInt<15>(Val))) {
3427 Result = DAG.getTargetConstant(Val, Type);
3432 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3434 EVT Type = Op.getValueType();
3435 int64_t Val = C->getSExtValue();
3436 if ((Val <= 65535) && (Val >= 1)) {
3437 Result = DAG.getTargetConstant(Val, Type);
3444 if (Result.getNode()) {
3445 Ops.push_back(Result);
3449 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3453 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3454 // The Mips target isn't yet aware of offsets.
3458 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3459 if (VT != MVT::f32 && VT != MVT::f64)
3461 if (Imm.isNegZero())
3463 return Imm.isZero();
3466 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3468 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3470 return TargetLowering::getJumpTableEncoding();