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 "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.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"
39 // If I is a shifted mask, set the size (Size) and the first bit of the
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43 if (!isShiftedMask_64(I))
46 Size = CountPopulation_64(I);
47 Pos = CountTrailingZeros_64(I);
51 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
52 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
53 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
56 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
58 case MipsISD::JmpLink: return "MipsISD::JmpLink";
59 case MipsISD::Hi: return "MipsISD::Hi";
60 case MipsISD::Lo: return "MipsISD::Lo";
61 case MipsISD::GPRel: return "MipsISD::GPRel";
62 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
63 case MipsISD::Ret: return "MipsISD::Ret";
64 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
65 case MipsISD::FPCmp: return "MipsISD::FPCmp";
66 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
67 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
68 case MipsISD::FPRound: return "MipsISD::FPRound";
69 case MipsISD::MAdd: return "MipsISD::MAdd";
70 case MipsISD::MAddu: return "MipsISD::MAddu";
71 case MipsISD::MSub: return "MipsISD::MSub";
72 case MipsISD::MSubu: return "MipsISD::MSubu";
73 case MipsISD::DivRem: return "MipsISD::DivRem";
74 case MipsISD::DivRemU: return "MipsISD::DivRemU";
75 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
76 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
77 case MipsISD::Wrapper: return "MipsISD::Wrapper";
78 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
79 case MipsISD::Sync: return "MipsISD::Sync";
80 case MipsISD::Ext: return "MipsISD::Ext";
81 case MipsISD::Ins: return "MipsISD::Ins";
87 MipsTargetLowering(MipsTargetMachine &TM)
88 : TargetLowering(TM, new MipsTargetObjectFile()),
89 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
90 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
91 IsO32(Subtarget->isABI_O32()) {
93 // Mips does not have i1 type, so use i32 for
94 // setcc operations results (slt, sgt, ...).
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
98 // Set up the register classes
99 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
102 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
104 if (!TM.Options.UseSoftFloat) {
105 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
107 // When dealing with single precision only, use libcalls
108 if (!Subtarget->isSingleFloat()) {
110 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
112 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
116 // Load extented operations for i1 types must be promoted
117 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
118 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121 // MIPS doesn't have extending float->double load/store
122 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
123 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
125 // Used by legalize types to correctly generate the setcc result.
126 // Without this, every float setcc comes with a AND/OR with the result,
127 // we don't want this, since the fpcmp result goes to a flag register,
128 // which is used implicitly by brcond and select operations.
129 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
131 // Mips Custom Operations
132 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
133 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
134 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
135 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
136 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
137 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
138 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
139 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
140 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
141 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT, MVT::f64, Custom);
144 setOperationAction(ISD::SELECT, MVT::i32, Custom);
145 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
146 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
147 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
148 setOperationAction(ISD::VASTART, MVT::Other, Custom);
150 setOperationAction(ISD::SDIV, MVT::i32, Expand);
151 setOperationAction(ISD::SREM, MVT::i32, Expand);
152 setOperationAction(ISD::UDIV, MVT::i32, Expand);
153 setOperationAction(ISD::UREM, MVT::i32, Expand);
154 setOperationAction(ISD::SDIV, MVT::i64, Expand);
155 setOperationAction(ISD::SREM, MVT::i64, Expand);
156 setOperationAction(ISD::UDIV, MVT::i64, Expand);
157 setOperationAction(ISD::UREM, MVT::i64, Expand);
159 // Operations not directly supported by Mips.
160 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
161 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
162 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
163 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
164 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
165 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
166 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
167 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
168 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
169 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
170 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
171 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
172 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
173 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
174 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
175 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
176 setOperationAction(ISD::ROTL, MVT::i32, Expand);
177 setOperationAction(ISD::ROTL, MVT::i64, Expand);
179 if (!Subtarget->hasMips32r2())
180 setOperationAction(ISD::ROTR, MVT::i32, Expand);
182 if (!Subtarget->hasMips64r2())
183 setOperationAction(ISD::ROTR, MVT::i64, Expand);
185 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
186 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
187 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
190 setOperationAction(ISD::FSIN, MVT::f32, Expand);
191 setOperationAction(ISD::FSIN, MVT::f64, Expand);
192 setOperationAction(ISD::FCOS, MVT::f32, Expand);
193 setOperationAction(ISD::FCOS, MVT::f64, Expand);
194 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
195 setOperationAction(ISD::FPOW, MVT::f32, Expand);
196 setOperationAction(ISD::FPOW, MVT::f64, Expand);
197 setOperationAction(ISD::FLOG, MVT::f32, Expand);
198 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
199 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
200 setOperationAction(ISD::FEXP, MVT::f32, Expand);
201 setOperationAction(ISD::FMA, MVT::f32, Expand);
202 setOperationAction(ISD::FMA, MVT::f64, Expand);
204 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
205 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
206 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
207 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
209 setOperationAction(ISD::VAARG, MVT::Other, Expand);
210 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
211 setOperationAction(ISD::VAEND, MVT::Other, Expand);
213 // Use the default for now
214 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
215 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
217 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
218 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
220 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
221 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
222 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
223 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
225 setInsertFencesForAtomic(true);
227 if (Subtarget->isSingleFloat())
228 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
230 if (!Subtarget->hasSEInReg()) {
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
235 if (!Subtarget->hasBitCount()) {
236 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
237 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
240 if (!Subtarget->hasSwap()) {
241 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
242 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
245 setTargetDAGCombine(ISD::ADDE);
246 setTargetDAGCombine(ISD::SUBE);
247 setTargetDAGCombine(ISD::SDIVREM);
248 setTargetDAGCombine(ISD::UDIVREM);
249 setTargetDAGCombine(ISD::SETCC);
250 setTargetDAGCombine(ISD::AND);
251 setTargetDAGCombine(ISD::OR);
253 setMinFunctionAlignment(HasMips64 ? 3 : 2);
255 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
256 computeRegisterProperties();
258 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
259 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
262 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
263 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
271 return Subtarget->hasMips32r2Or64();
277 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
282 // Transforms a subgraph in CurDAG if the following pattern is found:
283 // (addc multLo, Lo0), (adde multHi, Hi0),
285 // multHi/Lo: product of multiplication
286 // Lo0: initial value of Lo register
287 // Hi0: initial value of Hi register
288 // Return true if pattern matching was successful.
289 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
290 // ADDENode's second operand must be a flag output of an ADDC node in order
291 // for the matching to be successful.
292 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
294 if (ADDCNode->getOpcode() != ISD::ADDC)
297 SDValue MultHi = ADDENode->getOperand(0);
298 SDValue MultLo = ADDCNode->getOperand(0);
299 SDNode* MultNode = MultHi.getNode();
300 unsigned MultOpc = MultHi.getOpcode();
302 // MultHi and MultLo must be generated by the same node,
303 if (MultLo.getNode() != MultNode)
306 // and it must be a multiplication.
307 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
310 // MultLo amd MultHi must be the first and second output of MultNode
312 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
315 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
316 // of the values of MultNode, in which case MultNode will be removed in later
318 // If there exist users other than ADDENode or ADDCNode, this function returns
319 // here, which will result in MultNode being mapped to a single MULT
320 // instruction node rather than a pair of MULT and MADD instructions being
322 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
325 SDValue Chain = CurDAG->getEntryNode();
326 DebugLoc dl = ADDENode->getDebugLoc();
328 // create MipsMAdd(u) node
329 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
331 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
332 MultNode->getOperand(0),// Factor 0
333 MultNode->getOperand(1),// Factor 1
334 ADDCNode->getOperand(1),// Lo0
335 ADDENode->getOperand(1));// Hi0
337 // create CopyFromReg nodes
338 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
340 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
342 CopyFromLo.getValue(2));
344 // replace uses of adde and addc here
345 if (!SDValue(ADDCNode, 0).use_empty())
346 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
348 if (!SDValue(ADDENode, 0).use_empty())
349 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
355 // Transforms a subgraph in CurDAG if the following pattern is found:
356 // (addc Lo0, multLo), (sube Hi0, multHi),
358 // multHi/Lo: product of multiplication
359 // Lo0: initial value of Lo register
360 // Hi0: initial value of Hi register
361 // Return true if pattern matching was successful.
362 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
363 // SUBENode's second operand must be a flag output of an SUBC node in order
364 // for the matching to be successful.
365 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
367 if (SUBCNode->getOpcode() != ISD::SUBC)
370 SDValue MultHi = SUBENode->getOperand(1);
371 SDValue MultLo = SUBCNode->getOperand(1);
372 SDNode* MultNode = MultHi.getNode();
373 unsigned MultOpc = MultHi.getOpcode();
375 // MultHi and MultLo must be generated by the same node,
376 if (MultLo.getNode() != MultNode)
379 // and it must be a multiplication.
380 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
383 // MultLo amd MultHi must be the first and second output of MultNode
385 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
388 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
389 // of the values of MultNode, in which case MultNode will be removed in later
391 // If there exist users other than SUBENode or SUBCNode, this function returns
392 // here, which will result in MultNode being mapped to a single MULT
393 // instruction node rather than a pair of MULT and MSUB instructions being
395 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
398 SDValue Chain = CurDAG->getEntryNode();
399 DebugLoc dl = SUBENode->getDebugLoc();
401 // create MipsSub(u) node
402 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
404 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
405 MultNode->getOperand(0),// Factor 0
406 MultNode->getOperand(1),// Factor 1
407 SUBCNode->getOperand(0),// Lo0
408 SUBENode->getOperand(0));// Hi0
410 // create CopyFromReg nodes
411 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
413 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
415 CopyFromLo.getValue(2));
417 // replace uses of sube and subc here
418 if (!SDValue(SUBCNode, 0).use_empty())
419 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
421 if (!SDValue(SUBENode, 0).use_empty())
422 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
427 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
428 TargetLowering::DAGCombinerInfo &DCI,
429 const MipsSubtarget* Subtarget) {
430 if (DCI.isBeforeLegalize())
433 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
435 return SDValue(N, 0);
440 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
441 TargetLowering::DAGCombinerInfo &DCI,
442 const MipsSubtarget* Subtarget) {
443 if (DCI.isBeforeLegalize())
446 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
448 return SDValue(N, 0);
453 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
454 TargetLowering::DAGCombinerInfo &DCI,
455 const MipsSubtarget* Subtarget) {
456 if (DCI.isBeforeLegalizeOps())
459 EVT Ty = N->getValueType(0);
460 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
461 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
462 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
464 DebugLoc dl = N->getDebugLoc();
466 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
467 N->getOperand(0), N->getOperand(1));
468 SDValue InChain = DAG.getEntryNode();
469 SDValue InGlue = DivRem;
472 if (N->hasAnyUseOfValue(0)) {
473 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
475 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
476 InChain = CopyFromLo.getValue(1);
477 InGlue = CopyFromLo.getValue(2);
481 if (N->hasAnyUseOfValue(1)) {
482 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
484 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
490 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
492 default: llvm_unreachable("Unknown fp condition code!");
494 case ISD::SETOEQ: return Mips::FCOND_OEQ;
495 case ISD::SETUNE: return Mips::FCOND_UNE;
497 case ISD::SETOLT: return Mips::FCOND_OLT;
499 case ISD::SETOGT: return Mips::FCOND_OGT;
501 case ISD::SETOLE: return Mips::FCOND_OLE;
503 case ISD::SETOGE: return Mips::FCOND_OGE;
504 case ISD::SETULT: return Mips::FCOND_ULT;
505 case ISD::SETULE: return Mips::FCOND_ULE;
506 case ISD::SETUGT: return Mips::FCOND_UGT;
507 case ISD::SETUGE: return Mips::FCOND_UGE;
508 case ISD::SETUO: return Mips::FCOND_UN;
509 case ISD::SETO: return Mips::FCOND_OR;
511 case ISD::SETONE: return Mips::FCOND_ONE;
512 case ISD::SETUEQ: return Mips::FCOND_UEQ;
517 // Returns true if condition code has to be inverted.
518 static bool InvertFPCondCode(Mips::CondCode CC) {
519 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
522 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
523 "Illegal Condition Code");
528 // Creates and returns an FPCmp node from a setcc node.
529 // Returns Op if setcc is not a floating point comparison.
530 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
531 // must be a SETCC node
532 if (Op.getOpcode() != ISD::SETCC)
535 SDValue LHS = Op.getOperand(0);
537 if (!LHS.getValueType().isFloatingPoint())
540 SDValue RHS = Op.getOperand(1);
541 DebugLoc dl = Op.getDebugLoc();
543 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
544 // node if necessary.
545 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
547 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
548 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
551 // Creates and returns a CMovFPT/F node.
552 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
553 SDValue False, DebugLoc DL) {
554 bool invert = InvertFPCondCode((Mips::CondCode)
555 cast<ConstantSDNode>(Cond.getOperand(2))
558 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
559 True.getValueType(), True, False, Cond);
562 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
563 TargetLowering::DAGCombinerInfo &DCI,
564 const MipsSubtarget* Subtarget) {
565 if (DCI.isBeforeLegalizeOps())
568 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
570 if (Cond.getOpcode() != MipsISD::FPCmp)
573 SDValue True = DAG.getConstant(1, MVT::i32);
574 SDValue False = DAG.getConstant(0, MVT::i32);
576 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
579 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
580 TargetLowering::DAGCombinerInfo &DCI,
581 const MipsSubtarget* Subtarget) {
582 // Pattern match EXT.
583 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
584 // => ext $dst, $src, size, pos
585 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
588 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
589 unsigned ShiftRightOpc = ShiftRight.getOpcode();
591 // Op's first operand must be a shift right.
592 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
595 // The second operand of the shift must be an immediate.
597 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
600 uint64_t Pos = CN->getZExtValue();
601 uint64_t SMPos, SMSize;
603 // Op's second operand must be a shifted mask.
604 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
605 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
608 // Return if the shifted mask does not start at bit 0 or the sum of its size
609 // and Pos exceeds the word's size.
610 EVT ValTy = N->getValueType(0);
611 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
614 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
615 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
616 DAG.getConstant(SMSize, MVT::i32));
619 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
620 TargetLowering::DAGCombinerInfo &DCI,
621 const MipsSubtarget* Subtarget) {
622 // Pattern match INS.
623 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
624 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
625 // => ins $dst, $src, size, pos, $src1
626 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
629 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
630 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
633 // See if Op's first operand matches (and $src1 , mask0).
634 if (And0.getOpcode() != ISD::AND)
637 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
638 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
641 // See if Op's second operand matches (and (shl $src, pos), mask1).
642 if (And1.getOpcode() != ISD::AND)
645 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
646 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
649 // The shift masks must have the same position and size.
650 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
653 SDValue Shl = And1.getOperand(0);
654 if (Shl.getOpcode() != ISD::SHL)
657 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
660 unsigned Shamt = CN->getZExtValue();
662 // Return if the shift amount and the first bit position of mask are not the
664 EVT ValTy = N->getValueType(0);
665 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
668 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
669 DAG.getConstant(SMPos0, MVT::i32),
670 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
673 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
675 SelectionDAG &DAG = DCI.DAG;
676 unsigned opc = N->getOpcode();
681 return PerformADDECombine(N, DAG, DCI, Subtarget);
683 return PerformSUBECombine(N, DAG, DCI, Subtarget);
686 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
688 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
690 return PerformANDCombine(N, DAG, DCI, Subtarget);
692 return PerformORCombine(N, DAG, DCI, Subtarget);
698 SDValue MipsTargetLowering::
699 LowerOperation(SDValue Op, SelectionDAG &DAG) const
701 switch (Op.getOpcode())
703 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
704 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
705 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
706 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
707 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
708 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
709 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
710 case ISD::SELECT: return LowerSELECT(Op, DAG);
711 case ISD::VASTART: return LowerVASTART(Op, DAG);
712 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
713 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
714 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
715 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
720 //===----------------------------------------------------------------------===//
721 // Lower helper functions
722 //===----------------------------------------------------------------------===//
724 // AddLiveIn - This helper function adds the specified physical register to the
725 // MachineFunction as a live in value. It also creates a corresponding
726 // virtual register for it.
728 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
730 assert(RC->contains(PReg) && "Not the correct regclass!");
731 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
732 MF.getRegInfo().addLiveIn(PReg, VReg);
736 // Get fp branch code (not opcode) from condition code.
737 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
738 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
739 return Mips::BRANCH_T;
741 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
742 "Invalid CondCode.");
744 return Mips::BRANCH_F;
748 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
750 const MipsSubtarget* Subtarget,
751 const TargetInstrInfo *TII,
752 bool isFPCmp, unsigned Opc) {
753 // There is no need to expand CMov instructions if target has
754 // conditional moves.
755 if (Subtarget->hasCondMov())
758 // To "insert" a SELECT_CC instruction, we actually have to insert the
759 // diamond control-flow pattern. The incoming instruction knows the
760 // destination vreg to set, the condition code register to branch on, the
761 // true/false values to select between, and a branch opcode to use.
762 const BasicBlock *LLVM_BB = BB->getBasicBlock();
763 MachineFunction::iterator It = BB;
770 // bNE r1, r0, copy1MBB
771 // fallthrough --> copy0MBB
772 MachineBasicBlock *thisMBB = BB;
773 MachineFunction *F = BB->getParent();
774 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
775 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
776 F->insert(It, copy0MBB);
777 F->insert(It, sinkMBB);
779 // Transfer the remainder of BB and its successor edges to sinkMBB.
780 sinkMBB->splice(sinkMBB->begin(), BB,
781 llvm::next(MachineBasicBlock::iterator(MI)),
783 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
785 // Next, add the true and fallthrough blocks as its successors.
786 BB->addSuccessor(copy0MBB);
787 BB->addSuccessor(sinkMBB);
789 // Emit the right instruction according to the type of the operands compared
791 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
793 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
794 .addReg(Mips::ZERO).addMBB(sinkMBB);
798 // # fallthrough to sinkMBB
801 // Update machine-CFG edges
802 BB->addSuccessor(sinkMBB);
805 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
810 BuildMI(*BB, BB->begin(), dl,
811 TII->get(Mips::PHI), MI->getOperand(0).getReg())
812 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
813 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
815 BuildMI(*BB, BB->begin(), dl,
816 TII->get(Mips::PHI), MI->getOperand(0).getReg())
817 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
818 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
820 MI->eraseFromParent(); // The pseudo instruction is gone now.
825 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
826 MachineBasicBlock *BB) const {
827 switch (MI->getOpcode()) {
828 default: llvm_unreachable("Unexpected instr type to insert");
829 case Mips::ATOMIC_LOAD_ADD_I8:
830 case Mips::ATOMIC_LOAD_ADD_I8_P8:
831 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
832 case Mips::ATOMIC_LOAD_ADD_I16:
833 case Mips::ATOMIC_LOAD_ADD_I16_P8:
834 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
835 case Mips::ATOMIC_LOAD_ADD_I32:
836 case Mips::ATOMIC_LOAD_ADD_I32_P8:
837 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
838 case Mips::ATOMIC_LOAD_ADD_I64:
839 case Mips::ATOMIC_LOAD_ADD_I64_P8:
840 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
842 case Mips::ATOMIC_LOAD_AND_I8:
843 case Mips::ATOMIC_LOAD_AND_I8_P8:
844 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
845 case Mips::ATOMIC_LOAD_AND_I16:
846 case Mips::ATOMIC_LOAD_AND_I16_P8:
847 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
848 case Mips::ATOMIC_LOAD_AND_I32:
849 case Mips::ATOMIC_LOAD_AND_I32_P8:
850 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
851 case Mips::ATOMIC_LOAD_AND_I64:
852 case Mips::ATOMIC_LOAD_AND_I64_P8:
853 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
855 case Mips::ATOMIC_LOAD_OR_I8:
856 case Mips::ATOMIC_LOAD_OR_I8_P8:
857 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
858 case Mips::ATOMIC_LOAD_OR_I16:
859 case Mips::ATOMIC_LOAD_OR_I16_P8:
860 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
861 case Mips::ATOMIC_LOAD_OR_I32:
862 case Mips::ATOMIC_LOAD_OR_I32_P8:
863 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
864 case Mips::ATOMIC_LOAD_OR_I64:
865 case Mips::ATOMIC_LOAD_OR_I64_P8:
866 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
868 case Mips::ATOMIC_LOAD_XOR_I8:
869 case Mips::ATOMIC_LOAD_XOR_I8_P8:
870 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
871 case Mips::ATOMIC_LOAD_XOR_I16:
872 case Mips::ATOMIC_LOAD_XOR_I16_P8:
873 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
874 case Mips::ATOMIC_LOAD_XOR_I32:
875 case Mips::ATOMIC_LOAD_XOR_I32_P8:
876 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
877 case Mips::ATOMIC_LOAD_XOR_I64:
878 case Mips::ATOMIC_LOAD_XOR_I64_P8:
879 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
881 case Mips::ATOMIC_LOAD_NAND_I8:
882 case Mips::ATOMIC_LOAD_NAND_I8_P8:
883 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
884 case Mips::ATOMIC_LOAD_NAND_I16:
885 case Mips::ATOMIC_LOAD_NAND_I16_P8:
886 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
887 case Mips::ATOMIC_LOAD_NAND_I32:
888 case Mips::ATOMIC_LOAD_NAND_I32_P8:
889 return EmitAtomicBinary(MI, BB, 4, 0, true);
890 case Mips::ATOMIC_LOAD_NAND_I64:
891 case Mips::ATOMIC_LOAD_NAND_I64_P8:
892 return EmitAtomicBinary(MI, BB, 8, 0, true);
894 case Mips::ATOMIC_LOAD_SUB_I8:
895 case Mips::ATOMIC_LOAD_SUB_I8_P8:
896 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
897 case Mips::ATOMIC_LOAD_SUB_I16:
898 case Mips::ATOMIC_LOAD_SUB_I16_P8:
899 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
900 case Mips::ATOMIC_LOAD_SUB_I32:
901 case Mips::ATOMIC_LOAD_SUB_I32_P8:
902 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
903 case Mips::ATOMIC_LOAD_SUB_I64:
904 case Mips::ATOMIC_LOAD_SUB_I64_P8:
905 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
907 case Mips::ATOMIC_SWAP_I8:
908 case Mips::ATOMIC_SWAP_I8_P8:
909 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
910 case Mips::ATOMIC_SWAP_I16:
911 case Mips::ATOMIC_SWAP_I16_P8:
912 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
913 case Mips::ATOMIC_SWAP_I32:
914 case Mips::ATOMIC_SWAP_I32_P8:
915 return EmitAtomicBinary(MI, BB, 4, 0);
916 case Mips::ATOMIC_SWAP_I64:
917 case Mips::ATOMIC_SWAP_I64_P8:
918 return EmitAtomicBinary(MI, BB, 8, 0);
920 case Mips::ATOMIC_CMP_SWAP_I8:
921 case Mips::ATOMIC_CMP_SWAP_I8_P8:
922 return EmitAtomicCmpSwapPartword(MI, BB, 1);
923 case Mips::ATOMIC_CMP_SWAP_I16:
924 case Mips::ATOMIC_CMP_SWAP_I16_P8:
925 return EmitAtomicCmpSwapPartword(MI, BB, 2);
926 case Mips::ATOMIC_CMP_SWAP_I32:
927 case Mips::ATOMIC_CMP_SWAP_I32_P8:
928 return EmitAtomicCmpSwap(MI, BB, 4);
929 case Mips::ATOMIC_CMP_SWAP_I64:
930 case Mips::ATOMIC_CMP_SWAP_I64_P8:
931 return EmitAtomicCmpSwap(MI, BB, 8);
935 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
936 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
938 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
939 unsigned Size, unsigned BinOpcode,
941 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
943 MachineFunction *MF = BB->getParent();
944 MachineRegisterInfo &RegInfo = MF->getRegInfo();
945 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
946 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
947 DebugLoc dl = MI->getDebugLoc();
948 unsigned LL, SC, AND, NOR, ZERO, BEQ;
951 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
952 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
959 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
960 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
963 ZERO = Mips::ZERO_64;
967 unsigned OldVal = MI->getOperand(0).getReg();
968 unsigned Ptr = MI->getOperand(1).getReg();
969 unsigned Incr = MI->getOperand(2).getReg();
971 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
972 unsigned AndRes = RegInfo.createVirtualRegister(RC);
973 unsigned Success = RegInfo.createVirtualRegister(RC);
975 // insert new blocks after the current block
976 const BasicBlock *LLVM_BB = BB->getBasicBlock();
977 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
978 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
979 MachineFunction::iterator It = BB;
981 MF->insert(It, loopMBB);
982 MF->insert(It, exitMBB);
984 // Transfer the remainder of BB and its successor edges to exitMBB.
985 exitMBB->splice(exitMBB->begin(), BB,
986 llvm::next(MachineBasicBlock::iterator(MI)),
988 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
992 // fallthrough --> loopMBB
993 BB->addSuccessor(loopMBB);
994 loopMBB->addSuccessor(loopMBB);
995 loopMBB->addSuccessor(exitMBB);
999 // <binop> storeval, oldval, incr
1000 // sc success, storeval, 0(ptr)
1001 // beq success, $0, loopMBB
1003 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1005 // and andres, oldval, incr
1006 // nor storeval, $0, andres
1007 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1008 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1009 } else if (BinOpcode) {
1010 // <binop> storeval, oldval, incr
1011 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1015 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1016 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1018 MI->eraseFromParent(); // The instruction is gone now.
1024 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1025 MachineBasicBlock *BB,
1026 unsigned Size, unsigned BinOpcode,
1028 assert((Size == 1 || Size == 2) &&
1029 "Unsupported size for EmitAtomicBinaryPartial.");
1031 MachineFunction *MF = BB->getParent();
1032 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1033 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1034 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1035 DebugLoc dl = MI->getDebugLoc();
1036 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1037 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1039 unsigned Dest = MI->getOperand(0).getReg();
1040 unsigned Ptr = MI->getOperand(1).getReg();
1041 unsigned Incr = MI->getOperand(2).getReg();
1043 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1044 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1045 unsigned Mask = RegInfo.createVirtualRegister(RC);
1046 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1047 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1048 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1049 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1050 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1051 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1052 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1053 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1054 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1055 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1056 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1057 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1058 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1059 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1060 unsigned Success = RegInfo.createVirtualRegister(RC);
1062 // insert new blocks after the current block
1063 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1064 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1065 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1066 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1067 MachineFunction::iterator It = BB;
1069 MF->insert(It, loopMBB);
1070 MF->insert(It, sinkMBB);
1071 MF->insert(It, exitMBB);
1073 // Transfer the remainder of BB and its successor edges to exitMBB.
1074 exitMBB->splice(exitMBB->begin(), BB,
1075 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1076 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1078 BB->addSuccessor(loopMBB);
1079 loopMBB->addSuccessor(loopMBB);
1080 loopMBB->addSuccessor(sinkMBB);
1081 sinkMBB->addSuccessor(exitMBB);
1084 // addiu masklsb2,$0,-4 # 0xfffffffc
1085 // and alignedaddr,ptr,masklsb2
1086 // andi ptrlsb2,ptr,3
1087 // sll shiftamt,ptrlsb2,3
1088 // ori maskupper,$0,255 # 0xff
1089 // sll mask,maskupper,shiftamt
1090 // nor mask2,$0,mask
1091 // sll incr2,incr,shiftamt
1093 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1094 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1095 .addReg(Mips::ZERO).addImm(-4);
1096 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1097 .addReg(Ptr).addReg(MaskLSB2);
1098 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1099 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1100 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1101 .addReg(Mips::ZERO).addImm(MaskImm);
1102 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1103 .addReg(ShiftAmt).addReg(MaskUpper);
1104 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1105 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1107 // atomic.load.binop
1109 // ll oldval,0(alignedaddr)
1110 // binop binopres,oldval,incr2
1111 // and newval,binopres,mask
1112 // and maskedoldval0,oldval,mask2
1113 // or storeval,maskedoldval0,newval
1114 // sc success,storeval,0(alignedaddr)
1115 // beq success,$0,loopMBB
1119 // ll oldval,0(alignedaddr)
1120 // and newval,incr2,mask
1121 // and maskedoldval0,oldval,mask2
1122 // or storeval,maskedoldval0,newval
1123 // sc success,storeval,0(alignedaddr)
1124 // beq success,$0,loopMBB
1127 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1129 // and andres, oldval, incr2
1130 // nor binopres, $0, andres
1131 // and newval, binopres, mask
1132 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1133 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1134 .addReg(Mips::ZERO).addReg(AndRes);
1135 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1136 } else if (BinOpcode) {
1137 // <binop> binopres, oldval, incr2
1138 // and newval, binopres, mask
1139 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1140 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1141 } else {// atomic.swap
1142 // and newval, incr2, mask
1143 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1146 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1147 .addReg(OldVal).addReg(Mask2);
1148 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1149 .addReg(MaskedOldVal0).addReg(NewVal);
1150 BuildMI(BB, dl, TII->get(SC), Success)
1151 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1152 BuildMI(BB, dl, TII->get(Mips::BEQ))
1153 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1156 // and maskedoldval1,oldval,mask
1157 // srl srlres,maskedoldval1,shiftamt
1158 // sll sllres,srlres,24
1159 // sra dest,sllres,24
1161 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1163 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1164 .addReg(OldVal).addReg(Mask);
1165 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1166 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1167 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1168 .addReg(SrlRes).addImm(ShiftImm);
1169 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1170 .addReg(SllRes).addImm(ShiftImm);
1172 MI->eraseFromParent(); // The instruction is gone now.
1178 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1179 MachineBasicBlock *BB,
1180 unsigned Size) const {
1181 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1183 MachineFunction *MF = BB->getParent();
1184 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1185 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1186 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1187 DebugLoc dl = MI->getDebugLoc();
1188 unsigned LL, SC, ZERO, BNE, BEQ;
1191 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1192 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1198 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1199 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1200 ZERO = Mips::ZERO_64;
1205 unsigned Dest = MI->getOperand(0).getReg();
1206 unsigned Ptr = MI->getOperand(1).getReg();
1207 unsigned OldVal = MI->getOperand(2).getReg();
1208 unsigned NewVal = MI->getOperand(3).getReg();
1210 unsigned Success = RegInfo.createVirtualRegister(RC);
1212 // insert new blocks after the current block
1213 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1214 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1215 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1216 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1217 MachineFunction::iterator It = BB;
1219 MF->insert(It, loop1MBB);
1220 MF->insert(It, loop2MBB);
1221 MF->insert(It, exitMBB);
1223 // Transfer the remainder of BB and its successor edges to exitMBB.
1224 exitMBB->splice(exitMBB->begin(), BB,
1225 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1226 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1230 // fallthrough --> loop1MBB
1231 BB->addSuccessor(loop1MBB);
1232 loop1MBB->addSuccessor(exitMBB);
1233 loop1MBB->addSuccessor(loop2MBB);
1234 loop2MBB->addSuccessor(loop1MBB);
1235 loop2MBB->addSuccessor(exitMBB);
1239 // bne dest, oldval, exitMBB
1241 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1242 BuildMI(BB, dl, TII->get(BNE))
1243 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1246 // sc success, newval, 0(ptr)
1247 // beq success, $0, loop1MBB
1249 BuildMI(BB, dl, TII->get(SC), Success)
1250 .addReg(NewVal).addReg(Ptr).addImm(0);
1251 BuildMI(BB, dl, TII->get(BEQ))
1252 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1254 MI->eraseFromParent(); // The instruction is gone now.
1260 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1261 MachineBasicBlock *BB,
1262 unsigned Size) const {
1263 assert((Size == 1 || Size == 2) &&
1264 "Unsupported size for EmitAtomicCmpSwapPartial.");
1266 MachineFunction *MF = BB->getParent();
1267 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1268 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1269 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1270 DebugLoc dl = MI->getDebugLoc();
1271 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1272 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1274 unsigned Dest = MI->getOperand(0).getReg();
1275 unsigned Ptr = MI->getOperand(1).getReg();
1276 unsigned CmpVal = MI->getOperand(2).getReg();
1277 unsigned NewVal = MI->getOperand(3).getReg();
1279 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1280 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1281 unsigned Mask = RegInfo.createVirtualRegister(RC);
1282 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1283 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1284 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1285 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1286 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1287 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1288 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1289 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1290 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1291 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1292 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1293 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1294 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1295 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1296 unsigned Success = RegInfo.createVirtualRegister(RC);
1298 // insert new blocks after the current block
1299 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1300 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1301 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1302 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1303 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1304 MachineFunction::iterator It = BB;
1306 MF->insert(It, loop1MBB);
1307 MF->insert(It, loop2MBB);
1308 MF->insert(It, sinkMBB);
1309 MF->insert(It, exitMBB);
1311 // Transfer the remainder of BB and its successor edges to exitMBB.
1312 exitMBB->splice(exitMBB->begin(), BB,
1313 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1314 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1316 BB->addSuccessor(loop1MBB);
1317 loop1MBB->addSuccessor(sinkMBB);
1318 loop1MBB->addSuccessor(loop2MBB);
1319 loop2MBB->addSuccessor(loop1MBB);
1320 loop2MBB->addSuccessor(sinkMBB);
1321 sinkMBB->addSuccessor(exitMBB);
1323 // FIXME: computation of newval2 can be moved to loop2MBB.
1325 // addiu masklsb2,$0,-4 # 0xfffffffc
1326 // and alignedaddr,ptr,masklsb2
1327 // andi ptrlsb2,ptr,3
1328 // sll shiftamt,ptrlsb2,3
1329 // ori maskupper,$0,255 # 0xff
1330 // sll mask,maskupper,shiftamt
1331 // nor mask2,$0,mask
1332 // andi maskedcmpval,cmpval,255
1333 // sll shiftedcmpval,maskedcmpval,shiftamt
1334 // andi maskednewval,newval,255
1335 // sll shiftednewval,maskednewval,shiftamt
1336 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1337 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1338 .addReg(Mips::ZERO).addImm(-4);
1339 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1340 .addReg(Ptr).addReg(MaskLSB2);
1341 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1342 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1343 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1344 .addReg(Mips::ZERO).addImm(MaskImm);
1345 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1346 .addReg(ShiftAmt).addReg(MaskUpper);
1347 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1348 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1349 .addReg(CmpVal).addImm(MaskImm);
1350 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1351 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1352 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1353 .addReg(NewVal).addImm(MaskImm);
1354 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1355 .addReg(ShiftAmt).addReg(MaskedNewVal);
1358 // ll oldval,0(alginedaddr)
1359 // and maskedoldval0,oldval,mask
1360 // bne maskedoldval0,shiftedcmpval,sinkMBB
1362 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1363 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1364 .addReg(OldVal).addReg(Mask);
1365 BuildMI(BB, dl, TII->get(Mips::BNE))
1366 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1369 // and maskedoldval1,oldval,mask2
1370 // or storeval,maskedoldval1,shiftednewval
1371 // sc success,storeval,0(alignedaddr)
1372 // beq success,$0,loop1MBB
1374 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1375 .addReg(OldVal).addReg(Mask2);
1376 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1377 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1378 BuildMI(BB, dl, TII->get(SC), Success)
1379 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1380 BuildMI(BB, dl, TII->get(Mips::BEQ))
1381 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1384 // srl srlres,maskedoldval0,shiftamt
1385 // sll sllres,srlres,24
1386 // sra dest,sllres,24
1388 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1390 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1391 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1392 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1393 .addReg(SrlRes).addImm(ShiftImm);
1394 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1395 .addReg(SllRes).addImm(ShiftImm);
1397 MI->eraseFromParent(); // The instruction is gone now.
1402 //===----------------------------------------------------------------------===//
1403 // Misc Lower Operation implementation
1404 //===----------------------------------------------------------------------===//
1405 SDValue MipsTargetLowering::
1406 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1408 MachineFunction &MF = DAG.getMachineFunction();
1409 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1410 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1412 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1413 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1414 "Cannot lower if the alignment of the allocated space is larger than \
1415 that of the stack.");
1417 SDValue Chain = Op.getOperand(0);
1418 SDValue Size = Op.getOperand(1);
1419 DebugLoc dl = Op.getDebugLoc();
1421 // Get a reference from Mips stack pointer
1422 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1424 // Subtract the dynamic size from the actual stack size to
1425 // obtain the new stack size.
1426 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1428 // The Sub result contains the new stack start address, so it
1429 // must be placed in the stack pointer register.
1430 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1432 // This node always has two return values: a new stack pointer
1433 // value and a chain
1434 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1435 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1436 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1438 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1441 SDValue MipsTargetLowering::
1442 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1444 // The first operand is the chain, the second is the condition, the third is
1445 // the block to branch to if the condition is true.
1446 SDValue Chain = Op.getOperand(0);
1447 SDValue Dest = Op.getOperand(2);
1448 DebugLoc dl = Op.getDebugLoc();
1450 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1452 // Return if flag is not set by a floating point comparison.
1453 if (CondRes.getOpcode() != MipsISD::FPCmp)
1456 SDValue CCNode = CondRes.getOperand(2);
1458 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1459 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1461 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1465 SDValue MipsTargetLowering::
1466 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1468 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1470 // Return if flag is not set by a floating point comparison.
1471 if (Cond.getOpcode() != MipsISD::FPCmp)
1474 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1478 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1479 SelectionDAG &DAG) const {
1480 // FIXME there isn't actually debug info here
1481 DebugLoc dl = Op.getDebugLoc();
1482 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1484 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1485 SDVTList VTs = DAG.getVTList(MVT::i32);
1487 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1489 // %gp_rel relocation
1490 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1491 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1493 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1494 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1495 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1497 // %hi/%lo relocation
1498 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1500 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1502 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1503 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1504 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1507 EVT ValTy = Op.getValueType();
1508 bool HasGotOfst = (GV->hasInternalLinkage() ||
1509 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1510 unsigned GotFlag = IsN64 ?
1511 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1512 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1513 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1514 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1515 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1516 MachinePointerInfo(), false, false, false, 0);
1517 // On functions and global targets not internal linked only
1518 // a load from got/GP is necessary for PIC to work.
1521 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1522 IsN64 ? MipsII::MO_GOT_OFST :
1524 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1525 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1528 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1529 SelectionDAG &DAG) const {
1530 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1531 // FIXME there isn't actually debug info here
1532 DebugLoc dl = Op.getDebugLoc();
1534 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1535 // %hi/%lo relocation
1536 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1537 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1538 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1539 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1540 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1543 EVT ValTy = Op.getValueType();
1544 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1545 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1546 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1547 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1548 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1549 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1550 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1551 MachinePointerInfo(), false, false, false, 0);
1552 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1553 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1556 SDValue MipsTargetLowering::
1557 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1559 // If the relocation model is PIC, use the General Dynamic TLS Model or
1560 // Local Dynamic TLS model, otherwise use the Initial Exec or
1561 // Local Exec TLS Model.
1563 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1564 DebugLoc dl = GA->getDebugLoc();
1565 const GlobalValue *GV = GA->getGlobal();
1566 EVT PtrVT = getPointerTy();
1568 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1569 // General Dynamic TLS Model
1570 bool LocalDynamic = GV->hasInternalLinkage();
1571 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1572 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1573 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1574 GetGlobalReg(DAG, PtrVT), TGA);
1575 unsigned PtrSize = PtrVT.getSizeInBits();
1576 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1578 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1582 Entry.Node = Argument;
1584 Args.push_back(Entry);
1586 std::pair<SDValue, SDValue> CallResult =
1587 LowerCallTo(DAG.getEntryNode(), PtrTy,
1588 false, false, false, false, 0, CallingConv::C,
1589 /*isTailCall=*/false, /*doesNotRet=*/false,
1590 /*isReturnValueUsed=*/true,
1591 TlsGetAddr, Args, DAG, dl);
1593 SDValue Ret = CallResult.first;
1598 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1599 MipsII::MO_DTPREL_HI);
1600 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1601 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1602 MipsII::MO_DTPREL_LO);
1603 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1604 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1605 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1609 if (GV->isDeclaration()) {
1610 // Initial Exec TLS Model
1611 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1612 MipsII::MO_GOTTPREL);
1613 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1615 Offset = DAG.getLoad(PtrVT, dl,
1616 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1617 false, false, false, 0);
1619 // Local Exec TLS Model
1620 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1621 MipsII::MO_TPREL_HI);
1622 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1623 MipsII::MO_TPREL_LO);
1624 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1625 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1626 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1629 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1630 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1633 SDValue MipsTargetLowering::
1634 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1636 SDValue HiPart, JTI, JTILo;
1637 // FIXME there isn't actually debug info here
1638 DebugLoc dl = Op.getDebugLoc();
1639 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1640 EVT PtrVT = Op.getValueType();
1641 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1643 if (!IsPIC && !IsN64) {
1644 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1645 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1646 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1647 } else {// Emit Load from Global Pointer
1648 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1649 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1650 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1651 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1653 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1654 MachinePointerInfo(), false, false, false, 0);
1655 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1658 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1659 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1662 SDValue MipsTargetLowering::
1663 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1666 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1667 const Constant *C = N->getConstVal();
1668 // FIXME there isn't actually debug info here
1669 DebugLoc dl = Op.getDebugLoc();
1671 // gp_rel relocation
1672 // FIXME: we should reference the constant pool using small data sections,
1673 // but the asm printer currently doesn't support this feature without
1674 // hacking it. This feature should come soon so we can uncomment the
1676 //if (IsInSmallSection(C->getType())) {
1677 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1678 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1679 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1681 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1682 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1683 N->getOffset(), MipsII::MO_ABS_HI);
1684 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1685 N->getOffset(), MipsII::MO_ABS_LO);
1686 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1687 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1688 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1690 EVT ValTy = Op.getValueType();
1691 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1692 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1693 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1694 N->getOffset(), GOTFlag);
1695 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1696 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1697 MachinePointerInfo::getConstantPool(), false,
1699 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1700 N->getOffset(), OFSTFlag);
1701 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1702 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1708 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1709 MachineFunction &MF = DAG.getMachineFunction();
1710 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1712 DebugLoc dl = Op.getDebugLoc();
1713 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1716 // vastart just stores the address of the VarArgsFrameIndex slot into the
1717 // memory location argument.
1718 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1719 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1720 MachinePointerInfo(SV), false, false, 0);
1723 // Called if the size of integer registers is large enough to hold the whole
1724 // floating point number.
1725 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1726 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1727 EVT ValTy = Op.getValueType();
1728 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1729 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1730 DebugLoc dl = Op.getDebugLoc();
1731 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1732 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1733 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1734 DAG.getConstant(Mask - 1, IntValTy));
1735 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1736 DAG.getConstant(Mask, IntValTy));
1737 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1738 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1741 // Called if the size of integer registers is not large enough to hold the whole
1742 // floating point number (e.g. f64 & 32-bit integer register).
1744 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1746 // Use ext/ins instructions if target architecture is Mips32r2.
1747 // Eliminate redundant mfc1 and mtc1 instructions.
1748 unsigned LoIdx = 0, HiIdx = 1;
1751 std::swap(LoIdx, HiIdx);
1753 DebugLoc dl = Op.getDebugLoc();
1754 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1756 DAG.getConstant(LoIdx, MVT::i32));
1757 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1758 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1759 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1760 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1761 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1762 DAG.getConstant(0x7fffffff, MVT::i32));
1763 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1764 DAG.getConstant(0x80000000, MVT::i32));
1765 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1768 std::swap(Word0, Word1);
1770 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1774 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1775 EVT Ty = Op.getValueType();
1777 assert(Ty == MVT::f32 || Ty == MVT::f64);
1779 if (Ty == MVT::f32 || HasMips64)
1780 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1782 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1785 SDValue MipsTargetLowering::
1786 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1788 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1789 "Frame address can only be determined for current frame.");
1791 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1792 MFI->setFrameAddressIsTaken(true);
1793 EVT VT = Op.getValueType();
1794 DebugLoc dl = Op.getDebugLoc();
1795 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1796 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1800 // TODO: set SType according to the desired memory barrier behavior.
1802 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1804 DebugLoc dl = Op.getDebugLoc();
1805 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1806 DAG.getConstant(SType, MVT::i32));
1809 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1810 SelectionDAG& DAG) const {
1811 // FIXME: Need pseudo-fence for 'singlethread' fences
1812 // FIXME: Set SType for weaker fences where supported/appropriate.
1814 DebugLoc dl = Op.getDebugLoc();
1815 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1816 DAG.getConstant(SType, MVT::i32));
1819 //===----------------------------------------------------------------------===//
1820 // Calling Convention Implementation
1821 //===----------------------------------------------------------------------===//
1823 //===----------------------------------------------------------------------===//
1824 // TODO: Implement a generic logic using tblgen that can support this.
1825 // Mips O32 ABI rules:
1827 // i32 - Passed in A0, A1, A2, A3 and stack
1828 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1829 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1830 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1831 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1832 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1835 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1836 //===----------------------------------------------------------------------===//
1838 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1839 MVT LocVT, CCValAssign::LocInfo LocInfo,
1840 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1842 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1844 static const unsigned IntRegs[] = {
1845 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1847 static const unsigned F32Regs[] = {
1848 Mips::F12, Mips::F14
1850 static const unsigned F64Regs[] = {
1855 if (ArgFlags.isByVal()) {
1856 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1857 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1858 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1859 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1860 r < std::min(IntRegsSize, NextReg); ++r)
1861 State.AllocateReg(IntRegs[r]);
1865 // Promote i8 and i16
1866 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1868 if (ArgFlags.isSExt())
1869 LocInfo = CCValAssign::SExt;
1870 else if (ArgFlags.isZExt())
1871 LocInfo = CCValAssign::ZExt;
1873 LocInfo = CCValAssign::AExt;
1878 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1879 // is true: function is vararg, argument is 3rd or higher, there is previous
1880 // argument which is not f32 or f64.
1881 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1882 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1883 unsigned OrigAlign = ArgFlags.getOrigAlign();
1884 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1886 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1887 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1888 // If this is the first part of an i64 arg,
1889 // the allocated register must be either A0 or A2.
1890 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1891 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1893 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1894 // Allocate int register and shadow next int register. If first
1895 // available register is Mips::A1 or Mips::A3, shadow it too.
1896 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1897 if (Reg == Mips::A1 || Reg == Mips::A3)
1898 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1899 State.AllocateReg(IntRegs, IntRegsSize);
1901 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1902 // we are guaranteed to find an available float register
1903 if (ValVT == MVT::f32) {
1904 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1905 // Shadow int register
1906 State.AllocateReg(IntRegs, IntRegsSize);
1908 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1909 // Shadow int registers
1910 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1911 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1912 State.AllocateReg(IntRegs, IntRegsSize);
1913 State.AllocateReg(IntRegs, IntRegsSize);
1916 llvm_unreachable("Cannot handle this ValVT.");
1918 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1919 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1922 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1924 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1926 return false; // CC must always match
1929 static const unsigned Mips64IntRegs[8] =
1930 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1931 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1932 static const unsigned Mips64DPRegs[8] =
1933 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1934 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1936 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1937 CCValAssign::LocInfo LocInfo,
1938 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1939 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1940 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1941 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1943 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1945 // If byval is 16-byte aligned, the first arg register must be even.
1946 if ((Align == 16) && (FirstIdx % 2)) {
1947 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1951 // Mark the registers allocated.
1952 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1953 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1955 // Allocate space on caller's stack.
1956 unsigned Offset = State.AllocateStack(Size, Align);
1959 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1962 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1967 #include "MipsGenCallingConv.inc"
1970 AnalyzeMips64CallOperands(CCState &CCInfo,
1971 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1972 unsigned NumOps = Outs.size();
1973 for (unsigned i = 0; i != NumOps; ++i) {
1974 MVT ArgVT = Outs[i].VT;
1975 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1978 if (Outs[i].IsFixed)
1979 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1981 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1985 dbgs() << "Call operand #" << i << " has unhandled type "
1986 << EVT(ArgVT).getEVTString();
1988 llvm_unreachable(0);
1993 //===----------------------------------------------------------------------===//
1994 // Call Calling Convention Implementation
1995 //===----------------------------------------------------------------------===//
1997 static const unsigned O32IntRegsSize = 4;
1999 static const unsigned O32IntRegs[] = {
2000 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2003 // Return next O32 integer argument register.
2004 static unsigned getNextIntArgReg(unsigned Reg) {
2005 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2006 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2009 // Write ByVal Arg to arg registers and stack.
2011 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2012 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2013 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2014 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2015 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2016 MVT PtrType, bool isLittle) {
2017 unsigned LocMemOffset = VA.getLocMemOffset();
2018 unsigned Offset = 0;
2019 uint32_t RemainingSize = Flags.getByValSize();
2020 unsigned ByValAlign = Flags.getByValAlign();
2022 // Copy the first 4 words of byval arg to registers A0 - A3.
2023 // FIXME: Use a stricter alignment if it enables better optimization in passes
2025 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2026 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2027 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2028 DAG.getConstant(Offset, MVT::i32));
2029 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2030 MachinePointerInfo(), false, false, false,
2031 std::min(ByValAlign, (unsigned )4));
2032 MemOpChains.push_back(LoadVal.getValue(1));
2033 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2034 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2037 if (RemainingSize == 0)
2040 // If there still is a register available for argument passing, write the
2041 // remaining part of the structure to it using subword loads and shifts.
2042 if (LocMemOffset < 4 * 4) {
2043 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2044 "There must be one to three bytes remaining.");
2045 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2046 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2047 DAG.getConstant(Offset, MVT::i32));
2048 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2049 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2050 LoadPtr, MachinePointerInfo(),
2051 MVT::getIntegerVT(LoadSize * 8), false,
2053 MemOpChains.push_back(LoadVal.getValue(1));
2055 // If target is big endian, shift it to the most significant half-word or
2058 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2059 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2062 RemainingSize -= LoadSize;
2064 // Read second subword if necessary.
2065 if (RemainingSize != 0) {
2066 assert(RemainingSize == 1 && "There must be one byte remaining.");
2067 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2068 DAG.getConstant(Offset, MVT::i32));
2069 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2070 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2071 LoadPtr, MachinePointerInfo(),
2072 MVT::i8, false, false, Alignment);
2073 MemOpChains.push_back(Subword.getValue(1));
2074 // Insert the loaded byte to LoadVal.
2075 // FIXME: Use INS if supported by target.
2076 unsigned ShiftAmt = isLittle ? 16 : 8;
2077 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2078 DAG.getConstant(ShiftAmt, MVT::i32));
2079 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2082 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2083 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2087 // Create a fixed object on stack at offset LocMemOffset and copy
2088 // remaining part of byval arg to it using memcpy.
2089 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2090 DAG.getConstant(Offset, MVT::i32));
2091 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2092 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2093 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2094 DAG.getConstant(RemainingSize, MVT::i32),
2095 std::min(ByValAlign, (unsigned)4),
2096 /*isVolatile=*/false, /*AlwaysInline=*/false,
2097 MachinePointerInfo(0), MachinePointerInfo(0));
2100 // Copy Mips64 byVal arg to registers and stack.
2102 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2103 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2104 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2105 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2106 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2107 EVT PtrTy, bool isLittle) {
2108 unsigned ByValSize = Flags.getByValSize();
2109 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2110 bool IsRegLoc = VA.isRegLoc();
2111 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2112 unsigned LocMemOffset = 0;
2113 unsigned MemCpySize = ByValSize;
2116 LocMemOffset = VA.getLocMemOffset();
2118 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2120 const unsigned *RegEnd = Mips64IntRegs + 8;
2122 // Copy double words to registers.
2123 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2124 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2125 DAG.getConstant(Offset, PtrTy));
2126 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2127 MachinePointerInfo(), false, false, false,
2129 MemOpChains.push_back(LoadVal.getValue(1));
2130 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2133 // Return if the struct has been fully copied.
2134 if (!(MemCpySize = ByValSize - Offset))
2137 // If there is an argument register available, copy the remainder of the
2138 // byval argument with sub-doubleword loads and shifts.
2139 if (Reg != RegEnd) {
2140 assert((ByValSize < Offset + 8) &&
2141 "Size of the remainder should be smaller than 8-byte.");
2143 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2144 unsigned RemSize = ByValSize - Offset;
2146 if (RemSize < LoadSize)
2149 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2150 DAG.getConstant(Offset, PtrTy));
2152 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2153 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2154 false, false, Alignment);
2155 MemOpChains.push_back(LoadVal.getValue(1));
2157 // Offset in number of bits from double word boundary.
2158 unsigned OffsetDW = (Offset % 8) * 8;
2159 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2160 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2161 DAG.getConstant(Shamt, MVT::i32));
2163 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2166 Alignment = std::min(Alignment, LoadSize);
2169 RegsToPass.push_back(std::make_pair(*Reg, Val));
2174 assert(MemCpySize && "MemCpySize must not be zero.");
2176 // Create a fixed object on stack at offset LocMemOffset and copy
2177 // remainder of byval arg to it with memcpy.
2178 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2179 DAG.getConstant(Offset, PtrTy));
2180 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2181 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2182 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2183 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2184 /*isVolatile=*/false, /*AlwaysInline=*/false,
2185 MachinePointerInfo(0), MachinePointerInfo(0));
2188 /// LowerCall - functions arguments are copied from virtual regs to
2189 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2190 /// TODO: isTailCall.
2192 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2193 CallingConv::ID CallConv, bool isVarArg,
2194 bool doesNotRet, bool &isTailCall,
2195 const SmallVectorImpl<ISD::OutputArg> &Outs,
2196 const SmallVectorImpl<SDValue> &OutVals,
2197 const SmallVectorImpl<ISD::InputArg> &Ins,
2198 DebugLoc dl, SelectionDAG &DAG,
2199 SmallVectorImpl<SDValue> &InVals) const {
2200 // MIPs target does not yet support tail call optimization.
2203 MachineFunction &MF = DAG.getMachineFunction();
2204 MachineFrameInfo *MFI = MF.getFrameInfo();
2205 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2206 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2207 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2209 // Analyze operands of the call, assigning locations to each operand.
2210 SmallVector<CCValAssign, 16> ArgLocs;
2211 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2212 getTargetMachine(), ArgLocs, *DAG.getContext());
2215 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2217 AnalyzeMips64CallOperands(CCInfo, Outs);
2219 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2221 // Get a count of how many bytes are to be pushed on the stack.
2222 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2224 // Chain is the output chain of the last Load/Store or CopyToReg node.
2225 // ByValChain is the output chain of the last Memcpy node created for copying
2226 // byval arguments to the stack.
2227 SDValue Chain, CallSeqStart, ByValChain;
2228 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2229 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2230 ByValChain = InChain;
2232 // If this is the first call, create a stack frame object that points to
2233 // a location to which .cprestore saves $gp.
2234 if (IsO32 && IsPIC && MipsFI->globalBaseRegFixed() && !MipsFI->getGPFI())
2235 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2237 // Get the frame index of the stack frame object that points to the location
2238 // of dynamically allocated area on the stack.
2239 int DynAllocFI = MipsFI->getDynAllocFI();
2241 // Update size of the maximum argument space.
2242 // For O32, a minimum of four words (16 bytes) of argument space is
2245 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2247 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2249 if (MaxCallFrameSize < NextStackOffset) {
2250 MipsFI->setMaxCallFrameSize(NextStackOffset);
2252 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2253 // allocated stack space. These offsets must be aligned to a boundary
2254 // determined by the stack alignment of the ABI.
2255 unsigned StackAlignment = TFL->getStackAlignment();
2256 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2257 StackAlignment * StackAlignment;
2259 if (MipsFI->needGPSaveRestore())
2260 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2262 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2265 // With EABI is it possible to have 16 args on registers.
2266 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2267 SmallVector<SDValue, 8> MemOpChains;
2269 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2271 // Walk the register/memloc assignments, inserting copies/loads.
2272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2273 SDValue Arg = OutVals[i];
2274 CCValAssign &VA = ArgLocs[i];
2275 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2276 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2279 if (Flags.isByVal()) {
2280 assert(Flags.getByValSize() &&
2281 "ByVal args of size 0 should have been ignored by front-end.");
2283 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2284 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2285 Subtarget->isLittle());
2287 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2288 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2289 Subtarget->isLittle());
2293 // Promote the value if needed.
2294 switch (VA.getLocInfo()) {
2295 default: llvm_unreachable("Unknown loc info!");
2296 case CCValAssign::Full:
2297 if (VA.isRegLoc()) {
2298 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2299 (ValVT == MVT::f64 && LocVT == MVT::i64))
2300 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2301 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2302 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2303 Arg, DAG.getConstant(0, MVT::i32));
2304 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2305 Arg, DAG.getConstant(1, MVT::i32));
2306 if (!Subtarget->isLittle())
2308 unsigned LocRegLo = VA.getLocReg();
2309 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2310 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2311 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2316 case CCValAssign::SExt:
2317 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2319 case CCValAssign::ZExt:
2320 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2322 case CCValAssign::AExt:
2323 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2327 // Arguments that can be passed on register must be kept at
2328 // RegsToPass vector
2329 if (VA.isRegLoc()) {
2330 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2334 // Register can't get to this point...
2335 assert(VA.isMemLoc());
2337 // Create the frame index object for this incoming parameter
2338 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2339 VA.getLocMemOffset(), true);
2340 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2342 // emit ISD::STORE whichs stores the
2343 // parameter value to a stack Location
2344 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2345 MachinePointerInfo(), false, false, 0));
2348 // Extend range of indices of frame objects for outgoing arguments that were
2349 // created during this function call. Skip this step if no such objects were
2352 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2354 // If a memcpy has been created to copy a byval arg to a stack, replace the
2355 // chain input of CallSeqStart with ByValChain.
2356 if (InChain != ByValChain)
2357 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2358 NextStackOffsetVal);
2360 // Transform all store nodes into one single node because all store
2361 // nodes are independent of each other.
2362 if (!MemOpChains.empty())
2363 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2364 &MemOpChains[0], MemOpChains.size());
2366 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2367 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2368 // node so that legalize doesn't hack it.
2369 unsigned char OpFlag;
2370 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2371 bool GlobalOrExternal = false;
2374 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2375 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2376 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2377 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2378 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2380 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2383 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2384 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2385 getPointerTy(), 0, OpFlag);
2388 GlobalOrExternal = true;
2390 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2391 if (IsN64 || (!IsO32 && IsPIC))
2392 OpFlag = MipsII::MO_GOT_DISP;
2393 else if (!IsPIC) // !N64 && static
2394 OpFlag = MipsII::MO_NO_FLAG;
2396 OpFlag = MipsII::MO_GOT_CALL;
2397 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2399 GlobalOrExternal = true;
2404 // Create nodes that load address of callee and copy it to T9
2406 if (GlobalOrExternal) {
2407 // Load callee address
2408 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2409 GetGlobalReg(DAG, getPointerTy()), Callee);
2410 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2411 Callee, MachinePointerInfo::getGOT(),
2412 false, false, false, 0);
2414 // Use GOT+LO if callee has internal linkage.
2415 if (CalleeLo.getNode()) {
2416 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2417 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2423 // T9 should contain the address of the callee function if
2424 // -reloction-model=pic or it is an indirect call.
2425 if (IsPICCall || !GlobalOrExternal) {
2427 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2428 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2429 InFlag = Chain.getValue(1);
2430 Callee = DAG.getRegister(T9Reg, getPointerTy());
2433 // Build a sequence of copy-to-reg nodes chained together with token
2434 // chain and flag operands which copy the outgoing args into registers.
2435 // The InFlag in necessary since all emitted instructions must be
2437 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2438 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2439 RegsToPass[i].second, InFlag);
2440 InFlag = Chain.getValue(1);
2443 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2444 // = Chain, Callee, Reg#1, Reg#2, ...
2446 // Returns a chain & a flag for retval copy to use.
2447 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2448 SmallVector<SDValue, 8> Ops;
2449 Ops.push_back(Chain);
2450 Ops.push_back(Callee);
2452 // Add argument registers to the end of the list so that they are
2453 // known live into the call.
2454 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2455 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2456 RegsToPass[i].second.getValueType()));
2458 // Add a register mask operand representing the call-preserved registers.
2459 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2460 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2461 assert(Mask && "Missing call preserved mask for calling convention");
2462 Ops.push_back(DAG.getRegisterMask(Mask));
2464 if (InFlag.getNode())
2465 Ops.push_back(InFlag);
2467 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2468 InFlag = Chain.getValue(1);
2470 // Create the CALLSEQ_END node.
2471 Chain = DAG.getCALLSEQ_END(Chain,
2472 DAG.getIntPtrConstant(NextStackOffset, true),
2473 DAG.getIntPtrConstant(0, true), InFlag);
2474 InFlag = Chain.getValue(1);
2476 // Handle result values, copying them out of physregs into vregs that we
2478 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2479 Ins, dl, DAG, InVals);
2482 /// LowerCallResult - Lower the result values of a call into the
2483 /// appropriate copies out of appropriate physical registers.
2485 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2486 CallingConv::ID CallConv, bool isVarArg,
2487 const SmallVectorImpl<ISD::InputArg> &Ins,
2488 DebugLoc dl, SelectionDAG &DAG,
2489 SmallVectorImpl<SDValue> &InVals) const {
2490 // Assign locations to each value returned by this call.
2491 SmallVector<CCValAssign, 16> RVLocs;
2492 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2493 getTargetMachine(), RVLocs, *DAG.getContext());
2495 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2497 // Copy all of the result registers out of their specified physreg.
2498 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2499 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2500 RVLocs[i].getValVT(), InFlag).getValue(1);
2501 InFlag = Chain.getValue(2);
2502 InVals.push_back(Chain.getValue(0));
2508 //===----------------------------------------------------------------------===//
2509 // Formal Arguments Calling Convention Implementation
2510 //===----------------------------------------------------------------------===//
2511 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2512 std::vector<SDValue>& OutChains,
2513 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2514 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2515 unsigned LocMem = VA.getLocMemOffset();
2516 unsigned FirstWord = LocMem / 4;
2518 // copy register A0 - A3 to frame object
2519 for (unsigned i = 0; i < NumWords; ++i) {
2520 unsigned CurWord = FirstWord + i;
2521 if (CurWord >= O32IntRegsSize)
2524 unsigned SrcReg = O32IntRegs[CurWord];
2525 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2526 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2527 DAG.getConstant(i * 4, MVT::i32));
2528 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2529 StorePtr, MachinePointerInfo(), false,
2531 OutChains.push_back(Store);
2535 // Create frame object on stack and copy registers used for byval passing to it.
2537 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2538 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2539 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2540 MachineFrameInfo *MFI, bool IsRegLoc,
2541 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2543 const unsigned *Reg = Mips64IntRegs + 8;
2544 int FOOffset; // Frame object offset from virtual frame pointer.
2547 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2548 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2551 FOOffset = VA.getLocMemOffset();
2553 // Create frame object.
2554 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2555 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2556 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2557 InVals.push_back(FIN);
2559 // Copy arg registers.
2560 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2562 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2563 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2564 DAG.getConstant(I * 8, PtrTy));
2565 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2566 StorePtr, MachinePointerInfo(), false,
2568 OutChains.push_back(Store);
2574 /// LowerFormalArguments - transform physical registers into virtual registers
2575 /// and generate load operations for arguments places on the stack.
2577 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2578 CallingConv::ID CallConv,
2580 const SmallVectorImpl<ISD::InputArg> &Ins,
2581 DebugLoc dl, SelectionDAG &DAG,
2582 SmallVectorImpl<SDValue> &InVals)
2584 MachineFunction &MF = DAG.getMachineFunction();
2585 MachineFrameInfo *MFI = MF.getFrameInfo();
2586 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2588 MipsFI->setVarArgsFrameIndex(0);
2590 // Used with vargs to acumulate store chains.
2591 std::vector<SDValue> OutChains;
2593 // Assign locations to all of the incoming arguments.
2594 SmallVector<CCValAssign, 16> ArgLocs;
2595 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2596 getTargetMachine(), ArgLocs, *DAG.getContext());
2599 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2601 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2603 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2605 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2606 CCValAssign &VA = ArgLocs[i];
2607 EVT ValVT = VA.getValVT();
2608 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2609 bool IsRegLoc = VA.isRegLoc();
2611 if (Flags.isByVal()) {
2612 assert(Flags.getByValSize() &&
2613 "ByVal args of size 0 should have been ignored by front-end.");
2615 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2616 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2618 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2619 InVals.push_back(FIN);
2620 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2622 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2623 MFI, IsRegLoc, InVals, MipsFI,
2628 // Arguments stored on registers
2630 EVT RegVT = VA.getLocVT();
2631 unsigned ArgReg = VA.getLocReg();
2632 const TargetRegisterClass *RC;
2634 if (RegVT == MVT::i32)
2635 RC = Mips::CPURegsRegisterClass;
2636 else if (RegVT == MVT::i64)
2637 RC = Mips::CPU64RegsRegisterClass;
2638 else if (RegVT == MVT::f32)
2639 RC = Mips::FGR32RegisterClass;
2640 else if (RegVT == MVT::f64)
2641 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2643 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2645 // Transform the arguments stored on
2646 // physical registers into virtual ones
2647 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2648 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2650 // If this is an 8 or 16-bit value, it has been passed promoted
2651 // to 32 bits. Insert an assert[sz]ext to capture this, then
2652 // truncate to the right size.
2653 if (VA.getLocInfo() != CCValAssign::Full) {
2654 unsigned Opcode = 0;
2655 if (VA.getLocInfo() == CCValAssign::SExt)
2656 Opcode = ISD::AssertSext;
2657 else if (VA.getLocInfo() == CCValAssign::ZExt)
2658 Opcode = ISD::AssertZext;
2660 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2661 DAG.getValueType(ValVT));
2662 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2665 // Handle floating point arguments passed in integer registers.
2666 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2667 (RegVT == MVT::i64 && ValVT == MVT::f64))
2668 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2669 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2670 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2671 getNextIntArgReg(ArgReg), RC);
2672 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2673 if (!Subtarget->isLittle())
2674 std::swap(ArgValue, ArgValue2);
2675 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2676 ArgValue, ArgValue2);
2679 InVals.push_back(ArgValue);
2680 } else { // VA.isRegLoc()
2683 assert(VA.isMemLoc());
2685 // The stack pointer offset is relative to the caller stack frame.
2686 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2687 VA.getLocMemOffset(), true);
2689 // Create load nodes to retrieve arguments from the stack
2690 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2691 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2692 MachinePointerInfo::getFixedStack(LastFI),
2693 false, false, false, 0));
2697 // The mips ABIs for returning structs by value requires that we copy
2698 // the sret argument into $v0 for the return. Save the argument into
2699 // a virtual register so that we can access it from the return points.
2700 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2701 unsigned Reg = MipsFI->getSRetReturnReg();
2703 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2704 MipsFI->setSRetReturnReg(Reg);
2706 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2711 unsigned NumOfRegs = IsO32 ? 4 : 8;
2712 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2713 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2714 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2715 const TargetRegisterClass *RC
2716 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2717 unsigned RegSize = RC->getSize();
2718 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2720 // Offset of the first variable argument from stack pointer.
2721 int FirstVaArgOffset;
2723 if (IsO32 || (Idx == NumOfRegs)) {
2725 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2727 FirstVaArgOffset = RegSlotOffset;
2729 // Record the frame index of the first variable argument
2730 // which is a value necessary to VASTART.
2731 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2732 MipsFI->setVarArgsFrameIndex(LastFI);
2734 // Copy the integer registers that have not been used for argument passing
2735 // to the argument register save area. For O32, the save area is allocated
2736 // in the caller's stack frame, while for N32/64, it is allocated in the
2737 // callee's stack frame.
2738 for (int StackOffset = RegSlotOffset;
2739 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2740 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2741 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2742 MVT::getIntegerVT(RegSize * 8));
2743 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2744 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2745 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2746 MachinePointerInfo(), false, false, 0));
2750 MipsFI->setLastInArgFI(LastFI);
2752 // All stores are grouped in one node to allow the matching between
2753 // the size of Ins and InVals. This only happens when on varg functions
2754 if (!OutChains.empty()) {
2755 OutChains.push_back(Chain);
2756 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2757 &OutChains[0], OutChains.size());
2763 //===----------------------------------------------------------------------===//
2764 // Return Value Calling Convention Implementation
2765 //===----------------------------------------------------------------------===//
2768 MipsTargetLowering::LowerReturn(SDValue Chain,
2769 CallingConv::ID CallConv, bool isVarArg,
2770 const SmallVectorImpl<ISD::OutputArg> &Outs,
2771 const SmallVectorImpl<SDValue> &OutVals,
2772 DebugLoc dl, SelectionDAG &DAG) const {
2774 // CCValAssign - represent the assignment of
2775 // the return value to a location
2776 SmallVector<CCValAssign, 16> RVLocs;
2778 // CCState - Info about the registers and stack slot.
2779 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2780 getTargetMachine(), RVLocs, *DAG.getContext());
2782 // Analize return values.
2783 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2785 // If this is the first return lowered for this function, add
2786 // the regs to the liveout set for the function.
2787 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2788 for (unsigned i = 0; i != RVLocs.size(); ++i)
2789 if (RVLocs[i].isRegLoc())
2790 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2795 // Copy the result values into the output registers.
2796 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2797 CCValAssign &VA = RVLocs[i];
2798 assert(VA.isRegLoc() && "Can only return in registers!");
2800 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2802 // guarantee that all emitted copies are
2803 // stuck together, avoiding something bad
2804 Flag = Chain.getValue(1);
2807 // The mips ABIs for returning structs by value requires that we copy
2808 // the sret argument into $v0 for the return. We saved the argument into
2809 // a virtual register in the entry block, so now we copy the value out
2811 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2812 MachineFunction &MF = DAG.getMachineFunction();
2813 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2814 unsigned Reg = MipsFI->getSRetReturnReg();
2817 llvm_unreachable("sret virtual register not created in the entry block");
2818 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2820 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2821 Flag = Chain.getValue(1);
2824 // Return on Mips is always a "jr $ra"
2826 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2827 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2829 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2830 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2833 //===----------------------------------------------------------------------===//
2834 // Mips Inline Assembly Support
2835 //===----------------------------------------------------------------------===//
2837 /// getConstraintType - Given a constraint letter, return the type of
2838 /// constraint it is for this target.
2839 MipsTargetLowering::ConstraintType MipsTargetLowering::
2840 getConstraintType(const std::string &Constraint) const
2842 // Mips specific constrainy
2843 // GCC config/mips/constraints.md
2845 // 'd' : An address register. Equivalent to r
2846 // unless generating MIPS16 code.
2847 // 'y' : Equivalent to r; retained for
2848 // backwards compatibility.
2849 // 'f' : Floating Point registers.
2850 if (Constraint.size() == 1) {
2851 switch (Constraint[0]) {
2856 return C_RegisterClass;
2859 return TargetLowering::getConstraintType(Constraint);
2862 /// Examine constraint type and operand type and determine a weight value.
2863 /// This object must already have been set up with the operand type
2864 /// and the current alternative constraint selected.
2865 TargetLowering::ConstraintWeight
2866 MipsTargetLowering::getSingleConstraintMatchWeight(
2867 AsmOperandInfo &info, const char *constraint) const {
2868 ConstraintWeight weight = CW_Invalid;
2869 Value *CallOperandVal = info.CallOperandVal;
2870 // If we don't have a value, we can't do a match,
2871 // but allow it at the lowest weight.
2872 if (CallOperandVal == NULL)
2874 Type *type = CallOperandVal->getType();
2875 // Look at the constraint type.
2876 switch (*constraint) {
2878 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2882 if (type->isIntegerTy())
2883 weight = CW_Register;
2886 if (type->isFloatTy())
2887 weight = CW_Register;
2893 /// Given a register class constraint, like 'r', if this corresponds directly
2894 /// to an LLVM register class, return a register of 0 and the register class
2896 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2897 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2899 if (Constraint.size() == 1) {
2900 switch (Constraint[0]) {
2901 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2902 case 'y': // Same as 'r'. Exists for compatibility.
2905 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2906 assert(VT == MVT::i64 && "Unexpected type.");
2907 return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
2910 return std::make_pair(0U, Mips::FGR32RegisterClass);
2911 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2912 if (Subtarget->isFP64bit())
2913 return std::make_pair(0U, Mips::FGR64RegisterClass);
2915 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2919 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2923 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2924 // The Mips target isn't yet aware of offsets.
2928 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2929 if (VT != MVT::f32 && VT != MVT::f64)
2931 if (Imm.isNegZero())
2933 return Imm.isZero();
2936 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2938 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2940 return TargetLowering::getJumpTableEncoding();