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::WrapperPIC: return "MipsISD::WrapperPIC";
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);
95 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
98 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
100 // When dealing with single precision only, use libcalls
101 if (!Subtarget->isSingleFloat()) {
103 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
105 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
108 // Load extented operations for i1 types must be promoted
109 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
110 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
111 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
113 // MIPS doesn't have extending float->double load/store
114 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
115 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
117 // Used by legalize types to correctly generate the setcc result.
118 // Without this, every float setcc comes with a AND/OR with the result,
119 // we don't want this, since the fpcmp result goes to a flag register,
120 // which is used implicitly by brcond and select operations.
121 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
123 // Mips Custom Operations
124 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
125 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
126 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
127 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
128 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
129 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
130 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
132 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
133 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
134 setOperationAction(ISD::SELECT, MVT::f32, Custom);
135 setOperationAction(ISD::SELECT, MVT::f64, Custom);
136 setOperationAction(ISD::SELECT, MVT::i32, Custom);
137 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
138 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
139 setOperationAction(ISD::VASTART, MVT::Other, Custom);
141 setOperationAction(ISD::SDIV, MVT::i32, Expand);
142 setOperationAction(ISD::SREM, MVT::i32, Expand);
143 setOperationAction(ISD::UDIV, MVT::i32, Expand);
144 setOperationAction(ISD::UREM, MVT::i32, Expand);
145 setOperationAction(ISD::SDIV, MVT::i64, Expand);
146 setOperationAction(ISD::SREM, MVT::i64, Expand);
147 setOperationAction(ISD::UDIV, MVT::i64, Expand);
148 setOperationAction(ISD::UREM, MVT::i64, Expand);
150 // Operations not directly supported by Mips.
151 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
152 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
153 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
154 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
155 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
156 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
157 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
158 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
159 setOperationAction(ISD::ROTL, MVT::i32, Expand);
160 setOperationAction(ISD::ROTL, MVT::i64, Expand);
162 if (!Subtarget->hasMips32r2())
163 setOperationAction(ISD::ROTR, MVT::i32, Expand);
165 if (!Subtarget->hasMips64r2())
166 setOperationAction(ISD::ROTR, MVT::i64, Expand);
168 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
169 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
170 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
171 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
172 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
173 setOperationAction(ISD::FSIN, MVT::f32, Expand);
174 setOperationAction(ISD::FSIN, MVT::f64, Expand);
175 setOperationAction(ISD::FCOS, MVT::f32, Expand);
176 setOperationAction(ISD::FCOS, MVT::f64, Expand);
177 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
178 setOperationAction(ISD::FPOW, MVT::f32, Expand);
179 setOperationAction(ISD::FPOW, MVT::f64, Expand);
180 setOperationAction(ISD::FLOG, MVT::f32, Expand);
181 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
182 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
183 setOperationAction(ISD::FEXP, MVT::f32, Expand);
184 setOperationAction(ISD::FMA, MVT::f32, Expand);
185 setOperationAction(ISD::FMA, MVT::f64, Expand);
187 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
188 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
190 setOperationAction(ISD::VAARG, MVT::Other, Expand);
191 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
194 // Use the default for now
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
198 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
199 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
201 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
202 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
204 setInsertFencesForAtomic(true);
206 if (Subtarget->isSingleFloat())
207 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
209 if (!Subtarget->hasSEInReg()) {
210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
214 if (!Subtarget->hasBitCount())
215 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
217 if (!Subtarget->hasSwap())
218 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
220 setTargetDAGCombine(ISD::ADDE);
221 setTargetDAGCombine(ISD::SUBE);
222 setTargetDAGCombine(ISD::SDIVREM);
223 setTargetDAGCombine(ISD::UDIVREM);
224 setTargetDAGCombine(ISD::SETCC);
225 setTargetDAGCombine(ISD::AND);
226 setTargetDAGCombine(ISD::OR);
228 setMinFunctionAlignment(2);
230 setStackPointerRegisterToSaveRestore(Mips::SP);
231 computeRegisterProperties();
233 setExceptionPointerRegister(Mips::A0);
234 setExceptionSelectorRegister(Mips::A1);
237 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
238 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
239 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
242 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
247 // Transforms a subgraph in CurDAG if the following pattern is found:
248 // (addc multLo, Lo0), (adde multHi, Hi0),
250 // multHi/Lo: product of multiplication
251 // Lo0: initial value of Lo register
252 // Hi0: initial value of Hi register
253 // Return true if pattern matching was successful.
254 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
255 // ADDENode's second operand must be a flag output of an ADDC node in order
256 // for the matching to be successful.
257 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
259 if (ADDCNode->getOpcode() != ISD::ADDC)
262 SDValue MultHi = ADDENode->getOperand(0);
263 SDValue MultLo = ADDCNode->getOperand(0);
264 SDNode* MultNode = MultHi.getNode();
265 unsigned MultOpc = MultHi.getOpcode();
267 // MultHi and MultLo must be generated by the same node,
268 if (MultLo.getNode() != MultNode)
271 // and it must be a multiplication.
272 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
275 // MultLo amd MultHi must be the first and second output of MultNode
277 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
280 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
281 // of the values of MultNode, in which case MultNode will be removed in later
283 // If there exist users other than ADDENode or ADDCNode, this function returns
284 // here, which will result in MultNode being mapped to a single MULT
285 // instruction node rather than a pair of MULT and MADD instructions being
287 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
290 SDValue Chain = CurDAG->getEntryNode();
291 DebugLoc dl = ADDENode->getDebugLoc();
293 // create MipsMAdd(u) node
294 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
296 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
298 MultNode->getOperand(0),// Factor 0
299 MultNode->getOperand(1),// Factor 1
300 ADDCNode->getOperand(1),// Lo0
301 ADDENode->getOperand(1));// Hi0
303 // create CopyFromReg nodes
304 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
306 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
308 CopyFromLo.getValue(2));
310 // replace uses of adde and addc here
311 if (!SDValue(ADDCNode, 0).use_empty())
312 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
314 if (!SDValue(ADDENode, 0).use_empty())
315 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
321 // Transforms a subgraph in CurDAG if the following pattern is found:
322 // (addc Lo0, multLo), (sube Hi0, multHi),
324 // multHi/Lo: product of multiplication
325 // Lo0: initial value of Lo register
326 // Hi0: initial value of Hi register
327 // Return true if pattern matching was successful.
328 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
329 // SUBENode's second operand must be a flag output of an SUBC node in order
330 // for the matching to be successful.
331 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
333 if (SUBCNode->getOpcode() != ISD::SUBC)
336 SDValue MultHi = SUBENode->getOperand(1);
337 SDValue MultLo = SUBCNode->getOperand(1);
338 SDNode* MultNode = MultHi.getNode();
339 unsigned MultOpc = MultHi.getOpcode();
341 // MultHi and MultLo must be generated by the same node,
342 if (MultLo.getNode() != MultNode)
345 // and it must be a multiplication.
346 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
349 // MultLo amd MultHi must be the first and second output of MultNode
351 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
354 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
355 // of the values of MultNode, in which case MultNode will be removed in later
357 // If there exist users other than SUBENode or SUBCNode, this function returns
358 // here, which will result in MultNode being mapped to a single MULT
359 // instruction node rather than a pair of MULT and MSUB instructions being
361 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
364 SDValue Chain = CurDAG->getEntryNode();
365 DebugLoc dl = SUBENode->getDebugLoc();
367 // create MipsSub(u) node
368 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
370 SDValue MSub = CurDAG->getNode(MultOpc, dl,
372 MultNode->getOperand(0),// Factor 0
373 MultNode->getOperand(1),// Factor 1
374 SUBCNode->getOperand(0),// Lo0
375 SUBENode->getOperand(0));// Hi0
377 // create CopyFromReg nodes
378 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
380 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
382 CopyFromLo.getValue(2));
384 // replace uses of sube and subc here
385 if (!SDValue(SUBCNode, 0).use_empty())
386 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
388 if (!SDValue(SUBENode, 0).use_empty())
389 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
394 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
395 TargetLowering::DAGCombinerInfo &DCI,
396 const MipsSubtarget* Subtarget) {
397 if (DCI.isBeforeLegalize())
400 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
402 return SDValue(N, 0);
407 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
408 TargetLowering::DAGCombinerInfo &DCI,
409 const MipsSubtarget* Subtarget) {
410 if (DCI.isBeforeLegalize())
413 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
415 return SDValue(N, 0);
420 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
421 TargetLowering::DAGCombinerInfo &DCI,
422 const MipsSubtarget* Subtarget) {
423 if (DCI.isBeforeLegalizeOps())
426 EVT Ty = N->getValueType(0);
427 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
428 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
429 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
431 DebugLoc dl = N->getDebugLoc();
433 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
434 N->getOperand(0), N->getOperand(1));
435 SDValue InChain = DAG.getEntryNode();
436 SDValue InGlue = DivRem;
439 if (N->hasAnyUseOfValue(0)) {
440 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
443 InChain = CopyFromLo.getValue(1);
444 InGlue = CopyFromLo.getValue(2);
448 if (N->hasAnyUseOfValue(1)) {
449 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
451 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
457 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
459 default: llvm_unreachable("Unknown fp condition code!");
461 case ISD::SETOEQ: return Mips::FCOND_OEQ;
462 case ISD::SETUNE: return Mips::FCOND_UNE;
464 case ISD::SETOLT: return Mips::FCOND_OLT;
466 case ISD::SETOGT: return Mips::FCOND_OGT;
468 case ISD::SETOLE: return Mips::FCOND_OLE;
470 case ISD::SETOGE: return Mips::FCOND_OGE;
471 case ISD::SETULT: return Mips::FCOND_ULT;
472 case ISD::SETULE: return Mips::FCOND_ULE;
473 case ISD::SETUGT: return Mips::FCOND_UGT;
474 case ISD::SETUGE: return Mips::FCOND_UGE;
475 case ISD::SETUO: return Mips::FCOND_UN;
476 case ISD::SETO: return Mips::FCOND_OR;
478 case ISD::SETONE: return Mips::FCOND_ONE;
479 case ISD::SETUEQ: return Mips::FCOND_UEQ;
484 // Returns true if condition code has to be inverted.
485 static bool InvertFPCondCode(Mips::CondCode CC) {
486 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
489 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
492 assert(false && "Illegal Condition Code");
496 // Creates and returns an FPCmp node from a setcc node.
497 // Returns Op if setcc is not a floating point comparison.
498 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
499 // must be a SETCC node
500 if (Op.getOpcode() != ISD::SETCC)
503 SDValue LHS = Op.getOperand(0);
505 if (!LHS.getValueType().isFloatingPoint())
508 SDValue RHS = Op.getOperand(1);
509 DebugLoc dl = Op.getDebugLoc();
511 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
512 // node if necessary.
513 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
515 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
516 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
519 // Creates and returns a CMovFPT/F node.
520 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
521 SDValue False, DebugLoc DL) {
522 bool invert = InvertFPCondCode((Mips::CondCode)
523 cast<ConstantSDNode>(Cond.getOperand(2))
526 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
527 True.getValueType(), True, False, Cond);
530 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
531 TargetLowering::DAGCombinerInfo &DCI,
532 const MipsSubtarget* Subtarget) {
533 if (DCI.isBeforeLegalizeOps())
536 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
538 if (Cond.getOpcode() != MipsISD::FPCmp)
541 SDValue True = DAG.getConstant(1, MVT::i32);
542 SDValue False = DAG.getConstant(0, MVT::i32);
544 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
547 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
548 TargetLowering::DAGCombinerInfo &DCI,
549 const MipsSubtarget* Subtarget) {
550 // Pattern match EXT.
551 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
552 // => ext $dst, $src, size, pos
553 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
556 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
557 unsigned ShiftRightOpc = ShiftRight.getOpcode();
559 // Op's first operand must be a shift right.
560 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
563 // The second operand of the shift must be an immediate.
565 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
568 uint64_t Pos = CN->getZExtValue();
569 uint64_t SMPos, SMSize;
571 // Op's second operand must be a shifted mask.
572 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
573 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
576 // Return if the shifted mask does not start at bit 0 or the sum of its size
577 // and Pos exceeds the word's size.
578 EVT ValTy = N->getValueType(0);
579 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
582 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
583 ShiftRight.getOperand(0),
584 DAG.getConstant(Pos, MVT::i32),
585 DAG.getConstant(SMSize, MVT::i32));
588 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
589 TargetLowering::DAGCombinerInfo &DCI,
590 const MipsSubtarget* Subtarget) {
591 // Pattern match INS.
592 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
593 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
594 // => ins $dst, $src, size, pos, $src1
595 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
598 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
599 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
602 // See if Op's first operand matches (and $src1 , mask0).
603 if (And0.getOpcode() != ISD::AND)
606 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
607 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
610 // See if Op's second operand matches (and (shl $src, pos), mask1).
611 if (And1.getOpcode() != ISD::AND)
614 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
615 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
618 // The shift masks must have the same position and size.
619 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
622 SDValue Shl = And1.getOperand(0);
623 if (Shl.getOpcode() != ISD::SHL)
626 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
629 unsigned Shamt = CN->getZExtValue();
631 // Return if the shift amount and the first bit position of mask are not the
633 EVT ValTy = N->getValueType(0);
634 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
637 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy,
639 DAG.getConstant(SMPos0, MVT::i32),
640 DAG.getConstant(SMSize0, MVT::i32),
644 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
646 SelectionDAG &DAG = DCI.DAG;
647 unsigned opc = N->getOpcode();
652 return PerformADDECombine(N, DAG, DCI, Subtarget);
654 return PerformSUBECombine(N, DAG, DCI, Subtarget);
657 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
659 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
661 return PerformANDCombine(N, DAG, DCI, Subtarget);
663 return PerformORCombine(N, DAG, DCI, Subtarget);
669 SDValue MipsTargetLowering::
670 LowerOperation(SDValue Op, SelectionDAG &DAG) const
672 switch (Op.getOpcode())
674 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
675 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
676 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
677 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
678 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
679 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
680 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
681 case ISD::SELECT: return LowerSELECT(Op, DAG);
682 case ISD::VASTART: return LowerVASTART(Op, DAG);
683 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
684 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
685 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
686 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
691 //===----------------------------------------------------------------------===//
692 // Lower helper functions
693 //===----------------------------------------------------------------------===//
695 // AddLiveIn - This helper function adds the specified physical register to the
696 // MachineFunction as a live in value. It also creates a corresponding
697 // virtual register for it.
699 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
701 assert(RC->contains(PReg) && "Not the correct regclass!");
702 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
703 MF.getRegInfo().addLiveIn(PReg, VReg);
707 // Get fp branch code (not opcode) from condition code.
708 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
709 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
710 return Mips::BRANCH_T;
712 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
713 return Mips::BRANCH_F;
715 return Mips::BRANCH_INVALID;
719 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
721 const MipsSubtarget* Subtarget,
722 const TargetInstrInfo *TII,
723 bool isFPCmp, unsigned Opc) {
724 // There is no need to expand CMov instructions if target has
725 // conditional moves.
726 if (Subtarget->hasCondMov())
729 // To "insert" a SELECT_CC instruction, we actually have to insert the
730 // diamond control-flow pattern. The incoming instruction knows the
731 // destination vreg to set, the condition code register to branch on, the
732 // true/false values to select between, and a branch opcode to use.
733 const BasicBlock *LLVM_BB = BB->getBasicBlock();
734 MachineFunction::iterator It = BB;
741 // bNE r1, r0, copy1MBB
742 // fallthrough --> copy0MBB
743 MachineBasicBlock *thisMBB = BB;
744 MachineFunction *F = BB->getParent();
745 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
746 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
747 F->insert(It, copy0MBB);
748 F->insert(It, sinkMBB);
750 // Transfer the remainder of BB and its successor edges to sinkMBB.
751 sinkMBB->splice(sinkMBB->begin(), BB,
752 llvm::next(MachineBasicBlock::iterator(MI)),
754 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
756 // Next, add the true and fallthrough blocks as its successors.
757 BB->addSuccessor(copy0MBB);
758 BB->addSuccessor(sinkMBB);
760 // Emit the right instruction according to the type of the operands compared
762 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
764 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
765 .addReg(Mips::ZERO).addMBB(sinkMBB);
769 // # fallthrough to sinkMBB
772 // Update machine-CFG edges
773 BB->addSuccessor(sinkMBB);
776 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
781 BuildMI(*BB, BB->begin(), dl,
782 TII->get(Mips::PHI), MI->getOperand(0).getReg())
783 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
784 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
786 BuildMI(*BB, BB->begin(), dl,
787 TII->get(Mips::PHI), MI->getOperand(0).getReg())
788 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
789 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
791 MI->eraseFromParent(); // The pseudo instruction is gone now.
796 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
797 MachineBasicBlock *BB) const {
798 switch (MI->getOpcode()) {
800 assert(false && "Unexpected instr type to insert");
802 case Mips::ATOMIC_LOAD_ADD_I8:
803 case Mips::ATOMIC_LOAD_ADD_I8_P8:
804 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
805 case Mips::ATOMIC_LOAD_ADD_I16:
806 case Mips::ATOMIC_LOAD_ADD_I16_P8:
807 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
808 case Mips::ATOMIC_LOAD_ADD_I32:
809 case Mips::ATOMIC_LOAD_ADD_I32_P8:
810 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
811 case Mips::ATOMIC_LOAD_ADD_I64:
812 case Mips::ATOMIC_LOAD_ADD_I64_P8:
813 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
815 case Mips::ATOMIC_LOAD_AND_I8:
816 case Mips::ATOMIC_LOAD_AND_I8_P8:
817 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
818 case Mips::ATOMIC_LOAD_AND_I16:
819 case Mips::ATOMIC_LOAD_AND_I16_P8:
820 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
821 case Mips::ATOMIC_LOAD_AND_I32:
822 case Mips::ATOMIC_LOAD_AND_I32_P8:
823 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
824 case Mips::ATOMIC_LOAD_AND_I64:
825 case Mips::ATOMIC_LOAD_AND_I64_P8:
826 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
828 case Mips::ATOMIC_LOAD_OR_I8:
829 case Mips::ATOMIC_LOAD_OR_I8_P8:
830 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
831 case Mips::ATOMIC_LOAD_OR_I16:
832 case Mips::ATOMIC_LOAD_OR_I16_P8:
833 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
834 case Mips::ATOMIC_LOAD_OR_I32:
835 case Mips::ATOMIC_LOAD_OR_I32_P8:
836 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
837 case Mips::ATOMIC_LOAD_OR_I64:
838 case Mips::ATOMIC_LOAD_OR_I64_P8:
839 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
841 case Mips::ATOMIC_LOAD_XOR_I8:
842 case Mips::ATOMIC_LOAD_XOR_I8_P8:
843 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
844 case Mips::ATOMIC_LOAD_XOR_I16:
845 case Mips::ATOMIC_LOAD_XOR_I16_P8:
846 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
847 case Mips::ATOMIC_LOAD_XOR_I32:
848 case Mips::ATOMIC_LOAD_XOR_I32_P8:
849 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
850 case Mips::ATOMIC_LOAD_XOR_I64:
851 case Mips::ATOMIC_LOAD_XOR_I64_P8:
852 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
854 case Mips::ATOMIC_LOAD_NAND_I8:
855 case Mips::ATOMIC_LOAD_NAND_I8_P8:
856 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
857 case Mips::ATOMIC_LOAD_NAND_I16:
858 case Mips::ATOMIC_LOAD_NAND_I16_P8:
859 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
860 case Mips::ATOMIC_LOAD_NAND_I32:
861 case Mips::ATOMIC_LOAD_NAND_I32_P8:
862 return EmitAtomicBinary(MI, BB, 4, 0, true);
863 case Mips::ATOMIC_LOAD_NAND_I64:
864 case Mips::ATOMIC_LOAD_NAND_I64_P8:
865 return EmitAtomicBinary(MI, BB, 8, 0, true);
867 case Mips::ATOMIC_LOAD_SUB_I8:
868 case Mips::ATOMIC_LOAD_SUB_I8_P8:
869 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
870 case Mips::ATOMIC_LOAD_SUB_I16:
871 case Mips::ATOMIC_LOAD_SUB_I16_P8:
872 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
873 case Mips::ATOMIC_LOAD_SUB_I32:
874 case Mips::ATOMIC_LOAD_SUB_I32_P8:
875 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
876 case Mips::ATOMIC_LOAD_SUB_I64:
877 case Mips::ATOMIC_LOAD_SUB_I64_P8:
878 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
880 case Mips::ATOMIC_SWAP_I8:
881 case Mips::ATOMIC_SWAP_I8_P8:
882 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
883 case Mips::ATOMIC_SWAP_I16:
884 case Mips::ATOMIC_SWAP_I16_P8:
885 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
886 case Mips::ATOMIC_SWAP_I32:
887 case Mips::ATOMIC_SWAP_I32_P8:
888 return EmitAtomicBinary(MI, BB, 4, 0);
889 case Mips::ATOMIC_SWAP_I64:
890 case Mips::ATOMIC_SWAP_I64_P8:
891 return EmitAtomicBinary(MI, BB, 8, 0);
893 case Mips::ATOMIC_CMP_SWAP_I8:
894 case Mips::ATOMIC_CMP_SWAP_I8_P8:
895 return EmitAtomicCmpSwapPartword(MI, BB, 1);
896 case Mips::ATOMIC_CMP_SWAP_I16:
897 case Mips::ATOMIC_CMP_SWAP_I16_P8:
898 return EmitAtomicCmpSwapPartword(MI, BB, 2);
899 case Mips::ATOMIC_CMP_SWAP_I32:
900 case Mips::ATOMIC_CMP_SWAP_I32_P8:
901 return EmitAtomicCmpSwap(MI, BB, 4);
902 case Mips::ATOMIC_CMP_SWAP_I64:
903 case Mips::ATOMIC_CMP_SWAP_I64_P8:
904 return EmitAtomicCmpSwap(MI, BB, 8);
908 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
909 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
911 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
912 unsigned Size, unsigned BinOpcode,
914 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
916 MachineFunction *MF = BB->getParent();
917 MachineRegisterInfo &RegInfo = MF->getRegInfo();
918 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
919 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
920 DebugLoc dl = MI->getDebugLoc();
921 unsigned LL, SC, AND, NOR, ZERO, BEQ;
924 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
925 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
932 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
933 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
936 ZERO = Mips::ZERO_64;
940 unsigned OldVal = MI->getOperand(0).getReg();
941 unsigned Ptr = MI->getOperand(1).getReg();
942 unsigned Incr = MI->getOperand(2).getReg();
944 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
945 unsigned AndRes = RegInfo.createVirtualRegister(RC);
946 unsigned Success = RegInfo.createVirtualRegister(RC);
948 // insert new blocks after the current block
949 const BasicBlock *LLVM_BB = BB->getBasicBlock();
950 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
951 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
952 MachineFunction::iterator It = BB;
954 MF->insert(It, loopMBB);
955 MF->insert(It, exitMBB);
957 // Transfer the remainder of BB and its successor edges to exitMBB.
958 exitMBB->splice(exitMBB->begin(), BB,
959 llvm::next(MachineBasicBlock::iterator(MI)),
961 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
965 // fallthrough --> loopMBB
966 BB->addSuccessor(loopMBB);
967 loopMBB->addSuccessor(loopMBB);
968 loopMBB->addSuccessor(exitMBB);
972 // <binop> storeval, oldval, incr
973 // sc success, storeval, 0(ptr)
974 // beq success, $0, loopMBB
976 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
978 // and andres, oldval, incr
979 // nor storeval, $0, andres
980 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
981 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
982 } else if (BinOpcode) {
983 // <binop> storeval, oldval, incr
984 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
988 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
989 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
991 MI->eraseFromParent(); // The instruction is gone now.
997 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
998 MachineBasicBlock *BB,
999 unsigned Size, unsigned BinOpcode,
1001 assert((Size == 1 || Size == 2) &&
1002 "Unsupported size for EmitAtomicBinaryPartial.");
1004 MachineFunction *MF = BB->getParent();
1005 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1006 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1007 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1008 DebugLoc dl = MI->getDebugLoc();
1009 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1010 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1012 unsigned Dest = MI->getOperand(0).getReg();
1013 unsigned Ptr = MI->getOperand(1).getReg();
1014 unsigned Incr = MI->getOperand(2).getReg();
1016 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1017 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1018 unsigned Mask = RegInfo.createVirtualRegister(RC);
1019 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1020 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1021 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1022 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1023 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1024 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1025 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1026 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1027 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1028 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1029 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1030 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1031 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1032 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1033 unsigned Success = RegInfo.createVirtualRegister(RC);
1035 // insert new blocks after the current block
1036 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1037 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1038 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1039 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1040 MachineFunction::iterator It = BB;
1042 MF->insert(It, loopMBB);
1043 MF->insert(It, sinkMBB);
1044 MF->insert(It, exitMBB);
1046 // Transfer the remainder of BB and its successor edges to exitMBB.
1047 exitMBB->splice(exitMBB->begin(), BB,
1048 llvm::next(MachineBasicBlock::iterator(MI)),
1050 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1052 BB->addSuccessor(loopMBB);
1053 loopMBB->addSuccessor(loopMBB);
1054 loopMBB->addSuccessor(sinkMBB);
1055 sinkMBB->addSuccessor(exitMBB);
1058 // addiu masklsb2,$0,-4 # 0xfffffffc
1059 // and alignedaddr,ptr,masklsb2
1060 // andi ptrlsb2,ptr,3
1061 // sll shiftamt,ptrlsb2,3
1062 // ori maskupper,$0,255 # 0xff
1063 // sll mask,maskupper,shiftamt
1064 // nor mask2,$0,mask
1065 // sll incr2,incr,shiftamt
1067 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1068 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1069 .addReg(Mips::ZERO).addImm(-4);
1070 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1071 .addReg(Ptr).addReg(MaskLSB2);
1072 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1073 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1074 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1075 .addReg(Mips::ZERO).addImm(MaskImm);
1076 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1077 .addReg(ShiftAmt).addReg(MaskUpper);
1078 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1079 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1082 // atomic.load.binop
1084 // ll oldval,0(alignedaddr)
1085 // binop binopres,oldval,incr2
1086 // and newval,binopres,mask
1087 // and maskedoldval0,oldval,mask2
1088 // or storeval,maskedoldval0,newval
1089 // sc success,storeval,0(alignedaddr)
1090 // beq success,$0,loopMBB
1094 // ll oldval,0(alignedaddr)
1095 // and newval,incr2,mask
1096 // and maskedoldval0,oldval,mask2
1097 // or storeval,maskedoldval0,newval
1098 // sc success,storeval,0(alignedaddr)
1099 // beq success,$0,loopMBB
1102 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1104 // and andres, oldval, incr2
1105 // nor binopres, $0, andres
1106 // and newval, binopres, mask
1107 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1108 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1109 .addReg(Mips::ZERO).addReg(AndRes);
1110 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1111 } else if (BinOpcode) {
1112 // <binop> binopres, oldval, incr2
1113 // and newval, binopres, mask
1114 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1115 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1116 } else {// atomic.swap
1117 // and newval, incr2, mask
1118 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1121 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1122 .addReg(OldVal).addReg(Mask2);
1123 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1124 .addReg(MaskedOldVal0).addReg(NewVal);
1125 BuildMI(BB, dl, TII->get(SC), Success)
1126 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1127 BuildMI(BB, dl, TII->get(Mips::BEQ))
1128 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1131 // and maskedoldval1,oldval,mask
1132 // srl srlres,maskedoldval1,shiftamt
1133 // sll sllres,srlres,24
1134 // sra dest,sllres,24
1136 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1138 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1139 .addReg(OldVal).addReg(Mask);
1140 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1141 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1142 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1143 .addReg(SrlRes).addImm(ShiftImm);
1144 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1145 .addReg(SllRes).addImm(ShiftImm);
1147 MI->eraseFromParent(); // The instruction is gone now.
1153 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1154 MachineBasicBlock *BB,
1155 unsigned Size) const {
1156 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1158 MachineFunction *MF = BB->getParent();
1159 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1160 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1161 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1162 DebugLoc dl = MI->getDebugLoc();
1163 unsigned LL, SC, ZERO, BNE, BEQ;
1166 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1167 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1173 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1174 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1175 ZERO = Mips::ZERO_64;
1180 unsigned Dest = MI->getOperand(0).getReg();
1181 unsigned Ptr = MI->getOperand(1).getReg();
1182 unsigned OldVal = MI->getOperand(2).getReg();
1183 unsigned NewVal = MI->getOperand(3).getReg();
1185 unsigned Success = RegInfo.createVirtualRegister(RC);
1187 // insert new blocks after the current block
1188 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1189 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1190 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1191 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1192 MachineFunction::iterator It = BB;
1194 MF->insert(It, loop1MBB);
1195 MF->insert(It, loop2MBB);
1196 MF->insert(It, exitMBB);
1198 // Transfer the remainder of BB and its successor edges to exitMBB.
1199 exitMBB->splice(exitMBB->begin(), BB,
1200 llvm::next(MachineBasicBlock::iterator(MI)),
1202 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1206 // fallthrough --> loop1MBB
1207 BB->addSuccessor(loop1MBB);
1208 loop1MBB->addSuccessor(exitMBB);
1209 loop1MBB->addSuccessor(loop2MBB);
1210 loop2MBB->addSuccessor(loop1MBB);
1211 loop2MBB->addSuccessor(exitMBB);
1215 // bne dest, oldval, exitMBB
1217 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1218 BuildMI(BB, dl, TII->get(BNE))
1219 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1222 // sc success, newval, 0(ptr)
1223 // beq success, $0, loop1MBB
1225 BuildMI(BB, dl, TII->get(SC), Success)
1226 .addReg(NewVal).addReg(Ptr).addImm(0);
1227 BuildMI(BB, dl, TII->get(BEQ))
1228 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1230 MI->eraseFromParent(); // The instruction is gone now.
1236 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1237 MachineBasicBlock *BB,
1238 unsigned Size) const {
1239 assert((Size == 1 || Size == 2) &&
1240 "Unsupported size for EmitAtomicCmpSwapPartial.");
1242 MachineFunction *MF = BB->getParent();
1243 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1244 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1245 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1246 DebugLoc dl = MI->getDebugLoc();
1247 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1248 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1250 unsigned Dest = MI->getOperand(0).getReg();
1251 unsigned Ptr = MI->getOperand(1).getReg();
1252 unsigned CmpVal = MI->getOperand(2).getReg();
1253 unsigned NewVal = MI->getOperand(3).getReg();
1255 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1256 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1257 unsigned Mask = RegInfo.createVirtualRegister(RC);
1258 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1259 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1260 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1261 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1262 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1263 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1264 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1266 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1267 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1268 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1269 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1270 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1271 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1272 unsigned Success = RegInfo.createVirtualRegister(RC);
1274 // insert new blocks after the current block
1275 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1276 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1278 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1279 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1280 MachineFunction::iterator It = BB;
1282 MF->insert(It, loop1MBB);
1283 MF->insert(It, loop2MBB);
1284 MF->insert(It, sinkMBB);
1285 MF->insert(It, exitMBB);
1287 // Transfer the remainder of BB and its successor edges to exitMBB.
1288 exitMBB->splice(exitMBB->begin(), BB,
1289 llvm::next(MachineBasicBlock::iterator(MI)),
1291 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1293 BB->addSuccessor(loop1MBB);
1294 loop1MBB->addSuccessor(sinkMBB);
1295 loop1MBB->addSuccessor(loop2MBB);
1296 loop2MBB->addSuccessor(loop1MBB);
1297 loop2MBB->addSuccessor(sinkMBB);
1298 sinkMBB->addSuccessor(exitMBB);
1300 // FIXME: computation of newval2 can be moved to loop2MBB.
1302 // addiu masklsb2,$0,-4 # 0xfffffffc
1303 // and alignedaddr,ptr,masklsb2
1304 // andi ptrlsb2,ptr,3
1305 // sll shiftamt,ptrlsb2,3
1306 // ori maskupper,$0,255 # 0xff
1307 // sll mask,maskupper,shiftamt
1308 // nor mask2,$0,mask
1309 // andi maskedcmpval,cmpval,255
1310 // sll shiftedcmpval,maskedcmpval,shiftamt
1311 // andi maskednewval,newval,255
1312 // sll shiftednewval,maskednewval,shiftamt
1313 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1314 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1315 .addReg(Mips::ZERO).addImm(-4);
1316 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1317 .addReg(Ptr).addReg(MaskLSB2);
1318 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1319 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1320 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1321 .addReg(Mips::ZERO).addImm(MaskImm);
1322 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1323 .addReg(ShiftAmt).addReg(MaskUpper);
1324 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1325 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1326 .addReg(CmpVal).addImm(MaskImm);
1327 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1328 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1329 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1330 .addReg(NewVal).addImm(MaskImm);
1331 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1332 .addReg(ShiftAmt).addReg(MaskedNewVal);
1335 // ll oldval,0(alginedaddr)
1336 // and maskedoldval0,oldval,mask
1337 // bne maskedoldval0,shiftedcmpval,sinkMBB
1339 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1340 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1341 .addReg(OldVal).addReg(Mask);
1342 BuildMI(BB, dl, TII->get(Mips::BNE))
1343 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1346 // and maskedoldval1,oldval,mask2
1347 // or storeval,maskedoldval1,shiftednewval
1348 // sc success,storeval,0(alignedaddr)
1349 // beq success,$0,loop1MBB
1351 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1352 .addReg(OldVal).addReg(Mask2);
1353 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1354 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1355 BuildMI(BB, dl, TII->get(SC), Success)
1356 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1357 BuildMI(BB, dl, TII->get(Mips::BEQ))
1358 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1361 // srl srlres,maskedoldval0,shiftamt
1362 // sll sllres,srlres,24
1363 // sra dest,sllres,24
1365 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1367 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1368 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1369 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1370 .addReg(SrlRes).addImm(ShiftImm);
1371 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1372 .addReg(SllRes).addImm(ShiftImm);
1374 MI->eraseFromParent(); // The instruction is gone now.
1379 //===----------------------------------------------------------------------===//
1380 // Misc Lower Operation implementation
1381 //===----------------------------------------------------------------------===//
1382 SDValue MipsTargetLowering::
1383 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1385 MachineFunction &MF = DAG.getMachineFunction();
1386 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1387 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1389 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1390 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1391 "Cannot lower if the alignment of the allocated space is larger than \
1392 that of the stack.");
1394 SDValue Chain = Op.getOperand(0);
1395 SDValue Size = Op.getOperand(1);
1396 DebugLoc dl = Op.getDebugLoc();
1398 // Get a reference from Mips stack pointer
1399 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1401 // Subtract the dynamic size from the actual stack size to
1402 // obtain the new stack size.
1403 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1405 // The Sub result contains the new stack start address, so it
1406 // must be placed in the stack pointer register.
1407 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1409 // This node always has two return values: a new stack pointer
1410 // value and a chain
1411 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1412 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1413 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1415 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1418 SDValue MipsTargetLowering::
1419 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1421 // The first operand is the chain, the second is the condition, the third is
1422 // the block to branch to if the condition is true.
1423 SDValue Chain = Op.getOperand(0);
1424 SDValue Dest = Op.getOperand(2);
1425 DebugLoc dl = Op.getDebugLoc();
1427 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1429 // Return if flag is not set by a floating point comparison.
1430 if (CondRes.getOpcode() != MipsISD::FPCmp)
1433 SDValue CCNode = CondRes.getOperand(2);
1435 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1436 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1438 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1442 SDValue MipsTargetLowering::
1443 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1445 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1447 // Return if flag is not set by a floating point comparison.
1448 if (Cond.getOpcode() != MipsISD::FPCmp)
1451 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1455 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1456 SelectionDAG &DAG) const {
1457 // FIXME there isn't actually debug info here
1458 DebugLoc dl = Op.getDebugLoc();
1459 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1461 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1462 SDVTList VTs = DAG.getVTList(MVT::i32);
1464 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1466 // %gp_rel relocation
1467 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1468 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1470 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1471 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1472 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1474 // %hi/%lo relocation
1475 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1477 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1479 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1480 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1481 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1484 EVT ValTy = Op.getValueType();
1485 bool HasGotOfst = (GV->hasInternalLinkage() ||
1486 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1487 unsigned GotFlag = IsN64 ?
1488 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1489 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1490 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1491 GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1492 SDValue ResNode = DAG.getLoad(ValTy, dl,
1493 DAG.getEntryNode(), GA, MachinePointerInfo(),
1494 false, false, false, 0);
1495 // On functions and global targets not internal linked only
1496 // a load from got/GP is necessary for PIC to work.
1499 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1500 IsN64 ? MipsII::MO_GOT_OFST :
1502 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1503 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1506 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1507 SelectionDAG &DAG) const {
1508 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1509 // FIXME there isn't actually debug info here
1510 DebugLoc dl = Op.getDebugLoc();
1512 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1513 // %hi/%lo relocation
1514 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1516 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1518 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1519 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1520 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1523 EVT ValTy = Op.getValueType();
1524 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1525 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1526 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1527 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, BAGOTOffset);
1528 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1529 SDValue Load = DAG.getLoad(ValTy, dl,
1530 DAG.getEntryNode(), BAGOTOffset,
1531 MachinePointerInfo(), false, false, false, 0);
1532 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1533 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1536 SDValue MipsTargetLowering::
1537 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1539 // If the relocation model is PIC, use the General Dynamic TLS Model,
1540 // otherwise use the Initial Exec or Local Exec TLS Model.
1541 // TODO: implement Local Dynamic TLS model
1543 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1544 DebugLoc dl = GA->getDebugLoc();
1545 const GlobalValue *GV = GA->getGlobal();
1546 EVT PtrVT = getPointerTy();
1548 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1549 // General Dynamic TLS Model
1550 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT,
1551 0, MipsII::MO_TLSGD);
1552 SDValue Argument = DAG.getNode(MipsISD::WrapperPIC, dl, PtrVT, TGA);
1553 unsigned PtrSize = PtrVT.getSizeInBits();
1554 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1556 SmallVector<Type*, 1> Params;
1557 Params.push_back(PtrTy);
1558 FunctionType *FuncTy = FunctionType::get(PtrTy, Params, false);
1559 Function *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage,
1561 SDValue TlsGetAddr = DAG.getGlobalAddress(Func, dl, PtrVT);
1565 Entry.Node = Argument;
1567 Args.push_back(Entry);
1569 std::pair<SDValue, SDValue> CallResult =
1570 LowerCallTo(DAG.getEntryNode(), PtrTy,
1571 false, false, false, false, 0, CallingConv::C, false, true,
1572 TlsGetAddr, Args, DAG, dl);
1574 return CallResult.first;
1578 if (GV->isDeclaration()) {
1579 // Initial Exec TLS Model
1580 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1581 MipsII::MO_GOTTPREL);
1582 TGA = DAG.getNode(MipsISD::WrapperPIC, dl, PtrVT, TGA);
1583 Offset = DAG.getLoad(PtrVT, dl,
1584 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1585 false, false, false, 0);
1587 // Local Exec TLS Model
1588 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1589 MipsII::MO_TPREL_HI);
1590 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1591 MipsII::MO_TPREL_LO);
1592 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1593 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1594 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1597 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1598 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1601 SDValue MipsTargetLowering::
1602 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1604 SDValue HiPart, JTI, JTILo;
1605 // FIXME there isn't actually debug info here
1606 DebugLoc dl = Op.getDebugLoc();
1607 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1608 EVT PtrVT = Op.getValueType();
1609 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1611 if (!IsPIC && !IsN64) {
1612 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1613 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1614 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1615 } else {// Emit Load from Global Pointer
1616 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1617 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1618 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1619 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, PtrVT, JTI);
1620 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1621 MachinePointerInfo(), false, false, false, 0);
1622 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1625 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1626 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1629 SDValue MipsTargetLowering::
1630 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1633 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1634 const Constant *C = N->getConstVal();
1635 // FIXME there isn't actually debug info here
1636 DebugLoc dl = Op.getDebugLoc();
1638 // gp_rel relocation
1639 // FIXME: we should reference the constant pool using small data sections,
1640 // but the asm printer currently doesn't support this feature without
1641 // hacking it. This feature should come soon so we can uncomment the
1643 //if (IsInSmallSection(C->getType())) {
1644 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1645 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1646 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1648 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1649 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1650 N->getOffset(), MipsII::MO_ABS_HI);
1651 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1652 N->getOffset(), MipsII::MO_ABS_LO);
1653 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1654 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1655 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1657 EVT ValTy = Op.getValueType();
1658 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1659 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1660 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1661 N->getOffset(), GOTFlag);
1662 CP = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, CP);
1663 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(),
1664 CP, MachinePointerInfo::getConstantPool(),
1665 false, false, false, 0);
1666 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1667 N->getOffset(), OFSTFlag);
1668 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1669 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1675 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1676 MachineFunction &MF = DAG.getMachineFunction();
1677 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1679 DebugLoc dl = Op.getDebugLoc();
1680 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1683 // vastart just stores the address of the VarArgsFrameIndex slot into the
1684 // memory location argument.
1685 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1686 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1687 MachinePointerInfo(SV),
1691 // Called if the size of integer registers is large enough to hold the whole
1692 // floating point number.
1693 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1694 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1695 EVT ValTy = Op.getValueType();
1696 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1697 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1698 DebugLoc dl = Op.getDebugLoc();
1699 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1700 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1701 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1702 DAG.getConstant(Mask - 1, IntValTy));
1703 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1704 DAG.getConstant(Mask, IntValTy));
1705 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1706 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1709 // Called if the size of integer registers is not large enough to hold the whole
1710 // floating point number (e.g. f64 & 32-bit integer register).
1712 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1714 // Use ext/ins instructions if target architecture is Mips32r2.
1715 // Eliminate redundant mfc1 and mtc1 instructions.
1716 unsigned LoIdx = 0, HiIdx = 1;
1719 std::swap(LoIdx, HiIdx);
1721 DebugLoc dl = Op.getDebugLoc();
1722 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1724 DAG.getConstant(LoIdx, MVT::i32));
1725 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1726 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1727 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1728 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1729 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1730 DAG.getConstant(0x7fffffff, MVT::i32));
1731 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1732 DAG.getConstant(0x80000000, MVT::i32));
1733 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1736 std::swap(Word0, Word1);
1738 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1741 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1743 EVT Ty = Op.getValueType();
1745 assert(Ty == MVT::f32 || Ty == MVT::f64);
1747 if (Ty == MVT::f32 || HasMips64)
1748 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1750 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1753 SDValue MipsTargetLowering::
1754 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1756 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1757 "Frame address can only be determined for current frame.");
1759 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1760 MFI->setFrameAddressIsTaken(true);
1761 EVT VT = Op.getValueType();
1762 DebugLoc dl = Op.getDebugLoc();
1763 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1764 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1768 // TODO: set SType according to the desired memory barrier behavior.
1769 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1770 SelectionDAG& DAG) const {
1772 DebugLoc dl = Op.getDebugLoc();
1773 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1774 DAG.getConstant(SType, MVT::i32));
1777 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1778 SelectionDAG& DAG) const {
1779 // FIXME: Need pseudo-fence for 'singlethread' fences
1780 // FIXME: Set SType for weaker fences where supported/appropriate.
1782 DebugLoc dl = Op.getDebugLoc();
1783 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1784 DAG.getConstant(SType, MVT::i32));
1787 //===----------------------------------------------------------------------===//
1788 // Calling Convention Implementation
1789 //===----------------------------------------------------------------------===//
1791 //===----------------------------------------------------------------------===//
1792 // TODO: Implement a generic logic using tblgen that can support this.
1793 // Mips O32 ABI rules:
1795 // i32 - Passed in A0, A1, A2, A3 and stack
1796 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1797 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1798 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1799 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1800 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1803 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1804 //===----------------------------------------------------------------------===//
1806 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1807 MVT LocVT, CCValAssign::LocInfo LocInfo,
1808 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1810 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1812 static const unsigned IntRegs[] = {
1813 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1815 static const unsigned F32Regs[] = {
1816 Mips::F12, Mips::F14
1818 static const unsigned F64Regs[] = {
1823 if (ArgFlags.isByVal()) {
1824 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1825 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1826 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1827 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1828 r < std::min(IntRegsSize, NextReg); ++r)
1829 State.AllocateReg(IntRegs[r]);
1833 // Promote i8 and i16
1834 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1836 if (ArgFlags.isSExt())
1837 LocInfo = CCValAssign::SExt;
1838 else if (ArgFlags.isZExt())
1839 LocInfo = CCValAssign::ZExt;
1841 LocInfo = CCValAssign::AExt;
1846 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1847 // is true: function is vararg, argument is 3rd or higher, there is previous
1848 // argument which is not f32 or f64.
1849 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1850 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1851 unsigned OrigAlign = ArgFlags.getOrigAlign();
1852 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1854 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1855 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1856 // If this is the first part of an i64 arg,
1857 // the allocated register must be either A0 or A2.
1858 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1859 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1861 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1862 // Allocate int register and shadow next int register. If first
1863 // available register is Mips::A1 or Mips::A3, shadow it too.
1864 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1865 if (Reg == Mips::A1 || Reg == Mips::A3)
1866 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1867 State.AllocateReg(IntRegs, IntRegsSize);
1869 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1870 // we are guaranteed to find an available float register
1871 if (ValVT == MVT::f32) {
1872 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1873 // Shadow int register
1874 State.AllocateReg(IntRegs, IntRegsSize);
1876 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1877 // Shadow int registers
1878 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1879 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1880 State.AllocateReg(IntRegs, IntRegsSize);
1881 State.AllocateReg(IntRegs, IntRegsSize);
1884 llvm_unreachable("Cannot handle this ValVT.");
1886 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1887 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1890 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1892 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1894 return false; // CC must always match
1897 static const unsigned Mips64IntRegs[8] =
1898 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1899 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1900 static const unsigned Mips64DPRegs[8] =
1901 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1902 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1904 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1905 CCValAssign::LocInfo LocInfo,
1906 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1907 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1908 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1909 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1911 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1913 // If byval is 16-byte aligned, the first arg register must be even.
1914 if ((Align == 16) && (FirstIdx % 2)) {
1915 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1919 // Mark the registers allocated.
1920 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1921 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1923 // Allocate space on caller's stack.
1924 unsigned Offset = State.AllocateStack(Size, Align);
1927 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1930 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1935 #include "MipsGenCallingConv.inc"
1938 AnalyzeMips64CallOperands(CCState CCInfo,
1939 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1940 unsigned NumOps = Outs.size();
1941 for (unsigned i = 0; i != NumOps; ++i) {
1942 MVT ArgVT = Outs[i].VT;
1943 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1946 if (Outs[i].IsFixed)
1947 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1949 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1953 dbgs() << "Call operand #" << i << " has unhandled type "
1954 << EVT(ArgVT).getEVTString();
1956 llvm_unreachable(0);
1961 //===----------------------------------------------------------------------===//
1962 // Call Calling Convention Implementation
1963 //===----------------------------------------------------------------------===//
1965 static const unsigned O32IntRegsSize = 4;
1967 static const unsigned O32IntRegs[] = {
1968 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1971 // Return next O32 integer argument register.
1972 static unsigned getNextIntArgReg(unsigned Reg) {
1973 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1974 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1977 // Write ByVal Arg to arg registers and stack.
1979 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1980 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1981 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1982 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1983 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1984 MVT PtrType, bool isLittle) {
1985 unsigned LocMemOffset = VA.getLocMemOffset();
1986 unsigned Offset = 0;
1987 uint32_t RemainingSize = Flags.getByValSize();
1988 unsigned ByValAlign = Flags.getByValAlign();
1990 // Copy the first 4 words of byval arg to registers A0 - A3.
1991 // FIXME: Use a stricter alignment if it enables better optimization in passes
1993 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1994 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1995 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1996 DAG.getConstant(Offset, MVT::i32));
1997 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1998 MachinePointerInfo(),
1999 false, false, false, std::min(ByValAlign,
2001 MemOpChains.push_back(LoadVal.getValue(1));
2002 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2003 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2006 if (RemainingSize == 0)
2009 // If there still is a register available for argument passing, write the
2010 // remaining part of the structure to it using subword loads and shifts.
2011 if (LocMemOffset < 4 * 4) {
2012 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2013 "There must be one to three bytes remaining.");
2014 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2015 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2016 DAG.getConstant(Offset, MVT::i32));
2017 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2018 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2019 LoadPtr, MachinePointerInfo(),
2020 MVT::getIntegerVT(LoadSize * 8), false,
2022 MemOpChains.push_back(LoadVal.getValue(1));
2024 // If target is big endian, shift it to the most significant half-word or
2027 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2028 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2031 RemainingSize -= LoadSize;
2033 // Read second subword if necessary.
2034 if (RemainingSize != 0) {
2035 assert(RemainingSize == 1 && "There must be one byte remaining.");
2036 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2037 DAG.getConstant(Offset, MVT::i32));
2038 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2039 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2040 LoadPtr, MachinePointerInfo(),
2041 MVT::i8, false, false, Alignment);
2042 MemOpChains.push_back(Subword.getValue(1));
2043 // Insert the loaded byte to LoadVal.
2044 // FIXME: Use INS if supported by target.
2045 unsigned ShiftAmt = isLittle ? 16 : 8;
2046 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2047 DAG.getConstant(ShiftAmt, MVT::i32));
2048 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2051 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2052 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2056 // Create a fixed object on stack at offset LocMemOffset and copy
2057 // remaining part of byval arg to it using memcpy.
2058 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2059 DAG.getConstant(Offset, MVT::i32));
2060 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2061 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2062 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2063 DAG.getConstant(RemainingSize, MVT::i32),
2064 std::min(ByValAlign, (unsigned)4),
2065 /*isVolatile=*/false, /*AlwaysInline=*/false,
2066 MachinePointerInfo(0), MachinePointerInfo(0));
2069 // Copy Mips64 byVal arg to registers and stack.
2071 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2072 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2073 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2074 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2075 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2076 EVT PtrTy, bool isLittle) {
2077 unsigned ByValSize = Flags.getByValSize();
2078 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2079 bool IsRegLoc = VA.isRegLoc();
2080 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2081 unsigned LocMemOffset = 0;
2082 unsigned MemCpySize = ByValSize;
2085 LocMemOffset = VA.getLocMemOffset();
2087 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2089 const unsigned *RegEnd = Mips64IntRegs + 8;
2091 // Copy double words to registers.
2092 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2093 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2094 DAG.getConstant(Offset, PtrTy));
2095 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2096 MachinePointerInfo(), false, false, false,
2098 MemOpChains.push_back(LoadVal.getValue(1));
2099 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2102 // Return if the struct has been fully copied.
2103 if (!(MemCpySize = ByValSize - Offset))
2106 // If there is an argument register available, copy the remainder of the
2107 // byval argument with sub-doubleword loads and shifts.
2108 if (Reg != RegEnd) {
2109 assert((ByValSize < Offset + 8) &&
2110 "Size of the remainder should be smaller than 8-byte.");
2112 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2113 unsigned RemSize = ByValSize - Offset;
2115 if (RemSize < LoadSize)
2118 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2119 DAG.getConstant(Offset, PtrTy));
2121 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2122 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2123 false, false, Alignment);
2124 MemOpChains.push_back(LoadVal.getValue(1));
2126 // Offset in number of bits from double word boundary.
2127 unsigned OffsetDW = (Offset % 8) * 8;
2128 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2129 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2130 DAG.getConstant(Shamt, MVT::i32));
2132 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2135 Alignment = std::min(Alignment, LoadSize);
2138 RegsToPass.push_back(std::make_pair(*Reg, Val));
2143 assert(MemCpySize && "MemCpySize must not be zero.");
2145 // Create a fixed object on stack at offset LocMemOffset and copy
2146 // remainder of byval arg to it with memcpy.
2147 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2148 DAG.getConstant(Offset, PtrTy));
2149 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2150 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2151 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2152 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2153 /*isVolatile=*/false, /*AlwaysInline=*/false,
2154 MachinePointerInfo(0), MachinePointerInfo(0));
2157 /// LowerCall - functions arguments are copied from virtual regs to
2158 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2159 /// TODO: isTailCall.
2161 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2162 CallingConv::ID CallConv, bool isVarArg,
2164 const SmallVectorImpl<ISD::OutputArg> &Outs,
2165 const SmallVectorImpl<SDValue> &OutVals,
2166 const SmallVectorImpl<ISD::InputArg> &Ins,
2167 DebugLoc dl, SelectionDAG &DAG,
2168 SmallVectorImpl<SDValue> &InVals) const {
2169 // MIPs target does not yet support tail call optimization.
2172 MachineFunction &MF = DAG.getMachineFunction();
2173 MachineFrameInfo *MFI = MF.getFrameInfo();
2174 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2175 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2176 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2178 // Analyze operands of the call, assigning locations to each operand.
2179 SmallVector<CCValAssign, 16> ArgLocs;
2180 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2181 getTargetMachine(), ArgLocs, *DAG.getContext());
2184 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2186 AnalyzeMips64CallOperands(CCInfo, Outs);
2188 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2190 // Get a count of how many bytes are to be pushed on the stack.
2191 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2193 // Chain is the output chain of the last Load/Store or CopyToReg node.
2194 // ByValChain is the output chain of the last Memcpy node created for copying
2195 // byval arguments to the stack.
2196 SDValue Chain, CallSeqStart, ByValChain;
2197 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2198 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2199 ByValChain = InChain;
2201 // If this is the first call, create a stack frame object that points to
2202 // a location to which .cprestore saves $gp.
2203 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2204 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2206 // Get the frame index of the stack frame object that points to the location
2207 // of dynamically allocated area on the stack.
2208 int DynAllocFI = MipsFI->getDynAllocFI();
2210 // Update size of the maximum argument space.
2211 // For O32, a minimum of four words (16 bytes) of argument space is
2214 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2216 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2218 if (MaxCallFrameSize < NextStackOffset) {
2219 MipsFI->setMaxCallFrameSize(NextStackOffset);
2221 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2222 // allocated stack space. These offsets must be aligned to a boundary
2223 // determined by the stack alignment of the ABI.
2224 unsigned StackAlignment = TFL->getStackAlignment();
2225 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2226 StackAlignment * StackAlignment;
2228 if (MipsFI->needGPSaveRestore())
2229 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2231 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2234 // With EABI is it possible to have 16 args on registers.
2235 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2236 SmallVector<SDValue, 8> MemOpChains;
2238 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2240 // Walk the register/memloc assignments, inserting copies/loads.
2241 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2242 SDValue Arg = OutVals[i];
2243 CCValAssign &VA = ArgLocs[i];
2244 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2245 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2248 if (Flags.isByVal()) {
2249 assert(Flags.getByValSize() &&
2250 "ByVal args of size 0 should have been ignored by front-end.");
2252 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2253 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2254 Subtarget->isLittle());
2256 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2257 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2258 Subtarget->isLittle());
2262 // Promote the value if needed.
2263 switch (VA.getLocInfo()) {
2264 default: llvm_unreachable("Unknown loc info!");
2265 case CCValAssign::Full:
2266 if (VA.isRegLoc()) {
2267 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2268 (ValVT == MVT::f64 && LocVT == MVT::i64))
2269 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2270 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2271 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2272 Arg, DAG.getConstant(0, MVT::i32));
2273 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2274 Arg, DAG.getConstant(1, MVT::i32));
2275 if (!Subtarget->isLittle())
2277 unsigned LocRegLo = VA.getLocReg();
2278 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2279 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2280 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2285 case CCValAssign::SExt:
2286 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2288 case CCValAssign::ZExt:
2289 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2291 case CCValAssign::AExt:
2292 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2296 // Arguments that can be passed on register must be kept at
2297 // RegsToPass vector
2298 if (VA.isRegLoc()) {
2299 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2303 // Register can't get to this point...
2304 assert(VA.isMemLoc());
2306 // Create the frame index object for this incoming parameter
2307 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2308 VA.getLocMemOffset(), true);
2309 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2311 // emit ISD::STORE whichs stores the
2312 // parameter value to a stack Location
2313 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2314 MachinePointerInfo(),
2318 // Extend range of indices of frame objects for outgoing arguments that were
2319 // created during this function call. Skip this step if no such objects were
2322 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2324 // If a memcpy has been created to copy a byval arg to a stack, replace the
2325 // chain input of CallSeqStart with ByValChain.
2326 if (InChain != ByValChain)
2327 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2328 NextStackOffsetVal);
2330 // Transform all store nodes into one single node because all store
2331 // nodes are independent of each other.
2332 if (!MemOpChains.empty())
2333 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2334 &MemOpChains[0], MemOpChains.size());
2336 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2337 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2338 // node so that legalize doesn't hack it.
2339 unsigned char OpFlag;
2340 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2341 bool LoadSymAddr = false;
2344 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2345 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2346 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2347 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2348 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2350 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2353 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2354 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2355 getPointerTy(), 0, OpFlag);
2360 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2361 if (IsN64 || (!IsO32 && IsPIC))
2362 OpFlag = MipsII::MO_GOT_DISP;
2363 else if (!IsPIC) // !N64 && static
2364 OpFlag = MipsII::MO_NO_FLAG;
2366 OpFlag = MipsII::MO_GOT_CALL;
2367 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2368 getPointerTy(), OpFlag);
2374 // Create nodes that load address of callee and copy it to T9
2377 // Load callee address
2378 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, getPointerTy(), Callee);
2379 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2380 Callee, MachinePointerInfo::getGOT(),
2381 false, false, false, 0);
2383 // Use GOT+LO if callee has internal linkage.
2384 if (CalleeLo.getNode()) {
2385 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2386 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2392 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2393 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2394 InFlag = Chain.getValue(1);
2395 Callee = DAG.getRegister(T9Reg, getPointerTy());
2398 // Build a sequence of copy-to-reg nodes chained together with token
2399 // chain and flag operands which copy the outgoing args into registers.
2400 // The InFlag in necessary since all emitted instructions must be
2402 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2403 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2404 RegsToPass[i].second, InFlag);
2405 InFlag = Chain.getValue(1);
2408 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2409 // = Chain, Callee, Reg#1, Reg#2, ...
2411 // Returns a chain & a flag for retval copy to use.
2412 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2413 SmallVector<SDValue, 8> Ops;
2414 Ops.push_back(Chain);
2415 Ops.push_back(Callee);
2417 // Add argument registers to the end of the list so that they are
2418 // known live into the call.
2419 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2420 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2421 RegsToPass[i].second.getValueType()));
2423 if (InFlag.getNode())
2424 Ops.push_back(InFlag);
2426 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2427 InFlag = Chain.getValue(1);
2429 // Create the CALLSEQ_END node.
2430 Chain = DAG.getCALLSEQ_END(Chain,
2431 DAG.getIntPtrConstant(NextStackOffset, true),
2432 DAG.getIntPtrConstant(0, true), InFlag);
2433 InFlag = Chain.getValue(1);
2435 // Handle result values, copying them out of physregs into vregs that we
2437 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2438 Ins, dl, DAG, InVals);
2441 /// LowerCallResult - Lower the result values of a call into the
2442 /// appropriate copies out of appropriate physical registers.
2444 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2445 CallingConv::ID CallConv, bool isVarArg,
2446 const SmallVectorImpl<ISD::InputArg> &Ins,
2447 DebugLoc dl, SelectionDAG &DAG,
2448 SmallVectorImpl<SDValue> &InVals) const {
2449 // Assign locations to each value returned by this call.
2450 SmallVector<CCValAssign, 16> RVLocs;
2451 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2452 getTargetMachine(), RVLocs, *DAG.getContext());
2454 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2456 // Copy all of the result registers out of their specified physreg.
2457 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2458 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2459 RVLocs[i].getValVT(), InFlag).getValue(1);
2460 InFlag = Chain.getValue(2);
2461 InVals.push_back(Chain.getValue(0));
2467 //===----------------------------------------------------------------------===//
2468 // Formal Arguments Calling Convention Implementation
2469 //===----------------------------------------------------------------------===//
2470 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2471 std::vector<SDValue>& OutChains,
2472 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2473 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2474 unsigned LocMem = VA.getLocMemOffset();
2475 unsigned FirstWord = LocMem / 4;
2477 // copy register A0 - A3 to frame object
2478 for (unsigned i = 0; i < NumWords; ++i) {
2479 unsigned CurWord = FirstWord + i;
2480 if (CurWord >= O32IntRegsSize)
2483 unsigned SrcReg = O32IntRegs[CurWord];
2484 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2485 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2486 DAG.getConstant(i * 4, MVT::i32));
2487 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2488 StorePtr, MachinePointerInfo(), false,
2490 OutChains.push_back(Store);
2494 // Create frame object on stack and copy registers used for byval passing to it.
2496 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2497 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2498 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2499 MachineFrameInfo *MFI, bool IsRegLoc,
2500 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2502 const unsigned *Reg = Mips64IntRegs + 8;
2503 int FOOffset; // Frame object offset from virtual frame pointer.
2506 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2507 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2510 FOOffset = VA.getLocMemOffset();
2512 // Create frame object.
2513 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2514 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2515 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2516 InVals.push_back(FIN);
2518 // Copy arg registers.
2519 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2521 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2522 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2523 DAG.getConstant(I * 8, PtrTy));
2524 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2525 StorePtr, MachinePointerInfo(), false,
2527 OutChains.push_back(Store);
2533 /// LowerFormalArguments - transform physical registers into virtual registers
2534 /// and generate load operations for arguments places on the stack.
2536 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2537 CallingConv::ID CallConv,
2539 const SmallVectorImpl<ISD::InputArg>
2541 DebugLoc dl, SelectionDAG &DAG,
2542 SmallVectorImpl<SDValue> &InVals)
2544 MachineFunction &MF = DAG.getMachineFunction();
2545 MachineFrameInfo *MFI = MF.getFrameInfo();
2546 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2548 MipsFI->setVarArgsFrameIndex(0);
2550 // Used with vargs to acumulate store chains.
2551 std::vector<SDValue> OutChains;
2553 // Assign locations to all of the incoming arguments.
2554 SmallVector<CCValAssign, 16> ArgLocs;
2555 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2556 getTargetMachine(), ArgLocs, *DAG.getContext());
2559 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2561 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2563 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2565 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2566 CCValAssign &VA = ArgLocs[i];
2567 EVT ValVT = VA.getValVT();
2568 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2569 bool IsRegLoc = VA.isRegLoc();
2571 if (Flags.isByVal()) {
2572 assert(Flags.getByValSize() &&
2573 "ByVal args of size 0 should have been ignored by front-end.");
2575 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2576 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2578 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2579 InVals.push_back(FIN);
2580 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2582 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2583 MFI, IsRegLoc, InVals, MipsFI,
2588 // Arguments stored on registers
2590 EVT RegVT = VA.getLocVT();
2591 unsigned ArgReg = VA.getLocReg();
2592 TargetRegisterClass *RC = 0;
2594 if (RegVT == MVT::i32)
2595 RC = Mips::CPURegsRegisterClass;
2596 else if (RegVT == MVT::i64)
2597 RC = Mips::CPU64RegsRegisterClass;
2598 else if (RegVT == MVT::f32)
2599 RC = Mips::FGR32RegisterClass;
2600 else if (RegVT == MVT::f64)
2601 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2603 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2605 // Transform the arguments stored on
2606 // physical registers into virtual ones
2607 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2608 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2610 // If this is an 8 or 16-bit value, it has been passed promoted
2611 // to 32 bits. Insert an assert[sz]ext to capture this, then
2612 // truncate to the right size.
2613 if (VA.getLocInfo() != CCValAssign::Full) {
2614 unsigned Opcode = 0;
2615 if (VA.getLocInfo() == CCValAssign::SExt)
2616 Opcode = ISD::AssertSext;
2617 else if (VA.getLocInfo() == CCValAssign::ZExt)
2618 Opcode = ISD::AssertZext;
2620 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2621 DAG.getValueType(ValVT));
2622 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2625 // Handle floating point arguments passed in integer registers.
2626 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2627 (RegVT == MVT::i64 && ValVT == MVT::f64))
2628 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2629 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2630 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2631 getNextIntArgReg(ArgReg), RC);
2632 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2633 if (!Subtarget->isLittle())
2634 std::swap(ArgValue, ArgValue2);
2635 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2636 ArgValue, ArgValue2);
2639 InVals.push_back(ArgValue);
2640 } else { // VA.isRegLoc()
2643 assert(VA.isMemLoc());
2645 // The stack pointer offset is relative to the caller stack frame.
2646 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2647 VA.getLocMemOffset(), true);
2649 // Create load nodes to retrieve arguments from the stack
2650 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2651 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2652 MachinePointerInfo::getFixedStack(LastFI),
2653 false, false, false, 0));
2657 // The mips ABIs for returning structs by value requires that we copy
2658 // the sret argument into $v0 for the return. Save the argument into
2659 // a virtual register so that we can access it from the return points.
2660 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2661 unsigned Reg = MipsFI->getSRetReturnReg();
2663 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2664 MipsFI->setSRetReturnReg(Reg);
2666 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2667 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2671 unsigned NumOfRegs = IsO32 ? 4 : 8;
2672 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2673 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2674 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2675 TargetRegisterClass *RC
2676 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2677 unsigned RegSize = RC->getSize();
2678 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2680 // Offset of the first variable argument from stack pointer.
2681 int FirstVaArgOffset;
2683 if (IsO32 || (Idx == NumOfRegs)) {
2685 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2687 FirstVaArgOffset = RegSlotOffset;
2689 // Record the frame index of the first variable argument
2690 // which is a value necessary to VASTART.
2691 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2692 MipsFI->setVarArgsFrameIndex(LastFI);
2694 // Copy the integer registers that have not been used for argument passing
2695 // to the argument register save area. For O32, the save area is allocated
2696 // in the caller's stack frame, while for N32/64, it is allocated in the
2697 // callee's stack frame.
2698 for (int StackOffset = RegSlotOffset;
2699 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2700 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2701 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2702 MVT::getIntegerVT(RegSize * 8));
2703 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2704 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2705 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2706 MachinePointerInfo(),
2711 MipsFI->setLastInArgFI(LastFI);
2713 // All stores are grouped in one node to allow the matching between
2714 // the size of Ins and InVals. This only happens when on varg functions
2715 if (!OutChains.empty()) {
2716 OutChains.push_back(Chain);
2717 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2718 &OutChains[0], OutChains.size());
2724 //===----------------------------------------------------------------------===//
2725 // Return Value Calling Convention Implementation
2726 //===----------------------------------------------------------------------===//
2729 MipsTargetLowering::LowerReturn(SDValue Chain,
2730 CallingConv::ID CallConv, bool isVarArg,
2731 const SmallVectorImpl<ISD::OutputArg> &Outs,
2732 const SmallVectorImpl<SDValue> &OutVals,
2733 DebugLoc dl, SelectionDAG &DAG) const {
2735 // CCValAssign - represent the assignment of
2736 // the return value to a location
2737 SmallVector<CCValAssign, 16> RVLocs;
2739 // CCState - Info about the registers and stack slot.
2740 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2741 getTargetMachine(), RVLocs, *DAG.getContext());
2743 // Analize return values.
2744 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2746 // If this is the first return lowered for this function, add
2747 // the regs to the liveout set for the function.
2748 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2749 for (unsigned i = 0; i != RVLocs.size(); ++i)
2750 if (RVLocs[i].isRegLoc())
2751 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2756 // Copy the result values into the output registers.
2757 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2758 CCValAssign &VA = RVLocs[i];
2759 assert(VA.isRegLoc() && "Can only return in registers!");
2761 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2764 // guarantee that all emitted copies are
2765 // stuck together, avoiding something bad
2766 Flag = Chain.getValue(1);
2769 // The mips ABIs for returning structs by value requires that we copy
2770 // the sret argument into $v0 for the return. We saved the argument into
2771 // a virtual register in the entry block, so now we copy the value out
2773 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2774 MachineFunction &MF = DAG.getMachineFunction();
2775 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2776 unsigned Reg = MipsFI->getSRetReturnReg();
2779 llvm_unreachable("sret virtual register not created in the entry block");
2780 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2782 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2783 Flag = Chain.getValue(1);
2786 // Return on Mips is always a "jr $ra"
2788 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2789 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2791 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2792 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2795 //===----------------------------------------------------------------------===//
2796 // Mips Inline Assembly Support
2797 //===----------------------------------------------------------------------===//
2799 /// getConstraintType - Given a constraint letter, return the type of
2800 /// constraint it is for this target.
2801 MipsTargetLowering::ConstraintType MipsTargetLowering::
2802 getConstraintType(const std::string &Constraint) const
2804 // Mips specific constrainy
2805 // GCC config/mips/constraints.md
2807 // 'd' : An address register. Equivalent to r
2808 // unless generating MIPS16 code.
2809 // 'y' : Equivalent to r; retained for
2810 // backwards compatibility.
2811 // 'f' : Floating Point registers.
2812 if (Constraint.size() == 1) {
2813 switch (Constraint[0]) {
2818 return C_RegisterClass;
2822 return TargetLowering::getConstraintType(Constraint);
2825 /// Examine constraint type and operand type and determine a weight value.
2826 /// This object must already have been set up with the operand type
2827 /// and the current alternative constraint selected.
2828 TargetLowering::ConstraintWeight
2829 MipsTargetLowering::getSingleConstraintMatchWeight(
2830 AsmOperandInfo &info, const char *constraint) const {
2831 ConstraintWeight weight = CW_Invalid;
2832 Value *CallOperandVal = info.CallOperandVal;
2833 // If we don't have a value, we can't do a match,
2834 // but allow it at the lowest weight.
2835 if (CallOperandVal == NULL)
2837 Type *type = CallOperandVal->getType();
2838 // Look at the constraint type.
2839 switch (*constraint) {
2841 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2845 if (type->isIntegerTy())
2846 weight = CW_Register;
2849 if (type->isFloatTy())
2850 weight = CW_Register;
2856 /// Given a register class constraint, like 'r', if this corresponds directly
2857 /// to an LLVM register class, return a register of 0 and the register class
2859 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2860 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2862 if (Constraint.size() == 1) {
2863 switch (Constraint[0]) {
2864 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2865 case 'y': // Same as 'r'. Exists for compatibility.
2867 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2870 return std::make_pair(0U, Mips::FGR32RegisterClass);
2872 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2873 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2877 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2881 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2882 // The Mips target isn't yet aware of offsets.
2886 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2887 if (VT != MVT::f32 && VT != MVT::f64)
2889 if (Imm.isNegZero())
2891 return Imm.isZero();