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 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
53 case MipsISD::JmpLink: return "MipsISD::JmpLink";
54 case MipsISD::Hi: return "MipsISD::Hi";
55 case MipsISD::Lo: return "MipsISD::Lo";
56 case MipsISD::GPRel: return "MipsISD::GPRel";
57 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
58 case MipsISD::Ret: return "MipsISD::Ret";
59 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
60 case MipsISD::FPCmp: return "MipsISD::FPCmp";
61 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
62 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
63 case MipsISD::FPRound: return "MipsISD::FPRound";
64 case MipsISD::MAdd: return "MipsISD::MAdd";
65 case MipsISD::MAddu: return "MipsISD::MAddu";
66 case MipsISD::MSub: return "MipsISD::MSub";
67 case MipsISD::MSubu: return "MipsISD::MSubu";
68 case MipsISD::DivRem: return "MipsISD::DivRem";
69 case MipsISD::DivRemU: return "MipsISD::DivRemU";
70 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
71 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
72 case MipsISD::Wrapper: return "MipsISD::Wrapper";
73 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
74 case MipsISD::Sync: return "MipsISD::Sync";
75 case MipsISD::Ext: return "MipsISD::Ext";
76 case MipsISD::Ins: return "MipsISD::Ins";
82 MipsTargetLowering(MipsTargetMachine &TM)
83 : TargetLowering(TM, new MipsTargetObjectFile()),
84 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
85 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
86 IsO32(Subtarget->isABI_O32()) {
88 // Mips does not have i1 type, so use i32 for
89 // setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // Set up the register classes
94 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
97 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
99 if (!TM.Options.UseSoftFloat) {
100 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
102 // When dealing with single precision only, use libcalls
103 if (!Subtarget->isSingleFloat()) {
105 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
107 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
111 // Load extented operations for i1 types must be promoted
112 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
113 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
114 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
116 // MIPS doesn't have extending float->double load/store
117 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
118 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
120 // Used by legalize types to correctly generate the setcc result.
121 // Without this, every float setcc comes with a AND/OR with the result,
122 // we don't want this, since the fpcmp result goes to a flag register,
123 // which is used implicitly by brcond and select operations.
124 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
126 // Mips Custom Operations
127 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
129 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
130 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
131 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
132 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
133 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
134 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
135 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
136 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
137 setOperationAction(ISD::SELECT, MVT::f32, Custom);
138 setOperationAction(ISD::SELECT, MVT::f64, Custom);
139 setOperationAction(ISD::SELECT, MVT::i32, Custom);
140 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
141 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
142 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
143 setOperationAction(ISD::VASTART, MVT::Other, Custom);
145 setOperationAction(ISD::SDIV, MVT::i32, Expand);
146 setOperationAction(ISD::SREM, MVT::i32, Expand);
147 setOperationAction(ISD::UDIV, MVT::i32, Expand);
148 setOperationAction(ISD::UREM, MVT::i32, Expand);
149 setOperationAction(ISD::SDIV, MVT::i64, Expand);
150 setOperationAction(ISD::SREM, MVT::i64, Expand);
151 setOperationAction(ISD::UDIV, MVT::i64, Expand);
152 setOperationAction(ISD::UREM, MVT::i64, Expand);
154 // Operations not directly supported by Mips.
155 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
156 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
157 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
158 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
159 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
160 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
161 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
162 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
163 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
164 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
165 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
166 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
167 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
168 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
169 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
170 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
171 setOperationAction(ISD::ROTL, MVT::i32, Expand);
172 setOperationAction(ISD::ROTL, MVT::i64, Expand);
174 if (!Subtarget->hasMips32r2())
175 setOperationAction(ISD::ROTR, MVT::i32, Expand);
177 if (!Subtarget->hasMips64r2())
178 setOperationAction(ISD::ROTR, MVT::i64, Expand);
180 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
181 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
182 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
183 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
184 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
185 setOperationAction(ISD::FSIN, MVT::f32, Expand);
186 setOperationAction(ISD::FSIN, MVT::f64, Expand);
187 setOperationAction(ISD::FCOS, MVT::f32, Expand);
188 setOperationAction(ISD::FCOS, MVT::f64, Expand);
189 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
190 setOperationAction(ISD::FPOW, MVT::f32, Expand);
191 setOperationAction(ISD::FPOW, MVT::f64, Expand);
192 setOperationAction(ISD::FLOG, MVT::f32, Expand);
193 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
194 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
195 setOperationAction(ISD::FEXP, MVT::f32, Expand);
196 setOperationAction(ISD::FMA, MVT::f32, Expand);
197 setOperationAction(ISD::FMA, MVT::f64, Expand);
199 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
200 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
201 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
202 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
204 setOperationAction(ISD::VAARG, MVT::Other, Expand);
205 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
206 setOperationAction(ISD::VAEND, MVT::Other, Expand);
208 // Use the default for now
209 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
210 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
212 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
213 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
215 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
216 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
217 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
218 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
220 setInsertFencesForAtomic(true);
222 if (Subtarget->isSingleFloat())
223 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
225 if (!Subtarget->hasSEInReg()) {
226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
227 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
230 if (!Subtarget->hasBitCount()) {
231 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
232 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
235 if (!Subtarget->hasSwap()) {
236 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
237 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
240 setTargetDAGCombine(ISD::ADDE);
241 setTargetDAGCombine(ISD::SUBE);
242 setTargetDAGCombine(ISD::SDIVREM);
243 setTargetDAGCombine(ISD::UDIVREM);
244 setTargetDAGCombine(ISD::SETCC);
245 setTargetDAGCombine(ISD::AND);
246 setTargetDAGCombine(ISD::OR);
248 setMinFunctionAlignment(2);
250 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
251 computeRegisterProperties();
253 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
254 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
257 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
258 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
259 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
262 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
267 // Transforms a subgraph in CurDAG if the following pattern is found:
268 // (addc multLo, Lo0), (adde multHi, Hi0),
270 // multHi/Lo: product of multiplication
271 // Lo0: initial value of Lo register
272 // Hi0: initial value of Hi register
273 // Return true if pattern matching was successful.
274 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
275 // ADDENode's second operand must be a flag output of an ADDC node in order
276 // for the matching to be successful.
277 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
279 if (ADDCNode->getOpcode() != ISD::ADDC)
282 SDValue MultHi = ADDENode->getOperand(0);
283 SDValue MultLo = ADDCNode->getOperand(0);
284 SDNode* MultNode = MultHi.getNode();
285 unsigned MultOpc = MultHi.getOpcode();
287 // MultHi and MultLo must be generated by the same node,
288 if (MultLo.getNode() != MultNode)
291 // and it must be a multiplication.
292 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
295 // MultLo amd MultHi must be the first and second output of MultNode
297 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
300 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
301 // of the values of MultNode, in which case MultNode will be removed in later
303 // If there exist users other than ADDENode or ADDCNode, this function returns
304 // here, which will result in MultNode being mapped to a single MULT
305 // instruction node rather than a pair of MULT and MADD instructions being
307 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
310 SDValue Chain = CurDAG->getEntryNode();
311 DebugLoc dl = ADDENode->getDebugLoc();
313 // create MipsMAdd(u) node
314 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
316 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
317 MultNode->getOperand(0),// Factor 0
318 MultNode->getOperand(1),// Factor 1
319 ADDCNode->getOperand(1),// Lo0
320 ADDENode->getOperand(1));// Hi0
322 // create CopyFromReg nodes
323 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
325 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
327 CopyFromLo.getValue(2));
329 // replace uses of adde and addc here
330 if (!SDValue(ADDCNode, 0).use_empty())
331 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
333 if (!SDValue(ADDENode, 0).use_empty())
334 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
340 // Transforms a subgraph in CurDAG if the following pattern is found:
341 // (addc Lo0, multLo), (sube Hi0, multHi),
343 // multHi/Lo: product of multiplication
344 // Lo0: initial value of Lo register
345 // Hi0: initial value of Hi register
346 // Return true if pattern matching was successful.
347 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
348 // SUBENode's second operand must be a flag output of an SUBC node in order
349 // for the matching to be successful.
350 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
352 if (SUBCNode->getOpcode() != ISD::SUBC)
355 SDValue MultHi = SUBENode->getOperand(1);
356 SDValue MultLo = SUBCNode->getOperand(1);
357 SDNode* MultNode = MultHi.getNode();
358 unsigned MultOpc = MultHi.getOpcode();
360 // MultHi and MultLo must be generated by the same node,
361 if (MultLo.getNode() != MultNode)
364 // and it must be a multiplication.
365 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
368 // MultLo amd MultHi must be the first and second output of MultNode
370 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
373 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
374 // of the values of MultNode, in which case MultNode will be removed in later
376 // If there exist users other than SUBENode or SUBCNode, this function returns
377 // here, which will result in MultNode being mapped to a single MULT
378 // instruction node rather than a pair of MULT and MSUB instructions being
380 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
383 SDValue Chain = CurDAG->getEntryNode();
384 DebugLoc dl = SUBENode->getDebugLoc();
386 // create MipsSub(u) node
387 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
389 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
390 MultNode->getOperand(0),// Factor 0
391 MultNode->getOperand(1),// Factor 1
392 SUBCNode->getOperand(0),// Lo0
393 SUBENode->getOperand(0));// Hi0
395 // create CopyFromReg nodes
396 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
398 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
400 CopyFromLo.getValue(2));
402 // replace uses of sube and subc here
403 if (!SDValue(SUBCNode, 0).use_empty())
404 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
406 if (!SDValue(SUBENode, 0).use_empty())
407 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
412 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
413 TargetLowering::DAGCombinerInfo &DCI,
414 const MipsSubtarget* Subtarget) {
415 if (DCI.isBeforeLegalize())
418 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
420 return SDValue(N, 0);
425 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
426 TargetLowering::DAGCombinerInfo &DCI,
427 const MipsSubtarget* Subtarget) {
428 if (DCI.isBeforeLegalize())
431 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
433 return SDValue(N, 0);
438 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
439 TargetLowering::DAGCombinerInfo &DCI,
440 const MipsSubtarget* Subtarget) {
441 if (DCI.isBeforeLegalizeOps())
444 EVT Ty = N->getValueType(0);
445 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
446 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
447 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
449 DebugLoc dl = N->getDebugLoc();
451 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
452 N->getOperand(0), N->getOperand(1));
453 SDValue InChain = DAG.getEntryNode();
454 SDValue InGlue = DivRem;
457 if (N->hasAnyUseOfValue(0)) {
458 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
460 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
461 InChain = CopyFromLo.getValue(1);
462 InGlue = CopyFromLo.getValue(2);
466 if (N->hasAnyUseOfValue(1)) {
467 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
469 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
475 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
477 default: llvm_unreachable("Unknown fp condition code!");
479 case ISD::SETOEQ: return Mips::FCOND_OEQ;
480 case ISD::SETUNE: return Mips::FCOND_UNE;
482 case ISD::SETOLT: return Mips::FCOND_OLT;
484 case ISD::SETOGT: return Mips::FCOND_OGT;
486 case ISD::SETOLE: return Mips::FCOND_OLE;
488 case ISD::SETOGE: return Mips::FCOND_OGE;
489 case ISD::SETULT: return Mips::FCOND_ULT;
490 case ISD::SETULE: return Mips::FCOND_ULE;
491 case ISD::SETUGT: return Mips::FCOND_UGT;
492 case ISD::SETUGE: return Mips::FCOND_UGE;
493 case ISD::SETUO: return Mips::FCOND_UN;
494 case ISD::SETO: return Mips::FCOND_OR;
496 case ISD::SETONE: return Mips::FCOND_ONE;
497 case ISD::SETUEQ: return Mips::FCOND_UEQ;
502 // Returns true if condition code has to be inverted.
503 static bool InvertFPCondCode(Mips::CondCode CC) {
504 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
507 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
508 "Illegal Condition Code");
513 // Creates and returns an FPCmp node from a setcc node.
514 // Returns Op if setcc is not a floating point comparison.
515 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
516 // must be a SETCC node
517 if (Op.getOpcode() != ISD::SETCC)
520 SDValue LHS = Op.getOperand(0);
522 if (!LHS.getValueType().isFloatingPoint())
525 SDValue RHS = Op.getOperand(1);
526 DebugLoc dl = Op.getDebugLoc();
528 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
529 // node if necessary.
530 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
532 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
533 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
536 // Creates and returns a CMovFPT/F node.
537 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
538 SDValue False, DebugLoc DL) {
539 bool invert = InvertFPCondCode((Mips::CondCode)
540 cast<ConstantSDNode>(Cond.getOperand(2))
543 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
544 True.getValueType(), True, False, Cond);
547 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
548 TargetLowering::DAGCombinerInfo &DCI,
549 const MipsSubtarget* Subtarget) {
550 if (DCI.isBeforeLegalizeOps())
553 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
555 if (Cond.getOpcode() != MipsISD::FPCmp)
558 SDValue True = DAG.getConstant(1, MVT::i32);
559 SDValue False = DAG.getConstant(0, MVT::i32);
561 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
564 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
565 TargetLowering::DAGCombinerInfo &DCI,
566 const MipsSubtarget* Subtarget) {
567 // Pattern match EXT.
568 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
569 // => ext $dst, $src, size, pos
570 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
573 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
574 unsigned ShiftRightOpc = ShiftRight.getOpcode();
576 // Op's first operand must be a shift right.
577 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
580 // The second operand of the shift must be an immediate.
582 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
585 uint64_t Pos = CN->getZExtValue();
586 uint64_t SMPos, SMSize;
588 // Op's second operand must be a shifted mask.
589 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
590 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
593 // Return if the shifted mask does not start at bit 0 or the sum of its size
594 // and Pos exceeds the word's size.
595 EVT ValTy = N->getValueType(0);
596 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
599 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
600 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
601 DAG.getConstant(SMSize, MVT::i32));
604 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
605 TargetLowering::DAGCombinerInfo &DCI,
606 const MipsSubtarget* Subtarget) {
607 // Pattern match INS.
608 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
609 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
610 // => ins $dst, $src, size, pos, $src1
611 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
614 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
615 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
618 // See if Op's first operand matches (and $src1 , mask0).
619 if (And0.getOpcode() != ISD::AND)
622 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
623 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
626 // See if Op's second operand matches (and (shl $src, pos), mask1).
627 if (And1.getOpcode() != ISD::AND)
630 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
631 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
634 // The shift masks must have the same position and size.
635 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
638 SDValue Shl = And1.getOperand(0);
639 if (Shl.getOpcode() != ISD::SHL)
642 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
645 unsigned Shamt = CN->getZExtValue();
647 // Return if the shift amount and the first bit position of mask are not the
649 EVT ValTy = N->getValueType(0);
650 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
653 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
654 DAG.getConstant(SMPos0, MVT::i32),
655 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
658 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
660 SelectionDAG &DAG = DCI.DAG;
661 unsigned opc = N->getOpcode();
666 return PerformADDECombine(N, DAG, DCI, Subtarget);
668 return PerformSUBECombine(N, DAG, DCI, Subtarget);
671 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
673 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
675 return PerformANDCombine(N, DAG, DCI, Subtarget);
677 return PerformORCombine(N, DAG, DCI, Subtarget);
683 SDValue MipsTargetLowering::
684 LowerOperation(SDValue Op, SelectionDAG &DAG) const
686 switch (Op.getOpcode())
688 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
689 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
690 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
691 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
692 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
693 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
694 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
695 case ISD::SELECT: return LowerSELECT(Op, DAG);
696 case ISD::VASTART: return LowerVASTART(Op, DAG);
697 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
698 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
699 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
700 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
705 //===----------------------------------------------------------------------===//
706 // Lower helper functions
707 //===----------------------------------------------------------------------===//
709 // AddLiveIn - This helper function adds the specified physical register to the
710 // MachineFunction as a live in value. It also creates a corresponding
711 // virtual register for it.
713 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
715 assert(RC->contains(PReg) && "Not the correct regclass!");
716 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
717 MF.getRegInfo().addLiveIn(PReg, VReg);
721 // Get fp branch code (not opcode) from condition code.
722 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
723 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
724 return Mips::BRANCH_T;
726 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
727 "Invalid CondCode.");
729 return Mips::BRANCH_F;
733 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
735 const MipsSubtarget* Subtarget,
736 const TargetInstrInfo *TII,
737 bool isFPCmp, unsigned Opc) {
738 // There is no need to expand CMov instructions if target has
739 // conditional moves.
740 if (Subtarget->hasCondMov())
743 // To "insert" a SELECT_CC instruction, we actually have to insert the
744 // diamond control-flow pattern. The incoming instruction knows the
745 // destination vreg to set, the condition code register to branch on, the
746 // true/false values to select between, and a branch opcode to use.
747 const BasicBlock *LLVM_BB = BB->getBasicBlock();
748 MachineFunction::iterator It = BB;
755 // bNE r1, r0, copy1MBB
756 // fallthrough --> copy0MBB
757 MachineBasicBlock *thisMBB = BB;
758 MachineFunction *F = BB->getParent();
759 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
760 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
761 F->insert(It, copy0MBB);
762 F->insert(It, sinkMBB);
764 // Transfer the remainder of BB and its successor edges to sinkMBB.
765 sinkMBB->splice(sinkMBB->begin(), BB,
766 llvm::next(MachineBasicBlock::iterator(MI)),
768 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
770 // Next, add the true and fallthrough blocks as its successors.
771 BB->addSuccessor(copy0MBB);
772 BB->addSuccessor(sinkMBB);
774 // Emit the right instruction according to the type of the operands compared
776 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
778 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
779 .addReg(Mips::ZERO).addMBB(sinkMBB);
783 // # fallthrough to sinkMBB
786 // Update machine-CFG edges
787 BB->addSuccessor(sinkMBB);
790 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
795 BuildMI(*BB, BB->begin(), dl,
796 TII->get(Mips::PHI), MI->getOperand(0).getReg())
797 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
798 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
800 BuildMI(*BB, BB->begin(), dl,
801 TII->get(Mips::PHI), MI->getOperand(0).getReg())
802 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
803 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
805 MI->eraseFromParent(); // The pseudo instruction is gone now.
810 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
811 MachineBasicBlock *BB) const {
812 switch (MI->getOpcode()) {
814 assert(false && "Unexpected instr type to insert");
816 case Mips::ATOMIC_LOAD_ADD_I8:
817 case Mips::ATOMIC_LOAD_ADD_I8_P8:
818 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
819 case Mips::ATOMIC_LOAD_ADD_I16:
820 case Mips::ATOMIC_LOAD_ADD_I16_P8:
821 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
822 case Mips::ATOMIC_LOAD_ADD_I32:
823 case Mips::ATOMIC_LOAD_ADD_I32_P8:
824 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
825 case Mips::ATOMIC_LOAD_ADD_I64:
826 case Mips::ATOMIC_LOAD_ADD_I64_P8:
827 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
829 case Mips::ATOMIC_LOAD_AND_I8:
830 case Mips::ATOMIC_LOAD_AND_I8_P8:
831 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
832 case Mips::ATOMIC_LOAD_AND_I16:
833 case Mips::ATOMIC_LOAD_AND_I16_P8:
834 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
835 case Mips::ATOMIC_LOAD_AND_I32:
836 case Mips::ATOMIC_LOAD_AND_I32_P8:
837 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
838 case Mips::ATOMIC_LOAD_AND_I64:
839 case Mips::ATOMIC_LOAD_AND_I64_P8:
840 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
842 case Mips::ATOMIC_LOAD_OR_I8:
843 case Mips::ATOMIC_LOAD_OR_I8_P8:
844 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
845 case Mips::ATOMIC_LOAD_OR_I16:
846 case Mips::ATOMIC_LOAD_OR_I16_P8:
847 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
848 case Mips::ATOMIC_LOAD_OR_I32:
849 case Mips::ATOMIC_LOAD_OR_I32_P8:
850 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
851 case Mips::ATOMIC_LOAD_OR_I64:
852 case Mips::ATOMIC_LOAD_OR_I64_P8:
853 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
855 case Mips::ATOMIC_LOAD_XOR_I8:
856 case Mips::ATOMIC_LOAD_XOR_I8_P8:
857 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
858 case Mips::ATOMIC_LOAD_XOR_I16:
859 case Mips::ATOMIC_LOAD_XOR_I16_P8:
860 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
861 case Mips::ATOMIC_LOAD_XOR_I32:
862 case Mips::ATOMIC_LOAD_XOR_I32_P8:
863 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
864 case Mips::ATOMIC_LOAD_XOR_I64:
865 case Mips::ATOMIC_LOAD_XOR_I64_P8:
866 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
868 case Mips::ATOMIC_LOAD_NAND_I8:
869 case Mips::ATOMIC_LOAD_NAND_I8_P8:
870 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
871 case Mips::ATOMIC_LOAD_NAND_I16:
872 case Mips::ATOMIC_LOAD_NAND_I16_P8:
873 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
874 case Mips::ATOMIC_LOAD_NAND_I32:
875 case Mips::ATOMIC_LOAD_NAND_I32_P8:
876 return EmitAtomicBinary(MI, BB, 4, 0, true);
877 case Mips::ATOMIC_LOAD_NAND_I64:
878 case Mips::ATOMIC_LOAD_NAND_I64_P8:
879 return EmitAtomicBinary(MI, BB, 8, 0, true);
881 case Mips::ATOMIC_LOAD_SUB_I8:
882 case Mips::ATOMIC_LOAD_SUB_I8_P8:
883 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
884 case Mips::ATOMIC_LOAD_SUB_I16:
885 case Mips::ATOMIC_LOAD_SUB_I16_P8:
886 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
887 case Mips::ATOMIC_LOAD_SUB_I32:
888 case Mips::ATOMIC_LOAD_SUB_I32_P8:
889 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
890 case Mips::ATOMIC_LOAD_SUB_I64:
891 case Mips::ATOMIC_LOAD_SUB_I64_P8:
892 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
894 case Mips::ATOMIC_SWAP_I8:
895 case Mips::ATOMIC_SWAP_I8_P8:
896 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
897 case Mips::ATOMIC_SWAP_I16:
898 case Mips::ATOMIC_SWAP_I16_P8:
899 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
900 case Mips::ATOMIC_SWAP_I32:
901 case Mips::ATOMIC_SWAP_I32_P8:
902 return EmitAtomicBinary(MI, BB, 4, 0);
903 case Mips::ATOMIC_SWAP_I64:
904 case Mips::ATOMIC_SWAP_I64_P8:
905 return EmitAtomicBinary(MI, BB, 8, 0);
907 case Mips::ATOMIC_CMP_SWAP_I8:
908 case Mips::ATOMIC_CMP_SWAP_I8_P8:
909 return EmitAtomicCmpSwapPartword(MI, BB, 1);
910 case Mips::ATOMIC_CMP_SWAP_I16:
911 case Mips::ATOMIC_CMP_SWAP_I16_P8:
912 return EmitAtomicCmpSwapPartword(MI, BB, 2);
913 case Mips::ATOMIC_CMP_SWAP_I32:
914 case Mips::ATOMIC_CMP_SWAP_I32_P8:
915 return EmitAtomicCmpSwap(MI, BB, 4);
916 case Mips::ATOMIC_CMP_SWAP_I64:
917 case Mips::ATOMIC_CMP_SWAP_I64_P8:
918 return EmitAtomicCmpSwap(MI, BB, 8);
922 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
923 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
925 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
926 unsigned Size, unsigned BinOpcode,
928 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
930 MachineFunction *MF = BB->getParent();
931 MachineRegisterInfo &RegInfo = MF->getRegInfo();
932 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
933 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
934 DebugLoc dl = MI->getDebugLoc();
935 unsigned LL, SC, AND, NOR, ZERO, BEQ;
938 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
939 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
946 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
947 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
950 ZERO = Mips::ZERO_64;
954 unsigned OldVal = MI->getOperand(0).getReg();
955 unsigned Ptr = MI->getOperand(1).getReg();
956 unsigned Incr = MI->getOperand(2).getReg();
958 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
959 unsigned AndRes = RegInfo.createVirtualRegister(RC);
960 unsigned Success = RegInfo.createVirtualRegister(RC);
962 // insert new blocks after the current block
963 const BasicBlock *LLVM_BB = BB->getBasicBlock();
964 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
965 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
966 MachineFunction::iterator It = BB;
968 MF->insert(It, loopMBB);
969 MF->insert(It, exitMBB);
971 // Transfer the remainder of BB and its successor edges to exitMBB.
972 exitMBB->splice(exitMBB->begin(), BB,
973 llvm::next(MachineBasicBlock::iterator(MI)),
975 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
979 // fallthrough --> loopMBB
980 BB->addSuccessor(loopMBB);
981 loopMBB->addSuccessor(loopMBB);
982 loopMBB->addSuccessor(exitMBB);
986 // <binop> storeval, oldval, incr
987 // sc success, storeval, 0(ptr)
988 // beq success, $0, loopMBB
990 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
992 // and andres, oldval, incr
993 // nor storeval, $0, andres
994 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
995 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
996 } else if (BinOpcode) {
997 // <binop> storeval, oldval, incr
998 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1002 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1003 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1005 MI->eraseFromParent(); // The instruction is gone now.
1011 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1012 MachineBasicBlock *BB,
1013 unsigned Size, unsigned BinOpcode,
1015 assert((Size == 1 || Size == 2) &&
1016 "Unsupported size for EmitAtomicBinaryPartial.");
1018 MachineFunction *MF = BB->getParent();
1019 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1020 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1021 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1022 DebugLoc dl = MI->getDebugLoc();
1023 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1024 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1026 unsigned Dest = MI->getOperand(0).getReg();
1027 unsigned Ptr = MI->getOperand(1).getReg();
1028 unsigned Incr = MI->getOperand(2).getReg();
1030 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1031 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1032 unsigned Mask = RegInfo.createVirtualRegister(RC);
1033 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1034 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1035 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1036 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1037 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1038 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1039 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1040 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1041 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1042 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1043 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1044 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1045 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1046 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1047 unsigned Success = RegInfo.createVirtualRegister(RC);
1049 // insert new blocks after the current block
1050 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1051 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1052 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1053 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1054 MachineFunction::iterator It = BB;
1056 MF->insert(It, loopMBB);
1057 MF->insert(It, sinkMBB);
1058 MF->insert(It, exitMBB);
1060 // Transfer the remainder of BB and its successor edges to exitMBB.
1061 exitMBB->splice(exitMBB->begin(), BB,
1062 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1063 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1065 BB->addSuccessor(loopMBB);
1066 loopMBB->addSuccessor(loopMBB);
1067 loopMBB->addSuccessor(sinkMBB);
1068 sinkMBB->addSuccessor(exitMBB);
1071 // addiu masklsb2,$0,-4 # 0xfffffffc
1072 // and alignedaddr,ptr,masklsb2
1073 // andi ptrlsb2,ptr,3
1074 // sll shiftamt,ptrlsb2,3
1075 // ori maskupper,$0,255 # 0xff
1076 // sll mask,maskupper,shiftamt
1077 // nor mask2,$0,mask
1078 // sll incr2,incr,shiftamt
1080 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1081 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1082 .addReg(Mips::ZERO).addImm(-4);
1083 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1084 .addReg(Ptr).addReg(MaskLSB2);
1085 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1086 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1087 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1088 .addReg(Mips::ZERO).addImm(MaskImm);
1089 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1090 .addReg(ShiftAmt).addReg(MaskUpper);
1091 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1092 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1094 // atomic.load.binop
1096 // ll oldval,0(alignedaddr)
1097 // binop binopres,oldval,incr2
1098 // and newval,binopres,mask
1099 // and maskedoldval0,oldval,mask2
1100 // or storeval,maskedoldval0,newval
1101 // sc success,storeval,0(alignedaddr)
1102 // beq success,$0,loopMBB
1106 // ll oldval,0(alignedaddr)
1107 // and newval,incr2,mask
1108 // and maskedoldval0,oldval,mask2
1109 // or storeval,maskedoldval0,newval
1110 // sc success,storeval,0(alignedaddr)
1111 // beq success,$0,loopMBB
1114 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1116 // and andres, oldval, incr2
1117 // nor binopres, $0, andres
1118 // and newval, binopres, mask
1119 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1120 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1121 .addReg(Mips::ZERO).addReg(AndRes);
1122 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1123 } else if (BinOpcode) {
1124 // <binop> binopres, oldval, incr2
1125 // and newval, binopres, mask
1126 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1127 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1128 } else {// atomic.swap
1129 // and newval, incr2, mask
1130 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1133 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1134 .addReg(OldVal).addReg(Mask2);
1135 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1136 .addReg(MaskedOldVal0).addReg(NewVal);
1137 BuildMI(BB, dl, TII->get(SC), Success)
1138 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1139 BuildMI(BB, dl, TII->get(Mips::BEQ))
1140 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1143 // and maskedoldval1,oldval,mask
1144 // srl srlres,maskedoldval1,shiftamt
1145 // sll sllres,srlres,24
1146 // sra dest,sllres,24
1148 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1150 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1151 .addReg(OldVal).addReg(Mask);
1152 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1153 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1154 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1155 .addReg(SrlRes).addImm(ShiftImm);
1156 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1157 .addReg(SllRes).addImm(ShiftImm);
1159 MI->eraseFromParent(); // The instruction is gone now.
1165 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1166 MachineBasicBlock *BB,
1167 unsigned Size) const {
1168 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1170 MachineFunction *MF = BB->getParent();
1171 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1172 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1173 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1174 DebugLoc dl = MI->getDebugLoc();
1175 unsigned LL, SC, ZERO, BNE, BEQ;
1178 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1179 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1185 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1186 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1187 ZERO = Mips::ZERO_64;
1192 unsigned Dest = MI->getOperand(0).getReg();
1193 unsigned Ptr = MI->getOperand(1).getReg();
1194 unsigned OldVal = MI->getOperand(2).getReg();
1195 unsigned NewVal = MI->getOperand(3).getReg();
1197 unsigned Success = RegInfo.createVirtualRegister(RC);
1199 // insert new blocks after the current block
1200 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1201 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1202 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1203 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204 MachineFunction::iterator It = BB;
1206 MF->insert(It, loop1MBB);
1207 MF->insert(It, loop2MBB);
1208 MF->insert(It, exitMBB);
1210 // Transfer the remainder of BB and its successor edges to exitMBB.
1211 exitMBB->splice(exitMBB->begin(), BB,
1212 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1213 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1217 // fallthrough --> loop1MBB
1218 BB->addSuccessor(loop1MBB);
1219 loop1MBB->addSuccessor(exitMBB);
1220 loop1MBB->addSuccessor(loop2MBB);
1221 loop2MBB->addSuccessor(loop1MBB);
1222 loop2MBB->addSuccessor(exitMBB);
1226 // bne dest, oldval, exitMBB
1228 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1229 BuildMI(BB, dl, TII->get(BNE))
1230 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1233 // sc success, newval, 0(ptr)
1234 // beq success, $0, loop1MBB
1236 BuildMI(BB, dl, TII->get(SC), Success)
1237 .addReg(NewVal).addReg(Ptr).addImm(0);
1238 BuildMI(BB, dl, TII->get(BEQ))
1239 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1241 MI->eraseFromParent(); // The instruction is gone now.
1247 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1248 MachineBasicBlock *BB,
1249 unsigned Size) const {
1250 assert((Size == 1 || Size == 2) &&
1251 "Unsupported size for EmitAtomicCmpSwapPartial.");
1253 MachineFunction *MF = BB->getParent();
1254 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1255 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1257 DebugLoc dl = MI->getDebugLoc();
1258 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1259 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1261 unsigned Dest = MI->getOperand(0).getReg();
1262 unsigned Ptr = MI->getOperand(1).getReg();
1263 unsigned CmpVal = MI->getOperand(2).getReg();
1264 unsigned NewVal = MI->getOperand(3).getReg();
1266 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1267 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1268 unsigned Mask = RegInfo.createVirtualRegister(RC);
1269 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1270 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1271 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1272 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1273 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1274 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1275 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1276 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1277 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1278 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1279 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1280 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1281 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1282 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1283 unsigned Success = RegInfo.createVirtualRegister(RC);
1285 // insert new blocks after the current block
1286 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1287 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1288 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1289 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1290 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1291 MachineFunction::iterator It = BB;
1293 MF->insert(It, loop1MBB);
1294 MF->insert(It, loop2MBB);
1295 MF->insert(It, sinkMBB);
1296 MF->insert(It, exitMBB);
1298 // Transfer the remainder of BB and its successor edges to exitMBB.
1299 exitMBB->splice(exitMBB->begin(), BB,
1300 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1301 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1303 BB->addSuccessor(loop1MBB);
1304 loop1MBB->addSuccessor(sinkMBB);
1305 loop1MBB->addSuccessor(loop2MBB);
1306 loop2MBB->addSuccessor(loop1MBB);
1307 loop2MBB->addSuccessor(sinkMBB);
1308 sinkMBB->addSuccessor(exitMBB);
1310 // FIXME: computation of newval2 can be moved to loop2MBB.
1312 // addiu masklsb2,$0,-4 # 0xfffffffc
1313 // and alignedaddr,ptr,masklsb2
1314 // andi ptrlsb2,ptr,3
1315 // sll shiftamt,ptrlsb2,3
1316 // ori maskupper,$0,255 # 0xff
1317 // sll mask,maskupper,shiftamt
1318 // nor mask2,$0,mask
1319 // andi maskedcmpval,cmpval,255
1320 // sll shiftedcmpval,maskedcmpval,shiftamt
1321 // andi maskednewval,newval,255
1322 // sll shiftednewval,maskednewval,shiftamt
1323 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1324 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1325 .addReg(Mips::ZERO).addImm(-4);
1326 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1327 .addReg(Ptr).addReg(MaskLSB2);
1328 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1329 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1330 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1331 .addReg(Mips::ZERO).addImm(MaskImm);
1332 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1333 .addReg(ShiftAmt).addReg(MaskUpper);
1334 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1335 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1336 .addReg(CmpVal).addImm(MaskImm);
1337 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1338 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1339 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1340 .addReg(NewVal).addImm(MaskImm);
1341 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1342 .addReg(ShiftAmt).addReg(MaskedNewVal);
1345 // ll oldval,0(alginedaddr)
1346 // and maskedoldval0,oldval,mask
1347 // bne maskedoldval0,shiftedcmpval,sinkMBB
1349 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1350 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1351 .addReg(OldVal).addReg(Mask);
1352 BuildMI(BB, dl, TII->get(Mips::BNE))
1353 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1356 // and maskedoldval1,oldval,mask2
1357 // or storeval,maskedoldval1,shiftednewval
1358 // sc success,storeval,0(alignedaddr)
1359 // beq success,$0,loop1MBB
1361 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1362 .addReg(OldVal).addReg(Mask2);
1363 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1364 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1365 BuildMI(BB, dl, TII->get(SC), Success)
1366 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1367 BuildMI(BB, dl, TII->get(Mips::BEQ))
1368 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1371 // srl srlres,maskedoldval0,shiftamt
1372 // sll sllres,srlres,24
1373 // sra dest,sllres,24
1375 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1377 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1378 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1379 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1380 .addReg(SrlRes).addImm(ShiftImm);
1381 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1382 .addReg(SllRes).addImm(ShiftImm);
1384 MI->eraseFromParent(); // The instruction is gone now.
1389 //===----------------------------------------------------------------------===//
1390 // Misc Lower Operation implementation
1391 //===----------------------------------------------------------------------===//
1392 SDValue MipsTargetLowering::
1393 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1395 MachineFunction &MF = DAG.getMachineFunction();
1396 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1397 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1399 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1400 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1401 "Cannot lower if the alignment of the allocated space is larger than \
1402 that of the stack.");
1404 SDValue Chain = Op.getOperand(0);
1405 SDValue Size = Op.getOperand(1);
1406 DebugLoc dl = Op.getDebugLoc();
1408 // Get a reference from Mips stack pointer
1409 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1411 // Subtract the dynamic size from the actual stack size to
1412 // obtain the new stack size.
1413 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1415 // The Sub result contains the new stack start address, so it
1416 // must be placed in the stack pointer register.
1417 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1419 // This node always has two return values: a new stack pointer
1420 // value and a chain
1421 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1422 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1423 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1425 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1428 SDValue MipsTargetLowering::
1429 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1431 // The first operand is the chain, the second is the condition, the third is
1432 // the block to branch to if the condition is true.
1433 SDValue Chain = Op.getOperand(0);
1434 SDValue Dest = Op.getOperand(2);
1435 DebugLoc dl = Op.getDebugLoc();
1437 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1439 // Return if flag is not set by a floating point comparison.
1440 if (CondRes.getOpcode() != MipsISD::FPCmp)
1443 SDValue CCNode = CondRes.getOperand(2);
1445 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1446 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1448 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1452 SDValue MipsTargetLowering::
1453 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1455 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1457 // Return if flag is not set by a floating point comparison.
1458 if (Cond.getOpcode() != MipsISD::FPCmp)
1461 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1465 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1466 SelectionDAG &DAG) const {
1467 // FIXME there isn't actually debug info here
1468 DebugLoc dl = Op.getDebugLoc();
1469 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1471 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1472 SDVTList VTs = DAG.getVTList(MVT::i32);
1474 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1476 // %gp_rel relocation
1477 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1478 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1480 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1481 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1482 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1484 // %hi/%lo relocation
1485 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1487 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1489 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1490 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1491 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1494 EVT ValTy = Op.getValueType();
1495 bool HasGotOfst = (GV->hasInternalLinkage() ||
1496 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1497 unsigned GotFlag = IsN64 ?
1498 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1499 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1500 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1501 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GA);
1502 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1503 MachinePointerInfo(), false, false, false, 0);
1504 // On functions and global targets not internal linked only
1505 // a load from got/GP is necessary for PIC to work.
1508 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1509 IsN64 ? MipsII::MO_GOT_OFST :
1511 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1512 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1515 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1516 SelectionDAG &DAG) const {
1517 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1518 // FIXME there isn't actually debug info here
1519 DebugLoc dl = Op.getDebugLoc();
1521 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1522 // %hi/%lo relocation
1523 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1524 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1525 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1526 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1527 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1530 EVT ValTy = Op.getValueType();
1531 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1532 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1533 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1534 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy, BAGOTOffset);
1535 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1536 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1537 MachinePointerInfo(), false, false, false, 0);
1538 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1539 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1542 SDValue MipsTargetLowering::
1543 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1545 // If the relocation model is PIC, use the General Dynamic TLS Model or
1546 // Local Dynamic TLS model, otherwise use the Initial Exec or
1547 // Local Exec TLS Model.
1549 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1550 DebugLoc dl = GA->getDebugLoc();
1551 const GlobalValue *GV = GA->getGlobal();
1552 EVT PtrVT = getPointerTy();
1554 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1555 // General Dynamic TLS Model
1556 bool LocalDynamic = GV->hasInternalLinkage();
1557 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1558 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1559 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1560 unsigned PtrSize = PtrVT.getSizeInBits();
1561 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1563 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1567 Entry.Node = Argument;
1569 Args.push_back(Entry);
1571 std::pair<SDValue, SDValue> CallResult =
1572 LowerCallTo(DAG.getEntryNode(), PtrTy,
1573 false, false, false, false, 0, CallingConv::C, false, true,
1574 TlsGetAddr, Args, DAG, dl);
1576 SDValue Ret = CallResult.first;
1581 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1582 MipsII::MO_DTPREL_HI);
1583 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1584 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1585 MipsII::MO_DTPREL_LO);
1586 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1587 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1588 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1592 if (GV->isDeclaration()) {
1593 // Initial Exec TLS Model
1594 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1595 MipsII::MO_GOTTPREL);
1596 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1597 Offset = DAG.getLoad(PtrVT, dl,
1598 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1599 false, false, false, 0);
1601 // Local Exec TLS Model
1602 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1603 MipsII::MO_TPREL_HI);
1604 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1605 MipsII::MO_TPREL_LO);
1606 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1607 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1608 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1611 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1612 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1615 SDValue MipsTargetLowering::
1616 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1618 SDValue HiPart, JTI, JTILo;
1619 // FIXME there isn't actually debug info here
1620 DebugLoc dl = Op.getDebugLoc();
1621 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1622 EVT PtrVT = Op.getValueType();
1623 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1625 if (!IsPIC && !IsN64) {
1626 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1627 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1628 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1629 } else {// Emit Load from Global Pointer
1630 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1631 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1632 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1633 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, JTI);
1634 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1635 MachinePointerInfo(), false, false, false, 0);
1636 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1639 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1640 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1643 SDValue MipsTargetLowering::
1644 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1647 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1648 const Constant *C = N->getConstVal();
1649 // FIXME there isn't actually debug info here
1650 DebugLoc dl = Op.getDebugLoc();
1652 // gp_rel relocation
1653 // FIXME: we should reference the constant pool using small data sections,
1654 // but the asm printer currently doesn't support this feature without
1655 // hacking it. This feature should come soon so we can uncomment the
1657 //if (IsInSmallSection(C->getType())) {
1658 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1659 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1660 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1662 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1663 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1664 N->getOffset(), MipsII::MO_ABS_HI);
1665 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1666 N->getOffset(), MipsII::MO_ABS_LO);
1667 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1668 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1669 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1671 EVT ValTy = Op.getValueType();
1672 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1673 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1674 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1675 N->getOffset(), GOTFlag);
1676 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, CP);
1677 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1678 MachinePointerInfo::getConstantPool(), false,
1680 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1681 N->getOffset(), OFSTFlag);
1682 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1683 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1689 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1690 MachineFunction &MF = DAG.getMachineFunction();
1691 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1693 DebugLoc dl = Op.getDebugLoc();
1694 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1697 // vastart just stores the address of the VarArgsFrameIndex slot into the
1698 // memory location argument.
1699 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1700 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1701 MachinePointerInfo(SV), false, false, 0);
1704 // Called if the size of integer registers is large enough to hold the whole
1705 // floating point number.
1706 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1707 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1708 EVT ValTy = Op.getValueType();
1709 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1710 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1711 DebugLoc dl = Op.getDebugLoc();
1712 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1713 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1714 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1715 DAG.getConstant(Mask - 1, IntValTy));
1716 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1717 DAG.getConstant(Mask, IntValTy));
1718 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1719 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1722 // Called if the size of integer registers is not large enough to hold the whole
1723 // floating point number (e.g. f64 & 32-bit integer register).
1725 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1727 // Use ext/ins instructions if target architecture is Mips32r2.
1728 // Eliminate redundant mfc1 and mtc1 instructions.
1729 unsigned LoIdx = 0, HiIdx = 1;
1732 std::swap(LoIdx, HiIdx);
1734 DebugLoc dl = Op.getDebugLoc();
1735 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1737 DAG.getConstant(LoIdx, MVT::i32));
1738 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1739 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1740 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1741 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1742 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1743 DAG.getConstant(0x7fffffff, MVT::i32));
1744 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1745 DAG.getConstant(0x80000000, MVT::i32));
1746 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1749 std::swap(Word0, Word1);
1751 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1755 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1756 EVT Ty = Op.getValueType();
1758 assert(Ty == MVT::f32 || Ty == MVT::f64);
1760 if (Ty == MVT::f32 || HasMips64)
1761 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1763 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1766 SDValue MipsTargetLowering::
1767 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1769 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1770 "Frame address can only be determined for current frame.");
1772 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1773 MFI->setFrameAddressIsTaken(true);
1774 EVT VT = Op.getValueType();
1775 DebugLoc dl = Op.getDebugLoc();
1776 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1777 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1781 // TODO: set SType according to the desired memory barrier behavior.
1783 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1785 DebugLoc dl = Op.getDebugLoc();
1786 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1787 DAG.getConstant(SType, MVT::i32));
1790 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1791 SelectionDAG& DAG) const {
1792 // FIXME: Need pseudo-fence for 'singlethread' fences
1793 // FIXME: Set SType for weaker fences where supported/appropriate.
1795 DebugLoc dl = Op.getDebugLoc();
1796 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1797 DAG.getConstant(SType, MVT::i32));
1800 //===----------------------------------------------------------------------===//
1801 // Calling Convention Implementation
1802 //===----------------------------------------------------------------------===//
1804 //===----------------------------------------------------------------------===//
1805 // TODO: Implement a generic logic using tblgen that can support this.
1806 // Mips O32 ABI rules:
1808 // i32 - Passed in A0, A1, A2, A3 and stack
1809 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1810 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1811 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1812 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1813 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1816 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1817 //===----------------------------------------------------------------------===//
1819 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1820 MVT LocVT, CCValAssign::LocInfo LocInfo,
1821 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1823 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1825 static const unsigned IntRegs[] = {
1826 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1828 static const unsigned F32Regs[] = {
1829 Mips::F12, Mips::F14
1831 static const unsigned F64Regs[] = {
1836 if (ArgFlags.isByVal()) {
1837 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1838 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1839 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1840 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1841 r < std::min(IntRegsSize, NextReg); ++r)
1842 State.AllocateReg(IntRegs[r]);
1846 // Promote i8 and i16
1847 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1849 if (ArgFlags.isSExt())
1850 LocInfo = CCValAssign::SExt;
1851 else if (ArgFlags.isZExt())
1852 LocInfo = CCValAssign::ZExt;
1854 LocInfo = CCValAssign::AExt;
1859 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1860 // is true: function is vararg, argument is 3rd or higher, there is previous
1861 // argument which is not f32 or f64.
1862 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1863 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1864 unsigned OrigAlign = ArgFlags.getOrigAlign();
1865 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1867 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1868 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1869 // If this is the first part of an i64 arg,
1870 // the allocated register must be either A0 or A2.
1871 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1872 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1874 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1875 // Allocate int register and shadow next int register. If first
1876 // available register is Mips::A1 or Mips::A3, shadow it too.
1877 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1878 if (Reg == Mips::A1 || Reg == Mips::A3)
1879 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1880 State.AllocateReg(IntRegs, IntRegsSize);
1882 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1883 // we are guaranteed to find an available float register
1884 if (ValVT == MVT::f32) {
1885 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1886 // Shadow int register
1887 State.AllocateReg(IntRegs, IntRegsSize);
1889 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1890 // Shadow int registers
1891 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1892 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1893 State.AllocateReg(IntRegs, IntRegsSize);
1894 State.AllocateReg(IntRegs, IntRegsSize);
1897 llvm_unreachable("Cannot handle this ValVT.");
1899 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1900 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1903 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1905 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1907 return false; // CC must always match
1910 static const unsigned Mips64IntRegs[8] =
1911 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1912 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1913 static const unsigned Mips64DPRegs[8] =
1914 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1915 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1917 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1918 CCValAssign::LocInfo LocInfo,
1919 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1920 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1921 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1922 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1924 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1926 // If byval is 16-byte aligned, the first arg register must be even.
1927 if ((Align == 16) && (FirstIdx % 2)) {
1928 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1932 // Mark the registers allocated.
1933 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1934 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1936 // Allocate space on caller's stack.
1937 unsigned Offset = State.AllocateStack(Size, Align);
1940 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1943 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1948 #include "MipsGenCallingConv.inc"
1951 AnalyzeMips64CallOperands(CCState &CCInfo,
1952 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1953 unsigned NumOps = Outs.size();
1954 for (unsigned i = 0; i != NumOps; ++i) {
1955 MVT ArgVT = Outs[i].VT;
1956 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1959 if (Outs[i].IsFixed)
1960 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1962 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1966 dbgs() << "Call operand #" << i << " has unhandled type "
1967 << EVT(ArgVT).getEVTString();
1969 llvm_unreachable(0);
1974 //===----------------------------------------------------------------------===//
1975 // Call Calling Convention Implementation
1976 //===----------------------------------------------------------------------===//
1978 static const unsigned O32IntRegsSize = 4;
1980 static const unsigned O32IntRegs[] = {
1981 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1984 // Return next O32 integer argument register.
1985 static unsigned getNextIntArgReg(unsigned Reg) {
1986 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1987 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1990 // Write ByVal Arg to arg registers and stack.
1992 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1993 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1994 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1995 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1996 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1997 MVT PtrType, bool isLittle) {
1998 unsigned LocMemOffset = VA.getLocMemOffset();
1999 unsigned Offset = 0;
2000 uint32_t RemainingSize = Flags.getByValSize();
2001 unsigned ByValAlign = Flags.getByValAlign();
2003 // Copy the first 4 words of byval arg to registers A0 - A3.
2004 // FIXME: Use a stricter alignment if it enables better optimization in passes
2006 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2007 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2008 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2009 DAG.getConstant(Offset, MVT::i32));
2010 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2011 MachinePointerInfo(), false, false, false,
2012 std::min(ByValAlign, (unsigned )4));
2013 MemOpChains.push_back(LoadVal.getValue(1));
2014 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2015 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2018 if (RemainingSize == 0)
2021 // If there still is a register available for argument passing, write the
2022 // remaining part of the structure to it using subword loads and shifts.
2023 if (LocMemOffset < 4 * 4) {
2024 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2025 "There must be one to three bytes remaining.");
2026 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2027 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2028 DAG.getConstant(Offset, MVT::i32));
2029 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2030 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2031 LoadPtr, MachinePointerInfo(),
2032 MVT::getIntegerVT(LoadSize * 8), false,
2034 MemOpChains.push_back(LoadVal.getValue(1));
2036 // If target is big endian, shift it to the most significant half-word or
2039 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2040 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2043 RemainingSize -= LoadSize;
2045 // Read second subword if necessary.
2046 if (RemainingSize != 0) {
2047 assert(RemainingSize == 1 && "There must be one byte remaining.");
2048 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2049 DAG.getConstant(Offset, MVT::i32));
2050 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2051 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2052 LoadPtr, MachinePointerInfo(),
2053 MVT::i8, false, false, Alignment);
2054 MemOpChains.push_back(Subword.getValue(1));
2055 // Insert the loaded byte to LoadVal.
2056 // FIXME: Use INS if supported by target.
2057 unsigned ShiftAmt = isLittle ? 16 : 8;
2058 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2059 DAG.getConstant(ShiftAmt, MVT::i32));
2060 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2063 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2064 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2068 // Create a fixed object on stack at offset LocMemOffset and copy
2069 // remaining part of byval arg to it using memcpy.
2070 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2071 DAG.getConstant(Offset, MVT::i32));
2072 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2073 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2074 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2075 DAG.getConstant(RemainingSize, MVT::i32),
2076 std::min(ByValAlign, (unsigned)4),
2077 /*isVolatile=*/false, /*AlwaysInline=*/false,
2078 MachinePointerInfo(0), MachinePointerInfo(0));
2081 // Copy Mips64 byVal arg to registers and stack.
2083 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2084 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2085 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2086 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2087 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2088 EVT PtrTy, bool isLittle) {
2089 unsigned ByValSize = Flags.getByValSize();
2090 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2091 bool IsRegLoc = VA.isRegLoc();
2092 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2093 unsigned LocMemOffset = 0;
2094 unsigned MemCpySize = ByValSize;
2097 LocMemOffset = VA.getLocMemOffset();
2099 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2101 const unsigned *RegEnd = Mips64IntRegs + 8;
2103 // Copy double words to registers.
2104 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2105 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2106 DAG.getConstant(Offset, PtrTy));
2107 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2108 MachinePointerInfo(), false, false, false,
2110 MemOpChains.push_back(LoadVal.getValue(1));
2111 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2114 // Return if the struct has been fully copied.
2115 if (!(MemCpySize = ByValSize - Offset))
2118 // If there is an argument register available, copy the remainder of the
2119 // byval argument with sub-doubleword loads and shifts.
2120 if (Reg != RegEnd) {
2121 assert((ByValSize < Offset + 8) &&
2122 "Size of the remainder should be smaller than 8-byte.");
2124 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2125 unsigned RemSize = ByValSize - Offset;
2127 if (RemSize < LoadSize)
2130 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2131 DAG.getConstant(Offset, PtrTy));
2133 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2134 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2135 false, false, Alignment);
2136 MemOpChains.push_back(LoadVal.getValue(1));
2138 // Offset in number of bits from double word boundary.
2139 unsigned OffsetDW = (Offset % 8) * 8;
2140 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2141 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2142 DAG.getConstant(Shamt, MVT::i32));
2144 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2147 Alignment = std::min(Alignment, LoadSize);
2150 RegsToPass.push_back(std::make_pair(*Reg, Val));
2155 assert(MemCpySize && "MemCpySize must not be zero.");
2157 // Create a fixed object on stack at offset LocMemOffset and copy
2158 // remainder of byval arg to it with memcpy.
2159 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2160 DAG.getConstant(Offset, PtrTy));
2161 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2162 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2163 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2164 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2165 /*isVolatile=*/false, /*AlwaysInline=*/false,
2166 MachinePointerInfo(0), MachinePointerInfo(0));
2169 /// LowerCall - functions arguments are copied from virtual regs to
2170 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2171 /// TODO: isTailCall.
2173 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2174 CallingConv::ID CallConv, bool isVarArg,
2176 const SmallVectorImpl<ISD::OutputArg> &Outs,
2177 const SmallVectorImpl<SDValue> &OutVals,
2178 const SmallVectorImpl<ISD::InputArg> &Ins,
2179 DebugLoc dl, SelectionDAG &DAG,
2180 SmallVectorImpl<SDValue> &InVals) const {
2181 // MIPs target does not yet support tail call optimization.
2184 MachineFunction &MF = DAG.getMachineFunction();
2185 MachineFrameInfo *MFI = MF.getFrameInfo();
2186 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2187 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2188 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2190 // Analyze operands of the call, assigning locations to each operand.
2191 SmallVector<CCValAssign, 16> ArgLocs;
2192 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2193 getTargetMachine(), ArgLocs, *DAG.getContext());
2196 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2198 AnalyzeMips64CallOperands(CCInfo, Outs);
2200 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2202 // Get a count of how many bytes are to be pushed on the stack.
2203 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2205 // Chain is the output chain of the last Load/Store or CopyToReg node.
2206 // ByValChain is the output chain of the last Memcpy node created for copying
2207 // byval arguments to the stack.
2208 SDValue Chain, CallSeqStart, ByValChain;
2209 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2210 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2211 ByValChain = InChain;
2213 // If this is the first call, create a stack frame object that points to
2214 // a location to which .cprestore saves $gp.
2215 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2216 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2218 // Get the frame index of the stack frame object that points to the location
2219 // of dynamically allocated area on the stack.
2220 int DynAllocFI = MipsFI->getDynAllocFI();
2222 // Update size of the maximum argument space.
2223 // For O32, a minimum of four words (16 bytes) of argument space is
2226 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2228 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2230 if (MaxCallFrameSize < NextStackOffset) {
2231 MipsFI->setMaxCallFrameSize(NextStackOffset);
2233 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2234 // allocated stack space. These offsets must be aligned to a boundary
2235 // determined by the stack alignment of the ABI.
2236 unsigned StackAlignment = TFL->getStackAlignment();
2237 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2238 StackAlignment * StackAlignment;
2240 if (MipsFI->needGPSaveRestore())
2241 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2243 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2246 // With EABI is it possible to have 16 args on registers.
2247 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2248 SmallVector<SDValue, 8> MemOpChains;
2250 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2252 // Walk the register/memloc assignments, inserting copies/loads.
2253 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2254 SDValue Arg = OutVals[i];
2255 CCValAssign &VA = ArgLocs[i];
2256 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2257 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2260 if (Flags.isByVal()) {
2261 assert(Flags.getByValSize() &&
2262 "ByVal args of size 0 should have been ignored by front-end.");
2264 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2265 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2266 Subtarget->isLittle());
2268 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2269 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2270 Subtarget->isLittle());
2274 // Promote the value if needed.
2275 switch (VA.getLocInfo()) {
2276 default: llvm_unreachable("Unknown loc info!");
2277 case CCValAssign::Full:
2278 if (VA.isRegLoc()) {
2279 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2280 (ValVT == MVT::f64 && LocVT == MVT::i64))
2281 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2282 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2283 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2284 Arg, DAG.getConstant(0, MVT::i32));
2285 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2286 Arg, DAG.getConstant(1, MVT::i32));
2287 if (!Subtarget->isLittle())
2289 unsigned LocRegLo = VA.getLocReg();
2290 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2291 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2292 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2297 case CCValAssign::SExt:
2298 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2300 case CCValAssign::ZExt:
2301 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2303 case CCValAssign::AExt:
2304 if (ValVT == MVT::i32)
2305 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2307 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2311 // Arguments that can be passed on register must be kept at
2312 // RegsToPass vector
2313 if (VA.isRegLoc()) {
2314 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2318 // Register can't get to this point...
2319 assert(VA.isMemLoc());
2321 // Create the frame index object for this incoming parameter
2322 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2323 VA.getLocMemOffset(), true);
2324 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2326 // emit ISD::STORE whichs stores the
2327 // parameter value to a stack Location
2328 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2329 MachinePointerInfo(), false, false, 0));
2332 // Extend range of indices of frame objects for outgoing arguments that were
2333 // created during this function call. Skip this step if no such objects were
2336 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2338 // If a memcpy has been created to copy a byval arg to a stack, replace the
2339 // chain input of CallSeqStart with ByValChain.
2340 if (InChain != ByValChain)
2341 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2342 NextStackOffsetVal);
2344 // Transform all store nodes into one single node because all store
2345 // nodes are independent of each other.
2346 if (!MemOpChains.empty())
2347 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2348 &MemOpChains[0], MemOpChains.size());
2350 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2351 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2352 // node so that legalize doesn't hack it.
2353 unsigned char OpFlag;
2354 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2355 bool GlobalOrExternal = false;
2358 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2359 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2360 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2361 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2362 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2364 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2367 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2368 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2369 getPointerTy(), 0, OpFlag);
2372 GlobalOrExternal = true;
2374 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2375 if (IsN64 || (!IsO32 && IsPIC))
2376 OpFlag = MipsII::MO_GOT_DISP;
2377 else if (!IsPIC) // !N64 && static
2378 OpFlag = MipsII::MO_NO_FLAG;
2380 OpFlag = MipsII::MO_GOT_CALL;
2381 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2383 GlobalOrExternal = true;
2388 // Create nodes that load address of callee and copy it to T9
2390 if (GlobalOrExternal) {
2391 // Load callee address
2392 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(), Callee);
2393 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2394 Callee, MachinePointerInfo::getGOT(),
2395 false, false, false, 0);
2397 // Use GOT+LO if callee has internal linkage.
2398 if (CalleeLo.getNode()) {
2399 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2400 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2406 // T9 should contain the address of the callee function if
2407 // -reloction-model=pic or it is an indirect call.
2408 if (IsPICCall || !GlobalOrExternal) {
2410 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2411 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2412 InFlag = Chain.getValue(1);
2413 Callee = DAG.getRegister(T9Reg, getPointerTy());
2416 // Build a sequence of copy-to-reg nodes chained together with token
2417 // chain and flag operands which copy the outgoing args into registers.
2418 // The InFlag in necessary since all emitted instructions must be
2420 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2421 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2422 RegsToPass[i].second, InFlag);
2423 InFlag = Chain.getValue(1);
2426 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2427 // = Chain, Callee, Reg#1, Reg#2, ...
2429 // Returns a chain & a flag for retval copy to use.
2430 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2431 SmallVector<SDValue, 8> Ops;
2432 Ops.push_back(Chain);
2433 Ops.push_back(Callee);
2435 // Add argument registers to the end of the list so that they are
2436 // known live into the call.
2437 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2438 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2439 RegsToPass[i].second.getValueType()));
2441 if (InFlag.getNode())
2442 Ops.push_back(InFlag);
2444 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2445 InFlag = Chain.getValue(1);
2447 // Create the CALLSEQ_END node.
2448 Chain = DAG.getCALLSEQ_END(Chain,
2449 DAG.getIntPtrConstant(NextStackOffset, true),
2450 DAG.getIntPtrConstant(0, true), InFlag);
2451 InFlag = Chain.getValue(1);
2453 // Handle result values, copying them out of physregs into vregs that we
2455 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2456 Ins, dl, DAG, InVals);
2459 /// LowerCallResult - Lower the result values of a call into the
2460 /// appropriate copies out of appropriate physical registers.
2462 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2463 CallingConv::ID CallConv, bool isVarArg,
2464 const SmallVectorImpl<ISD::InputArg> &Ins,
2465 DebugLoc dl, SelectionDAG &DAG,
2466 SmallVectorImpl<SDValue> &InVals) const {
2467 // Assign locations to each value returned by this call.
2468 SmallVector<CCValAssign, 16> RVLocs;
2469 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2470 getTargetMachine(), RVLocs, *DAG.getContext());
2472 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2474 // Copy all of the result registers out of their specified physreg.
2475 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2476 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2477 RVLocs[i].getValVT(), InFlag).getValue(1);
2478 InFlag = Chain.getValue(2);
2479 InVals.push_back(Chain.getValue(0));
2485 //===----------------------------------------------------------------------===//
2486 // Formal Arguments Calling Convention Implementation
2487 //===----------------------------------------------------------------------===//
2488 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2489 std::vector<SDValue>& OutChains,
2490 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2491 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2492 unsigned LocMem = VA.getLocMemOffset();
2493 unsigned FirstWord = LocMem / 4;
2495 // copy register A0 - A3 to frame object
2496 for (unsigned i = 0; i < NumWords; ++i) {
2497 unsigned CurWord = FirstWord + i;
2498 if (CurWord >= O32IntRegsSize)
2501 unsigned SrcReg = O32IntRegs[CurWord];
2502 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2503 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2504 DAG.getConstant(i * 4, MVT::i32));
2505 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2506 StorePtr, MachinePointerInfo(), false,
2508 OutChains.push_back(Store);
2512 // Create frame object on stack and copy registers used for byval passing to it.
2514 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2515 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2516 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2517 MachineFrameInfo *MFI, bool IsRegLoc,
2518 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2520 const unsigned *Reg = Mips64IntRegs + 8;
2521 int FOOffset; // Frame object offset from virtual frame pointer.
2524 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2525 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2528 FOOffset = VA.getLocMemOffset();
2530 // Create frame object.
2531 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2532 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2533 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2534 InVals.push_back(FIN);
2536 // Copy arg registers.
2537 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2539 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2540 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2541 DAG.getConstant(I * 8, PtrTy));
2542 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2543 StorePtr, MachinePointerInfo(), false,
2545 OutChains.push_back(Store);
2551 /// LowerFormalArguments - transform physical registers into virtual registers
2552 /// and generate load operations for arguments places on the stack.
2554 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2555 CallingConv::ID CallConv,
2557 const SmallVectorImpl<ISD::InputArg> &Ins,
2558 DebugLoc dl, SelectionDAG &DAG,
2559 SmallVectorImpl<SDValue> &InVals)
2561 MachineFunction &MF = DAG.getMachineFunction();
2562 MachineFrameInfo *MFI = MF.getFrameInfo();
2563 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2565 MipsFI->setVarArgsFrameIndex(0);
2567 // Used with vargs to acumulate store chains.
2568 std::vector<SDValue> OutChains;
2570 // Assign locations to all of the incoming arguments.
2571 SmallVector<CCValAssign, 16> ArgLocs;
2572 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2573 getTargetMachine(), ArgLocs, *DAG.getContext());
2576 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2578 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2580 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2582 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2583 CCValAssign &VA = ArgLocs[i];
2584 EVT ValVT = VA.getValVT();
2585 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2586 bool IsRegLoc = VA.isRegLoc();
2588 if (Flags.isByVal()) {
2589 assert(Flags.getByValSize() &&
2590 "ByVal args of size 0 should have been ignored by front-end.");
2592 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2593 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2595 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2596 InVals.push_back(FIN);
2597 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2599 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2600 MFI, IsRegLoc, InVals, MipsFI,
2605 // Arguments stored on registers
2607 EVT RegVT = VA.getLocVT();
2608 unsigned ArgReg = VA.getLocReg();
2609 TargetRegisterClass *RC = 0;
2611 if (RegVT == MVT::i32)
2612 RC = Mips::CPURegsRegisterClass;
2613 else if (RegVT == MVT::i64)
2614 RC = Mips::CPU64RegsRegisterClass;
2615 else if (RegVT == MVT::f32)
2616 RC = Mips::FGR32RegisterClass;
2617 else if (RegVT == MVT::f64)
2618 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2620 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2622 // Transform the arguments stored on
2623 // physical registers into virtual ones
2624 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2625 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2627 // If this is an 8 or 16-bit value, it has been passed promoted
2628 // to 32 bits. Insert an assert[sz]ext to capture this, then
2629 // truncate to the right size.
2630 if (VA.getLocInfo() != CCValAssign::Full) {
2631 unsigned Opcode = 0;
2632 if (VA.getLocInfo() == CCValAssign::SExt)
2633 Opcode = ISD::AssertSext;
2634 else if (VA.getLocInfo() == CCValAssign::ZExt)
2635 Opcode = ISD::AssertZext;
2637 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2638 DAG.getValueType(ValVT));
2639 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2642 // Handle floating point arguments passed in integer registers.
2643 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2644 (RegVT == MVT::i64 && ValVT == MVT::f64))
2645 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2646 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2647 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2648 getNextIntArgReg(ArgReg), RC);
2649 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2650 if (!Subtarget->isLittle())
2651 std::swap(ArgValue, ArgValue2);
2652 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2653 ArgValue, ArgValue2);
2656 InVals.push_back(ArgValue);
2657 } else { // VA.isRegLoc()
2660 assert(VA.isMemLoc());
2662 // The stack pointer offset is relative to the caller stack frame.
2663 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2664 VA.getLocMemOffset(), true);
2666 // Create load nodes to retrieve arguments from the stack
2667 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2668 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2669 MachinePointerInfo::getFixedStack(LastFI),
2670 false, false, false, 0));
2674 // The mips ABIs for returning structs by value requires that we copy
2675 // the sret argument into $v0 for the return. Save the argument into
2676 // a virtual register so that we can access it from the return points.
2677 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2678 unsigned Reg = MipsFI->getSRetReturnReg();
2680 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2681 MipsFI->setSRetReturnReg(Reg);
2683 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2684 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2688 unsigned NumOfRegs = IsO32 ? 4 : 8;
2689 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2690 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2691 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2692 TargetRegisterClass *RC
2693 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2694 unsigned RegSize = RC->getSize();
2695 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2697 // Offset of the first variable argument from stack pointer.
2698 int FirstVaArgOffset;
2700 if (IsO32 || (Idx == NumOfRegs)) {
2702 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2704 FirstVaArgOffset = RegSlotOffset;
2706 // Record the frame index of the first variable argument
2707 // which is a value necessary to VASTART.
2708 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2709 MipsFI->setVarArgsFrameIndex(LastFI);
2711 // Copy the integer registers that have not been used for argument passing
2712 // to the argument register save area. For O32, the save area is allocated
2713 // in the caller's stack frame, while for N32/64, it is allocated in the
2714 // callee's stack frame.
2715 for (int StackOffset = RegSlotOffset;
2716 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2717 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2718 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2719 MVT::getIntegerVT(RegSize * 8));
2720 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2721 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2722 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2723 MachinePointerInfo(), false, false, 0));
2727 MipsFI->setLastInArgFI(LastFI);
2729 // All stores are grouped in one node to allow the matching between
2730 // the size of Ins and InVals. This only happens when on varg functions
2731 if (!OutChains.empty()) {
2732 OutChains.push_back(Chain);
2733 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2734 &OutChains[0], OutChains.size());
2740 //===----------------------------------------------------------------------===//
2741 // Return Value Calling Convention Implementation
2742 //===----------------------------------------------------------------------===//
2745 MipsTargetLowering::LowerReturn(SDValue Chain,
2746 CallingConv::ID CallConv, bool isVarArg,
2747 const SmallVectorImpl<ISD::OutputArg> &Outs,
2748 const SmallVectorImpl<SDValue> &OutVals,
2749 DebugLoc dl, SelectionDAG &DAG) const {
2751 // CCValAssign - represent the assignment of
2752 // the return value to a location
2753 SmallVector<CCValAssign, 16> RVLocs;
2755 // CCState - Info about the registers and stack slot.
2756 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2757 getTargetMachine(), RVLocs, *DAG.getContext());
2759 // Analize return values.
2760 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2762 // If this is the first return lowered for this function, add
2763 // the regs to the liveout set for the function.
2764 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2765 for (unsigned i = 0; i != RVLocs.size(); ++i)
2766 if (RVLocs[i].isRegLoc())
2767 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2772 // Copy the result values into the output registers.
2773 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2774 CCValAssign &VA = RVLocs[i];
2775 assert(VA.isRegLoc() && "Can only return in registers!");
2777 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2779 // guarantee that all emitted copies are
2780 // stuck together, avoiding something bad
2781 Flag = Chain.getValue(1);
2784 // The mips ABIs for returning structs by value requires that we copy
2785 // the sret argument into $v0 for the return. We saved the argument into
2786 // a virtual register in the entry block, so now we copy the value out
2788 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2789 MachineFunction &MF = DAG.getMachineFunction();
2790 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2791 unsigned Reg = MipsFI->getSRetReturnReg();
2794 llvm_unreachable("sret virtual register not created in the entry block");
2795 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2797 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2798 Flag = Chain.getValue(1);
2801 // Return on Mips is always a "jr $ra"
2803 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2804 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2806 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2807 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2810 //===----------------------------------------------------------------------===//
2811 // Mips Inline Assembly Support
2812 //===----------------------------------------------------------------------===//
2814 /// getConstraintType - Given a constraint letter, return the type of
2815 /// constraint it is for this target.
2816 MipsTargetLowering::ConstraintType MipsTargetLowering::
2817 getConstraintType(const std::string &Constraint) const
2819 // Mips specific constrainy
2820 // GCC config/mips/constraints.md
2822 // 'd' : An address register. Equivalent to r
2823 // unless generating MIPS16 code.
2824 // 'y' : Equivalent to r; retained for
2825 // backwards compatibility.
2826 // 'f' : Floating Point registers.
2827 if (Constraint.size() == 1) {
2828 switch (Constraint[0]) {
2833 return C_RegisterClass;
2836 return TargetLowering::getConstraintType(Constraint);
2839 /// Examine constraint type and operand type and determine a weight value.
2840 /// This object must already have been set up with the operand type
2841 /// and the current alternative constraint selected.
2842 TargetLowering::ConstraintWeight
2843 MipsTargetLowering::getSingleConstraintMatchWeight(
2844 AsmOperandInfo &info, const char *constraint) const {
2845 ConstraintWeight weight = CW_Invalid;
2846 Value *CallOperandVal = info.CallOperandVal;
2847 // If we don't have a value, we can't do a match,
2848 // but allow it at the lowest weight.
2849 if (CallOperandVal == NULL)
2851 Type *type = CallOperandVal->getType();
2852 // Look at the constraint type.
2853 switch (*constraint) {
2855 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2859 if (type->isIntegerTy())
2860 weight = CW_Register;
2863 if (type->isFloatTy())
2864 weight = CW_Register;
2870 /// Given a register class constraint, like 'r', if this corresponds directly
2871 /// to an LLVM register class, return a register of 0 and the register class
2873 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2874 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2876 if (Constraint.size() == 1) {
2877 switch (Constraint[0]) {
2878 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2879 case 'y': // Same as 'r'. Exists for compatibility.
2882 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2883 assert(VT == MVT::i64 && "Unexpected type.");
2884 return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
2887 return std::make_pair(0U, Mips::FGR32RegisterClass);
2888 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2889 if (Subtarget->isFP64bit())
2890 return std::make_pair(0U, Mips::FGR64RegisterClass);
2892 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2896 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2900 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2901 // The Mips target isn't yet aware of offsets.
2905 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2906 if (VT != MVT::f32 && VT != MVT::f64)
2908 if (Imm.isNegZero())
2910 return Imm.isZero();
2913 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2915 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2917 return TargetLowering::getJumpTableEncoding();