1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
39 // If I is a shifted mask, set the size (Size) and the first bit of the
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43 if (!isShiftedMask_64(I))
46 Size = CountPopulation_64(I);
47 Pos = CountTrailingZeros_64(I);
51 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
53 case MipsISD::JmpLink: return "MipsISD::JmpLink";
54 case MipsISD::Hi: return "MipsISD::Hi";
55 case MipsISD::Lo: return "MipsISD::Lo";
56 case MipsISD::GPRel: return "MipsISD::GPRel";
57 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
58 case MipsISD::Ret: return "MipsISD::Ret";
59 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
60 case MipsISD::FPCmp: return "MipsISD::FPCmp";
61 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
62 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
63 case MipsISD::FPRound: return "MipsISD::FPRound";
64 case MipsISD::MAdd: return "MipsISD::MAdd";
65 case MipsISD::MAddu: return "MipsISD::MAddu";
66 case MipsISD::MSub: return "MipsISD::MSub";
67 case MipsISD::MSubu: return "MipsISD::MSubu";
68 case MipsISD::DivRem: return "MipsISD::DivRem";
69 case MipsISD::DivRemU: return "MipsISD::DivRemU";
70 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
71 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
72 case MipsISD::Wrapper: return "MipsISD::Wrapper";
73 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
74 case MipsISD::Sync: return "MipsISD::Sync";
75 case MipsISD::Ext: return "MipsISD::Ext";
76 case MipsISD::Ins: return "MipsISD::Ins";
82 MipsTargetLowering(MipsTargetMachine &TM)
83 : TargetLowering(TM, new MipsTargetObjectFile()),
84 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
85 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
86 IsO32(Subtarget->isABI_O32()) {
88 // Mips does not have i1 type, so use i32 for
89 // setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // Set up the register classes
94 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
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::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
161 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
162 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
163 setOperationAction(ISD::ROTL, MVT::i32, Expand);
164 setOperationAction(ISD::ROTL, MVT::i64, Expand);
166 if (!Subtarget->hasMips32r2())
167 setOperationAction(ISD::ROTR, MVT::i32, Expand);
169 if (!Subtarget->hasMips64r2())
170 setOperationAction(ISD::ROTR, MVT::i64, Expand);
172 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
173 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
174 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
175 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
176 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
177 setOperationAction(ISD::FSIN, MVT::f32, Expand);
178 setOperationAction(ISD::FSIN, MVT::f64, Expand);
179 setOperationAction(ISD::FCOS, MVT::f32, Expand);
180 setOperationAction(ISD::FCOS, MVT::f64, Expand);
181 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
182 setOperationAction(ISD::FPOW, MVT::f32, Expand);
183 setOperationAction(ISD::FPOW, MVT::f64, Expand);
184 setOperationAction(ISD::FLOG, MVT::f32, Expand);
185 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
186 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
187 setOperationAction(ISD::FEXP, MVT::f32, Expand);
188 setOperationAction(ISD::FMA, MVT::f32, Expand);
189 setOperationAction(ISD::FMA, MVT::f64, Expand);
191 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
192 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
194 setOperationAction(ISD::VAARG, MVT::Other, Expand);
195 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
196 setOperationAction(ISD::VAEND, MVT::Other, Expand);
198 // Use the default for now
199 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
200 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
202 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
203 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
205 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
206 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
208 setInsertFencesForAtomic(true);
210 if (Subtarget->isSingleFloat())
211 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
213 if (!Subtarget->hasSEInReg()) {
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
218 if (!Subtarget->hasBitCount())
219 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
221 if (!Subtarget->hasSwap())
222 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
224 setTargetDAGCombine(ISD::ADDE);
225 setTargetDAGCombine(ISD::SUBE);
226 setTargetDAGCombine(ISD::SDIVREM);
227 setTargetDAGCombine(ISD::UDIVREM);
228 setTargetDAGCombine(ISD::SETCC);
229 setTargetDAGCombine(ISD::AND);
230 setTargetDAGCombine(ISD::OR);
232 setMinFunctionAlignment(2);
234 setStackPointerRegisterToSaveRestore(Mips::SP);
235 computeRegisterProperties();
237 setExceptionPointerRegister(Mips::A0);
238 setExceptionSelectorRegister(Mips::A1);
241 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
242 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
243 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
246 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
251 // Transforms a subgraph in CurDAG if the following pattern is found:
252 // (addc multLo, Lo0), (adde multHi, Hi0),
254 // multHi/Lo: product of multiplication
255 // Lo0: initial value of Lo register
256 // Hi0: initial value of Hi register
257 // Return true if pattern matching was successful.
258 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
259 // ADDENode's second operand must be a flag output of an ADDC node in order
260 // for the matching to be successful.
261 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
263 if (ADDCNode->getOpcode() != ISD::ADDC)
266 SDValue MultHi = ADDENode->getOperand(0);
267 SDValue MultLo = ADDCNode->getOperand(0);
268 SDNode* MultNode = MultHi.getNode();
269 unsigned MultOpc = MultHi.getOpcode();
271 // MultHi and MultLo must be generated by the same node,
272 if (MultLo.getNode() != MultNode)
275 // and it must be a multiplication.
276 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
279 // MultLo amd MultHi must be the first and second output of MultNode
281 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
284 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
285 // of the values of MultNode, in which case MultNode will be removed in later
287 // If there exist users other than ADDENode or ADDCNode, this function returns
288 // here, which will result in MultNode being mapped to a single MULT
289 // instruction node rather than a pair of MULT and MADD instructions being
291 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
294 SDValue Chain = CurDAG->getEntryNode();
295 DebugLoc dl = ADDENode->getDebugLoc();
297 // create MipsMAdd(u) node
298 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
300 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
302 MultNode->getOperand(0),// Factor 0
303 MultNode->getOperand(1),// Factor 1
304 ADDCNode->getOperand(1),// Lo0
305 ADDENode->getOperand(1));// Hi0
307 // create CopyFromReg nodes
308 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
310 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
312 CopyFromLo.getValue(2));
314 // replace uses of adde and addc here
315 if (!SDValue(ADDCNode, 0).use_empty())
316 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
318 if (!SDValue(ADDENode, 0).use_empty())
319 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
325 // Transforms a subgraph in CurDAG if the following pattern is found:
326 // (addc Lo0, multLo), (sube Hi0, multHi),
328 // multHi/Lo: product of multiplication
329 // Lo0: initial value of Lo register
330 // Hi0: initial value of Hi register
331 // Return true if pattern matching was successful.
332 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
333 // SUBENode's second operand must be a flag output of an SUBC node in order
334 // for the matching to be successful.
335 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
337 if (SUBCNode->getOpcode() != ISD::SUBC)
340 SDValue MultHi = SUBENode->getOperand(1);
341 SDValue MultLo = SUBCNode->getOperand(1);
342 SDNode* MultNode = MultHi.getNode();
343 unsigned MultOpc = MultHi.getOpcode();
345 // MultHi and MultLo must be generated by the same node,
346 if (MultLo.getNode() != MultNode)
349 // and it must be a multiplication.
350 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
353 // MultLo amd MultHi must be the first and second output of MultNode
355 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
358 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
359 // of the values of MultNode, in which case MultNode will be removed in later
361 // If there exist users other than SUBENode or SUBCNode, this function returns
362 // here, which will result in MultNode being mapped to a single MULT
363 // instruction node rather than a pair of MULT and MSUB instructions being
365 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
368 SDValue Chain = CurDAG->getEntryNode();
369 DebugLoc dl = SUBENode->getDebugLoc();
371 // create MipsSub(u) node
372 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
374 SDValue MSub = CurDAG->getNode(MultOpc, dl,
376 MultNode->getOperand(0),// Factor 0
377 MultNode->getOperand(1),// Factor 1
378 SUBCNode->getOperand(0),// Lo0
379 SUBENode->getOperand(0));// Hi0
381 // create CopyFromReg nodes
382 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
384 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
386 CopyFromLo.getValue(2));
388 // replace uses of sube and subc here
389 if (!SDValue(SUBCNode, 0).use_empty())
390 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
392 if (!SDValue(SUBENode, 0).use_empty())
393 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
398 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
399 TargetLowering::DAGCombinerInfo &DCI,
400 const MipsSubtarget* Subtarget) {
401 if (DCI.isBeforeLegalize())
404 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
406 return SDValue(N, 0);
411 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
412 TargetLowering::DAGCombinerInfo &DCI,
413 const MipsSubtarget* Subtarget) {
414 if (DCI.isBeforeLegalize())
417 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
419 return SDValue(N, 0);
424 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
425 TargetLowering::DAGCombinerInfo &DCI,
426 const MipsSubtarget* Subtarget) {
427 if (DCI.isBeforeLegalizeOps())
430 EVT Ty = N->getValueType(0);
431 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
432 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
433 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
435 DebugLoc dl = N->getDebugLoc();
437 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
438 N->getOperand(0), N->getOperand(1));
439 SDValue InChain = DAG.getEntryNode();
440 SDValue InGlue = DivRem;
443 if (N->hasAnyUseOfValue(0)) {
444 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
447 InChain = CopyFromLo.getValue(1);
448 InGlue = CopyFromLo.getValue(2);
452 if (N->hasAnyUseOfValue(1)) {
453 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
455 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
461 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
463 default: llvm_unreachable("Unknown fp condition code!");
465 case ISD::SETOEQ: return Mips::FCOND_OEQ;
466 case ISD::SETUNE: return Mips::FCOND_UNE;
468 case ISD::SETOLT: return Mips::FCOND_OLT;
470 case ISD::SETOGT: return Mips::FCOND_OGT;
472 case ISD::SETOLE: return Mips::FCOND_OLE;
474 case ISD::SETOGE: return Mips::FCOND_OGE;
475 case ISD::SETULT: return Mips::FCOND_ULT;
476 case ISD::SETULE: return Mips::FCOND_ULE;
477 case ISD::SETUGT: return Mips::FCOND_UGT;
478 case ISD::SETUGE: return Mips::FCOND_UGE;
479 case ISD::SETUO: return Mips::FCOND_UN;
480 case ISD::SETO: return Mips::FCOND_OR;
482 case ISD::SETONE: return Mips::FCOND_ONE;
483 case ISD::SETUEQ: return Mips::FCOND_UEQ;
488 // Returns true if condition code has to be inverted.
489 static bool InvertFPCondCode(Mips::CondCode CC) {
490 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
493 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
496 assert(false && "Illegal Condition Code");
500 // Creates and returns an FPCmp node from a setcc node.
501 // Returns Op if setcc is not a floating point comparison.
502 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
503 // must be a SETCC node
504 if (Op.getOpcode() != ISD::SETCC)
507 SDValue LHS = Op.getOperand(0);
509 if (!LHS.getValueType().isFloatingPoint())
512 SDValue RHS = Op.getOperand(1);
513 DebugLoc dl = Op.getDebugLoc();
515 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
516 // node if necessary.
517 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
519 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
520 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
523 // Creates and returns a CMovFPT/F node.
524 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
525 SDValue False, DebugLoc DL) {
526 bool invert = InvertFPCondCode((Mips::CondCode)
527 cast<ConstantSDNode>(Cond.getOperand(2))
530 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
531 True.getValueType(), True, False, Cond);
534 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
535 TargetLowering::DAGCombinerInfo &DCI,
536 const MipsSubtarget* Subtarget) {
537 if (DCI.isBeforeLegalizeOps())
540 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
542 if (Cond.getOpcode() != MipsISD::FPCmp)
545 SDValue True = DAG.getConstant(1, MVT::i32);
546 SDValue False = DAG.getConstant(0, MVT::i32);
548 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
551 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
552 TargetLowering::DAGCombinerInfo &DCI,
553 const MipsSubtarget* Subtarget) {
554 // Pattern match EXT.
555 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
556 // => ext $dst, $src, size, pos
557 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
560 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
561 unsigned ShiftRightOpc = ShiftRight.getOpcode();
563 // Op's first operand must be a shift right.
564 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
567 // The second operand of the shift must be an immediate.
569 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
572 uint64_t Pos = CN->getZExtValue();
573 uint64_t SMPos, SMSize;
575 // Op's second operand must be a shifted mask.
576 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
577 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
580 // Return if the shifted mask does not start at bit 0 or the sum of its size
581 // and Pos exceeds the word's size.
582 EVT ValTy = N->getValueType(0);
583 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
586 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
587 ShiftRight.getOperand(0),
588 DAG.getConstant(Pos, MVT::i32),
589 DAG.getConstant(SMSize, MVT::i32));
592 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
593 TargetLowering::DAGCombinerInfo &DCI,
594 const MipsSubtarget* Subtarget) {
595 // Pattern match INS.
596 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
597 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
598 // => ins $dst, $src, size, pos, $src1
599 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
602 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
603 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
606 // See if Op's first operand matches (and $src1 , mask0).
607 if (And0.getOpcode() != ISD::AND)
610 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
611 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
614 // See if Op's second operand matches (and (shl $src, pos), mask1).
615 if (And1.getOpcode() != ISD::AND)
618 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
619 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
622 // The shift masks must have the same position and size.
623 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
626 SDValue Shl = And1.getOperand(0);
627 if (Shl.getOpcode() != ISD::SHL)
630 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
633 unsigned Shamt = CN->getZExtValue();
635 // Return if the shift amount and the first bit position of mask are not the
637 EVT ValTy = N->getValueType(0);
638 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
641 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy,
643 DAG.getConstant(SMPos0, MVT::i32),
644 DAG.getConstant(SMSize0, MVT::i32),
648 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
650 SelectionDAG &DAG = DCI.DAG;
651 unsigned opc = N->getOpcode();
656 return PerformADDECombine(N, DAG, DCI, Subtarget);
658 return PerformSUBECombine(N, DAG, DCI, Subtarget);
661 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
663 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
665 return PerformANDCombine(N, DAG, DCI, Subtarget);
667 return PerformORCombine(N, DAG, DCI, Subtarget);
673 SDValue MipsTargetLowering::
674 LowerOperation(SDValue Op, SelectionDAG &DAG) const
676 switch (Op.getOpcode())
678 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
679 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
680 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
681 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
682 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
683 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
684 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
685 case ISD::SELECT: return LowerSELECT(Op, DAG);
686 case ISD::VASTART: return LowerVASTART(Op, DAG);
687 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
688 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
689 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
690 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
695 //===----------------------------------------------------------------------===//
696 // Lower helper functions
697 //===----------------------------------------------------------------------===//
699 // AddLiveIn - This helper function adds the specified physical register to the
700 // MachineFunction as a live in value. It also creates a corresponding
701 // virtual register for it.
703 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
705 assert(RC->contains(PReg) && "Not the correct regclass!");
706 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
707 MF.getRegInfo().addLiveIn(PReg, VReg);
711 // Get fp branch code (not opcode) from condition code.
712 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
713 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
714 return Mips::BRANCH_T;
716 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
717 return Mips::BRANCH_F;
719 return Mips::BRANCH_INVALID;
723 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
725 const MipsSubtarget* Subtarget,
726 const TargetInstrInfo *TII,
727 bool isFPCmp, unsigned Opc) {
728 // There is no need to expand CMov instructions if target has
729 // conditional moves.
730 if (Subtarget->hasCondMov())
733 // To "insert" a SELECT_CC instruction, we actually have to insert the
734 // diamond control-flow pattern. The incoming instruction knows the
735 // destination vreg to set, the condition code register to branch on, the
736 // true/false values to select between, and a branch opcode to use.
737 const BasicBlock *LLVM_BB = BB->getBasicBlock();
738 MachineFunction::iterator It = BB;
745 // bNE r1, r0, copy1MBB
746 // fallthrough --> copy0MBB
747 MachineBasicBlock *thisMBB = BB;
748 MachineFunction *F = BB->getParent();
749 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
750 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
751 F->insert(It, copy0MBB);
752 F->insert(It, sinkMBB);
754 // Transfer the remainder of BB and its successor edges to sinkMBB.
755 sinkMBB->splice(sinkMBB->begin(), BB,
756 llvm::next(MachineBasicBlock::iterator(MI)),
758 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
760 // Next, add the true and fallthrough blocks as its successors.
761 BB->addSuccessor(copy0MBB);
762 BB->addSuccessor(sinkMBB);
764 // Emit the right instruction according to the type of the operands compared
766 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
768 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
769 .addReg(Mips::ZERO).addMBB(sinkMBB);
773 // # fallthrough to sinkMBB
776 // Update machine-CFG edges
777 BB->addSuccessor(sinkMBB);
780 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
785 BuildMI(*BB, BB->begin(), dl,
786 TII->get(Mips::PHI), MI->getOperand(0).getReg())
787 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
788 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
790 BuildMI(*BB, BB->begin(), dl,
791 TII->get(Mips::PHI), MI->getOperand(0).getReg())
792 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
793 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
795 MI->eraseFromParent(); // The pseudo instruction is gone now.
800 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
801 MachineBasicBlock *BB) const {
802 switch (MI->getOpcode()) {
804 assert(false && "Unexpected instr type to insert");
806 case Mips::ATOMIC_LOAD_ADD_I8:
807 case Mips::ATOMIC_LOAD_ADD_I8_P8:
808 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
809 case Mips::ATOMIC_LOAD_ADD_I16:
810 case Mips::ATOMIC_LOAD_ADD_I16_P8:
811 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
812 case Mips::ATOMIC_LOAD_ADD_I32:
813 case Mips::ATOMIC_LOAD_ADD_I32_P8:
814 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
815 case Mips::ATOMIC_LOAD_ADD_I64:
816 case Mips::ATOMIC_LOAD_ADD_I64_P8:
817 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
819 case Mips::ATOMIC_LOAD_AND_I8:
820 case Mips::ATOMIC_LOAD_AND_I8_P8:
821 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
822 case Mips::ATOMIC_LOAD_AND_I16:
823 case Mips::ATOMIC_LOAD_AND_I16_P8:
824 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
825 case Mips::ATOMIC_LOAD_AND_I32:
826 case Mips::ATOMIC_LOAD_AND_I32_P8:
827 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
828 case Mips::ATOMIC_LOAD_AND_I64:
829 case Mips::ATOMIC_LOAD_AND_I64_P8:
830 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
832 case Mips::ATOMIC_LOAD_OR_I8:
833 case Mips::ATOMIC_LOAD_OR_I8_P8:
834 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
835 case Mips::ATOMIC_LOAD_OR_I16:
836 case Mips::ATOMIC_LOAD_OR_I16_P8:
837 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
838 case Mips::ATOMIC_LOAD_OR_I32:
839 case Mips::ATOMIC_LOAD_OR_I32_P8:
840 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
841 case Mips::ATOMIC_LOAD_OR_I64:
842 case Mips::ATOMIC_LOAD_OR_I64_P8:
843 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
845 case Mips::ATOMIC_LOAD_XOR_I8:
846 case Mips::ATOMIC_LOAD_XOR_I8_P8:
847 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
848 case Mips::ATOMIC_LOAD_XOR_I16:
849 case Mips::ATOMIC_LOAD_XOR_I16_P8:
850 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
851 case Mips::ATOMIC_LOAD_XOR_I32:
852 case Mips::ATOMIC_LOAD_XOR_I32_P8:
853 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
854 case Mips::ATOMIC_LOAD_XOR_I64:
855 case Mips::ATOMIC_LOAD_XOR_I64_P8:
856 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
858 case Mips::ATOMIC_LOAD_NAND_I8:
859 case Mips::ATOMIC_LOAD_NAND_I8_P8:
860 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
861 case Mips::ATOMIC_LOAD_NAND_I16:
862 case Mips::ATOMIC_LOAD_NAND_I16_P8:
863 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
864 case Mips::ATOMIC_LOAD_NAND_I32:
865 case Mips::ATOMIC_LOAD_NAND_I32_P8:
866 return EmitAtomicBinary(MI, BB, 4, 0, true);
867 case Mips::ATOMIC_LOAD_NAND_I64:
868 case Mips::ATOMIC_LOAD_NAND_I64_P8:
869 return EmitAtomicBinary(MI, BB, 8, 0, true);
871 case Mips::ATOMIC_LOAD_SUB_I8:
872 case Mips::ATOMIC_LOAD_SUB_I8_P8:
873 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
874 case Mips::ATOMIC_LOAD_SUB_I16:
875 case Mips::ATOMIC_LOAD_SUB_I16_P8:
876 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
877 case Mips::ATOMIC_LOAD_SUB_I32:
878 case Mips::ATOMIC_LOAD_SUB_I32_P8:
879 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
880 case Mips::ATOMIC_LOAD_SUB_I64:
881 case Mips::ATOMIC_LOAD_SUB_I64_P8:
882 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
884 case Mips::ATOMIC_SWAP_I8:
885 case Mips::ATOMIC_SWAP_I8_P8:
886 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
887 case Mips::ATOMIC_SWAP_I16:
888 case Mips::ATOMIC_SWAP_I16_P8:
889 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
890 case Mips::ATOMIC_SWAP_I32:
891 case Mips::ATOMIC_SWAP_I32_P8:
892 return EmitAtomicBinary(MI, BB, 4, 0);
893 case Mips::ATOMIC_SWAP_I64:
894 case Mips::ATOMIC_SWAP_I64_P8:
895 return EmitAtomicBinary(MI, BB, 8, 0);
897 case Mips::ATOMIC_CMP_SWAP_I8:
898 case Mips::ATOMIC_CMP_SWAP_I8_P8:
899 return EmitAtomicCmpSwapPartword(MI, BB, 1);
900 case Mips::ATOMIC_CMP_SWAP_I16:
901 case Mips::ATOMIC_CMP_SWAP_I16_P8:
902 return EmitAtomicCmpSwapPartword(MI, BB, 2);
903 case Mips::ATOMIC_CMP_SWAP_I32:
904 case Mips::ATOMIC_CMP_SWAP_I32_P8:
905 return EmitAtomicCmpSwap(MI, BB, 4);
906 case Mips::ATOMIC_CMP_SWAP_I64:
907 case Mips::ATOMIC_CMP_SWAP_I64_P8:
908 return EmitAtomicCmpSwap(MI, BB, 8);
912 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
913 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
915 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
916 unsigned Size, unsigned BinOpcode,
918 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
920 MachineFunction *MF = BB->getParent();
921 MachineRegisterInfo &RegInfo = MF->getRegInfo();
922 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
923 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
924 DebugLoc dl = MI->getDebugLoc();
925 unsigned LL, SC, AND, NOR, ZERO, BEQ;
928 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
929 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
936 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
937 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
940 ZERO = Mips::ZERO_64;
944 unsigned OldVal = MI->getOperand(0).getReg();
945 unsigned Ptr = MI->getOperand(1).getReg();
946 unsigned Incr = MI->getOperand(2).getReg();
948 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
949 unsigned AndRes = RegInfo.createVirtualRegister(RC);
950 unsigned Success = RegInfo.createVirtualRegister(RC);
952 // insert new blocks after the current block
953 const BasicBlock *LLVM_BB = BB->getBasicBlock();
954 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
955 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
956 MachineFunction::iterator It = BB;
958 MF->insert(It, loopMBB);
959 MF->insert(It, exitMBB);
961 // Transfer the remainder of BB and its successor edges to exitMBB.
962 exitMBB->splice(exitMBB->begin(), BB,
963 llvm::next(MachineBasicBlock::iterator(MI)),
965 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
969 // fallthrough --> loopMBB
970 BB->addSuccessor(loopMBB);
971 loopMBB->addSuccessor(loopMBB);
972 loopMBB->addSuccessor(exitMBB);
976 // <binop> storeval, oldval, incr
977 // sc success, storeval, 0(ptr)
978 // beq success, $0, loopMBB
980 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
982 // and andres, oldval, incr
983 // nor storeval, $0, andres
984 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
985 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
986 } else if (BinOpcode) {
987 // <binop> storeval, oldval, incr
988 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
992 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
993 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
995 MI->eraseFromParent(); // The instruction is gone now.
1001 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1002 MachineBasicBlock *BB,
1003 unsigned Size, unsigned BinOpcode,
1005 assert((Size == 1 || Size == 2) &&
1006 "Unsupported size for EmitAtomicBinaryPartial.");
1008 MachineFunction *MF = BB->getParent();
1009 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1010 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1011 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1012 DebugLoc dl = MI->getDebugLoc();
1013 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1014 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1016 unsigned Dest = MI->getOperand(0).getReg();
1017 unsigned Ptr = MI->getOperand(1).getReg();
1018 unsigned Incr = MI->getOperand(2).getReg();
1020 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1021 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1022 unsigned Mask = RegInfo.createVirtualRegister(RC);
1023 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1024 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1025 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1026 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1027 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1028 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1029 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1030 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1031 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1032 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1033 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1034 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1035 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1036 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1037 unsigned Success = RegInfo.createVirtualRegister(RC);
1039 // insert new blocks after the current block
1040 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1041 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1042 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1043 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1044 MachineFunction::iterator It = BB;
1046 MF->insert(It, loopMBB);
1047 MF->insert(It, sinkMBB);
1048 MF->insert(It, exitMBB);
1050 // Transfer the remainder of BB and its successor edges to exitMBB.
1051 exitMBB->splice(exitMBB->begin(), BB,
1052 llvm::next(MachineBasicBlock::iterator(MI)),
1054 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1056 BB->addSuccessor(loopMBB);
1057 loopMBB->addSuccessor(loopMBB);
1058 loopMBB->addSuccessor(sinkMBB);
1059 sinkMBB->addSuccessor(exitMBB);
1062 // addiu masklsb2,$0,-4 # 0xfffffffc
1063 // and alignedaddr,ptr,masklsb2
1064 // andi ptrlsb2,ptr,3
1065 // sll shiftamt,ptrlsb2,3
1066 // ori maskupper,$0,255 # 0xff
1067 // sll mask,maskupper,shiftamt
1068 // nor mask2,$0,mask
1069 // sll incr2,incr,shiftamt
1071 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1072 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1073 .addReg(Mips::ZERO).addImm(-4);
1074 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1075 .addReg(Ptr).addReg(MaskLSB2);
1076 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1077 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1078 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1079 .addReg(Mips::ZERO).addImm(MaskImm);
1080 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1081 .addReg(ShiftAmt).addReg(MaskUpper);
1082 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1083 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1086 // atomic.load.binop
1088 // ll oldval,0(alignedaddr)
1089 // binop binopres,oldval,incr2
1090 // and newval,binopres,mask
1091 // and maskedoldval0,oldval,mask2
1092 // or storeval,maskedoldval0,newval
1093 // sc success,storeval,0(alignedaddr)
1094 // beq success,$0,loopMBB
1098 // ll oldval,0(alignedaddr)
1099 // and newval,incr2,mask
1100 // and maskedoldval0,oldval,mask2
1101 // or storeval,maskedoldval0,newval
1102 // sc success,storeval,0(alignedaddr)
1103 // beq success,$0,loopMBB
1106 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1108 // and andres, oldval, incr2
1109 // nor binopres, $0, andres
1110 // and newval, binopres, mask
1111 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1112 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1113 .addReg(Mips::ZERO).addReg(AndRes);
1114 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1115 } else if (BinOpcode) {
1116 // <binop> binopres, oldval, incr2
1117 // and newval, binopres, mask
1118 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1119 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1120 } else {// atomic.swap
1121 // and newval, incr2, mask
1122 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1125 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1126 .addReg(OldVal).addReg(Mask2);
1127 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1128 .addReg(MaskedOldVal0).addReg(NewVal);
1129 BuildMI(BB, dl, TII->get(SC), Success)
1130 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1131 BuildMI(BB, dl, TII->get(Mips::BEQ))
1132 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1135 // and maskedoldval1,oldval,mask
1136 // srl srlres,maskedoldval1,shiftamt
1137 // sll sllres,srlres,24
1138 // sra dest,sllres,24
1140 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1142 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1143 .addReg(OldVal).addReg(Mask);
1144 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1145 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1146 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1147 .addReg(SrlRes).addImm(ShiftImm);
1148 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1149 .addReg(SllRes).addImm(ShiftImm);
1151 MI->eraseFromParent(); // The instruction is gone now.
1157 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1158 MachineBasicBlock *BB,
1159 unsigned Size) const {
1160 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1162 MachineFunction *MF = BB->getParent();
1163 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1164 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1165 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1166 DebugLoc dl = MI->getDebugLoc();
1167 unsigned LL, SC, ZERO, BNE, BEQ;
1170 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1171 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1177 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1178 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1179 ZERO = Mips::ZERO_64;
1184 unsigned Dest = MI->getOperand(0).getReg();
1185 unsigned Ptr = MI->getOperand(1).getReg();
1186 unsigned OldVal = MI->getOperand(2).getReg();
1187 unsigned NewVal = MI->getOperand(3).getReg();
1189 unsigned Success = RegInfo.createVirtualRegister(RC);
1191 // insert new blocks after the current block
1192 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1193 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1194 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1195 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1196 MachineFunction::iterator It = BB;
1198 MF->insert(It, loop1MBB);
1199 MF->insert(It, loop2MBB);
1200 MF->insert(It, exitMBB);
1202 // Transfer the remainder of BB and its successor edges to exitMBB.
1203 exitMBB->splice(exitMBB->begin(), BB,
1204 llvm::next(MachineBasicBlock::iterator(MI)),
1206 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1210 // fallthrough --> loop1MBB
1211 BB->addSuccessor(loop1MBB);
1212 loop1MBB->addSuccessor(exitMBB);
1213 loop1MBB->addSuccessor(loop2MBB);
1214 loop2MBB->addSuccessor(loop1MBB);
1215 loop2MBB->addSuccessor(exitMBB);
1219 // bne dest, oldval, exitMBB
1221 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1222 BuildMI(BB, dl, TII->get(BNE))
1223 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1226 // sc success, newval, 0(ptr)
1227 // beq success, $0, loop1MBB
1229 BuildMI(BB, dl, TII->get(SC), Success)
1230 .addReg(NewVal).addReg(Ptr).addImm(0);
1231 BuildMI(BB, dl, TII->get(BEQ))
1232 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1234 MI->eraseFromParent(); // The instruction is gone now.
1240 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1241 MachineBasicBlock *BB,
1242 unsigned Size) const {
1243 assert((Size == 1 || Size == 2) &&
1244 "Unsupported size for EmitAtomicCmpSwapPartial.");
1246 MachineFunction *MF = BB->getParent();
1247 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1248 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1250 DebugLoc dl = MI->getDebugLoc();
1251 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1252 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1254 unsigned Dest = MI->getOperand(0).getReg();
1255 unsigned Ptr = MI->getOperand(1).getReg();
1256 unsigned CmpVal = MI->getOperand(2).getReg();
1257 unsigned NewVal = MI->getOperand(3).getReg();
1259 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1260 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1261 unsigned Mask = RegInfo.createVirtualRegister(RC);
1262 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1263 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1264 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1266 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1267 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1268 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1269 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1270 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1271 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1272 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1273 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1274 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1275 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1276 unsigned Success = RegInfo.createVirtualRegister(RC);
1278 // insert new blocks after the current block
1279 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1280 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1281 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1282 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1283 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1284 MachineFunction::iterator It = BB;
1286 MF->insert(It, loop1MBB);
1287 MF->insert(It, loop2MBB);
1288 MF->insert(It, sinkMBB);
1289 MF->insert(It, exitMBB);
1291 // Transfer the remainder of BB and its successor edges to exitMBB.
1292 exitMBB->splice(exitMBB->begin(), BB,
1293 llvm::next(MachineBasicBlock::iterator(MI)),
1295 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1297 BB->addSuccessor(loop1MBB);
1298 loop1MBB->addSuccessor(sinkMBB);
1299 loop1MBB->addSuccessor(loop2MBB);
1300 loop2MBB->addSuccessor(loop1MBB);
1301 loop2MBB->addSuccessor(sinkMBB);
1302 sinkMBB->addSuccessor(exitMBB);
1304 // FIXME: computation of newval2 can be moved to loop2MBB.
1306 // addiu masklsb2,$0,-4 # 0xfffffffc
1307 // and alignedaddr,ptr,masklsb2
1308 // andi ptrlsb2,ptr,3
1309 // sll shiftamt,ptrlsb2,3
1310 // ori maskupper,$0,255 # 0xff
1311 // sll mask,maskupper,shiftamt
1312 // nor mask2,$0,mask
1313 // andi maskedcmpval,cmpval,255
1314 // sll shiftedcmpval,maskedcmpval,shiftamt
1315 // andi maskednewval,newval,255
1316 // sll shiftednewval,maskednewval,shiftamt
1317 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1318 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1319 .addReg(Mips::ZERO).addImm(-4);
1320 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1321 .addReg(Ptr).addReg(MaskLSB2);
1322 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1323 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1324 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1325 .addReg(Mips::ZERO).addImm(MaskImm);
1326 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1327 .addReg(ShiftAmt).addReg(MaskUpper);
1328 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1329 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1330 .addReg(CmpVal).addImm(MaskImm);
1331 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1332 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1333 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1334 .addReg(NewVal).addImm(MaskImm);
1335 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1336 .addReg(ShiftAmt).addReg(MaskedNewVal);
1339 // ll oldval,0(alginedaddr)
1340 // and maskedoldval0,oldval,mask
1341 // bne maskedoldval0,shiftedcmpval,sinkMBB
1343 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1344 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1345 .addReg(OldVal).addReg(Mask);
1346 BuildMI(BB, dl, TII->get(Mips::BNE))
1347 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1350 // and maskedoldval1,oldval,mask2
1351 // or storeval,maskedoldval1,shiftednewval
1352 // sc success,storeval,0(alignedaddr)
1353 // beq success,$0,loop1MBB
1355 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1356 .addReg(OldVal).addReg(Mask2);
1357 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1358 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1359 BuildMI(BB, dl, TII->get(SC), Success)
1360 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1361 BuildMI(BB, dl, TII->get(Mips::BEQ))
1362 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1365 // srl srlres,maskedoldval0,shiftamt
1366 // sll sllres,srlres,24
1367 // sra dest,sllres,24
1369 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1371 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1372 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1373 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1374 .addReg(SrlRes).addImm(ShiftImm);
1375 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1376 .addReg(SllRes).addImm(ShiftImm);
1378 MI->eraseFromParent(); // The instruction is gone now.
1383 //===----------------------------------------------------------------------===//
1384 // Misc Lower Operation implementation
1385 //===----------------------------------------------------------------------===//
1386 SDValue MipsTargetLowering::
1387 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1389 MachineFunction &MF = DAG.getMachineFunction();
1390 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1391 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1393 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1394 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1395 "Cannot lower if the alignment of the allocated space is larger than \
1396 that of the stack.");
1398 SDValue Chain = Op.getOperand(0);
1399 SDValue Size = Op.getOperand(1);
1400 DebugLoc dl = Op.getDebugLoc();
1402 // Get a reference from Mips stack pointer
1403 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1405 // Subtract the dynamic size from the actual stack size to
1406 // obtain the new stack size.
1407 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1409 // The Sub result contains the new stack start address, so it
1410 // must be placed in the stack pointer register.
1411 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1413 // This node always has two return values: a new stack pointer
1414 // value and a chain
1415 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1416 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1417 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1419 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1422 SDValue MipsTargetLowering::
1423 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1425 // The first operand is the chain, the second is the condition, the third is
1426 // the block to branch to if the condition is true.
1427 SDValue Chain = Op.getOperand(0);
1428 SDValue Dest = Op.getOperand(2);
1429 DebugLoc dl = Op.getDebugLoc();
1431 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1433 // Return if flag is not set by a floating point comparison.
1434 if (CondRes.getOpcode() != MipsISD::FPCmp)
1437 SDValue CCNode = CondRes.getOperand(2);
1439 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1440 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1442 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1446 SDValue MipsTargetLowering::
1447 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1449 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1451 // Return if flag is not set by a floating point comparison.
1452 if (Cond.getOpcode() != MipsISD::FPCmp)
1455 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1459 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1460 SelectionDAG &DAG) const {
1461 // FIXME there isn't actually debug info here
1462 DebugLoc dl = Op.getDebugLoc();
1463 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1465 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1466 SDVTList VTs = DAG.getVTList(MVT::i32);
1468 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1470 // %gp_rel relocation
1471 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1472 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1474 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1475 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1476 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1478 // %hi/%lo relocation
1479 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1481 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1483 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1484 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1485 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1488 EVT ValTy = Op.getValueType();
1489 bool HasGotOfst = (GV->hasInternalLinkage() ||
1490 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1491 unsigned GotFlag = IsN64 ?
1492 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1493 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1494 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1495 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GA);
1496 SDValue ResNode = DAG.getLoad(ValTy, dl,
1497 DAG.getEntryNode(), GA, MachinePointerInfo(),
1498 false, false, false, 0);
1499 // On functions and global targets not internal linked only
1500 // a load from got/GP is necessary for PIC to work.
1503 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1504 IsN64 ? MipsII::MO_GOT_OFST :
1506 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1507 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1510 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1511 SelectionDAG &DAG) const {
1512 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1513 // FIXME there isn't actually debug info here
1514 DebugLoc dl = Op.getDebugLoc();
1516 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1517 // %hi/%lo relocation
1518 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1520 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1522 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1523 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1524 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1527 EVT ValTy = Op.getValueType();
1528 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1529 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1530 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1531 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy, BAGOTOffset);
1532 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1533 SDValue Load = DAG.getLoad(ValTy, dl,
1534 DAG.getEntryNode(), BAGOTOffset,
1535 MachinePointerInfo(), false, false, false, 0);
1536 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1537 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1540 SDValue MipsTargetLowering::
1541 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1543 // If the relocation model is PIC, use the General Dynamic TLS Model,
1544 // otherwise use the Initial Exec or Local Exec TLS Model.
1545 // TODO: implement Local Dynamic TLS model
1547 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1548 DebugLoc dl = GA->getDebugLoc();
1549 const GlobalValue *GV = GA->getGlobal();
1550 EVT PtrVT = getPointerTy();
1552 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1553 // General Dynamic TLS Model
1554 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT,
1555 0, MipsII::MO_TLSGD);
1556 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1557 unsigned PtrSize = PtrVT.getSizeInBits();
1558 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1560 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1564 Entry.Node = Argument;
1566 Args.push_back(Entry);
1568 std::pair<SDValue, SDValue> CallResult =
1569 LowerCallTo(DAG.getEntryNode(), PtrTy,
1570 false, false, false, false, 0, CallingConv::C, false, true,
1571 TlsGetAddr, Args, DAG, dl);
1573 return CallResult.first;
1577 if (GV->isDeclaration()) {
1578 // Initial Exec TLS Model
1579 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1580 MipsII::MO_GOTTPREL);
1581 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1582 Offset = DAG.getLoad(PtrVT, dl,
1583 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1584 false, false, false, 0);
1586 // Local Exec TLS Model
1587 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1588 MipsII::MO_TPREL_HI);
1589 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1590 MipsII::MO_TPREL_LO);
1591 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1592 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1593 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1596 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1597 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1600 SDValue MipsTargetLowering::
1601 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1603 SDValue HiPart, JTI, JTILo;
1604 // FIXME there isn't actually debug info here
1605 DebugLoc dl = Op.getDebugLoc();
1606 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1607 EVT PtrVT = Op.getValueType();
1608 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1610 if (!IsPIC && !IsN64) {
1611 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1612 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1613 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1614 } else {// Emit Load from Global Pointer
1615 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1616 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1617 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1618 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, JTI);
1619 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1620 MachinePointerInfo(), false, false, false, 0);
1621 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1624 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1625 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1628 SDValue MipsTargetLowering::
1629 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1632 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1633 const Constant *C = N->getConstVal();
1634 // FIXME there isn't actually debug info here
1635 DebugLoc dl = Op.getDebugLoc();
1637 // gp_rel relocation
1638 // FIXME: we should reference the constant pool using small data sections,
1639 // but the asm printer currently doesn't support this feature without
1640 // hacking it. This feature should come soon so we can uncomment the
1642 //if (IsInSmallSection(C->getType())) {
1643 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1644 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1645 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1647 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1648 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1649 N->getOffset(), MipsII::MO_ABS_HI);
1650 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1651 N->getOffset(), MipsII::MO_ABS_LO);
1652 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1653 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1654 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1656 EVT ValTy = Op.getValueType();
1657 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1658 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1659 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1660 N->getOffset(), GOTFlag);
1661 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, CP);
1662 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(),
1663 CP, MachinePointerInfo::getConstantPool(),
1664 false, false, false, 0);
1665 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1666 N->getOffset(), OFSTFlag);
1667 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1668 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1674 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1675 MachineFunction &MF = DAG.getMachineFunction();
1676 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1678 DebugLoc dl = Op.getDebugLoc();
1679 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1682 // vastart just stores the address of the VarArgsFrameIndex slot into the
1683 // memory location argument.
1684 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1685 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1686 MachinePointerInfo(SV),
1690 // Called if the size of integer registers is large enough to hold the whole
1691 // floating point number.
1692 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1693 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1694 EVT ValTy = Op.getValueType();
1695 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1696 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1697 DebugLoc dl = Op.getDebugLoc();
1698 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1699 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1700 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1701 DAG.getConstant(Mask - 1, IntValTy));
1702 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1703 DAG.getConstant(Mask, IntValTy));
1704 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1705 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1708 // Called if the size of integer registers is not large enough to hold the whole
1709 // floating point number (e.g. f64 & 32-bit integer register).
1711 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1713 // Use ext/ins instructions if target architecture is Mips32r2.
1714 // Eliminate redundant mfc1 and mtc1 instructions.
1715 unsigned LoIdx = 0, HiIdx = 1;
1718 std::swap(LoIdx, HiIdx);
1720 DebugLoc dl = Op.getDebugLoc();
1721 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1723 DAG.getConstant(LoIdx, MVT::i32));
1724 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1725 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1726 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1727 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1728 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1729 DAG.getConstant(0x7fffffff, MVT::i32));
1730 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1731 DAG.getConstant(0x80000000, MVT::i32));
1732 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1735 std::swap(Word0, Word1);
1737 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1740 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1742 EVT Ty = Op.getValueType();
1744 assert(Ty == MVT::f32 || Ty == MVT::f64);
1746 if (Ty == MVT::f32 || HasMips64)
1747 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1749 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1752 SDValue MipsTargetLowering::
1753 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1755 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1756 "Frame address can only be determined for current frame.");
1758 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1759 MFI->setFrameAddressIsTaken(true);
1760 EVT VT = Op.getValueType();
1761 DebugLoc dl = Op.getDebugLoc();
1762 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1763 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1767 // TODO: set SType according to the desired memory barrier behavior.
1768 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1769 SelectionDAG& DAG) const {
1771 DebugLoc dl = Op.getDebugLoc();
1772 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1773 DAG.getConstant(SType, MVT::i32));
1776 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1777 SelectionDAG& DAG) const {
1778 // FIXME: Need pseudo-fence for 'singlethread' fences
1779 // FIXME: Set SType for weaker fences where supported/appropriate.
1781 DebugLoc dl = Op.getDebugLoc();
1782 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1783 DAG.getConstant(SType, MVT::i32));
1786 //===----------------------------------------------------------------------===//
1787 // Calling Convention Implementation
1788 //===----------------------------------------------------------------------===//
1790 //===----------------------------------------------------------------------===//
1791 // TODO: Implement a generic logic using tblgen that can support this.
1792 // Mips O32 ABI rules:
1794 // i32 - Passed in A0, A1, A2, A3 and stack
1795 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1796 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1797 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1798 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1799 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1802 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1803 //===----------------------------------------------------------------------===//
1805 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1806 MVT LocVT, CCValAssign::LocInfo LocInfo,
1807 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1809 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1811 static const unsigned IntRegs[] = {
1812 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1814 static const unsigned F32Regs[] = {
1815 Mips::F12, Mips::F14
1817 static const unsigned F64Regs[] = {
1822 if (ArgFlags.isByVal()) {
1823 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1824 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1825 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1826 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1827 r < std::min(IntRegsSize, NextReg); ++r)
1828 State.AllocateReg(IntRegs[r]);
1832 // Promote i8 and i16
1833 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1835 if (ArgFlags.isSExt())
1836 LocInfo = CCValAssign::SExt;
1837 else if (ArgFlags.isZExt())
1838 LocInfo = CCValAssign::ZExt;
1840 LocInfo = CCValAssign::AExt;
1845 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1846 // is true: function is vararg, argument is 3rd or higher, there is previous
1847 // argument which is not f32 or f64.
1848 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1849 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1850 unsigned OrigAlign = ArgFlags.getOrigAlign();
1851 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1853 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1854 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1855 // If this is the first part of an i64 arg,
1856 // the allocated register must be either A0 or A2.
1857 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1858 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1860 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1861 // Allocate int register and shadow next int register. If first
1862 // available register is Mips::A1 or Mips::A3, shadow it too.
1863 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1864 if (Reg == Mips::A1 || Reg == Mips::A3)
1865 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1866 State.AllocateReg(IntRegs, IntRegsSize);
1868 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1869 // we are guaranteed to find an available float register
1870 if (ValVT == MVT::f32) {
1871 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1872 // Shadow int register
1873 State.AllocateReg(IntRegs, IntRegsSize);
1875 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1876 // Shadow int registers
1877 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1878 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1879 State.AllocateReg(IntRegs, IntRegsSize);
1880 State.AllocateReg(IntRegs, IntRegsSize);
1883 llvm_unreachable("Cannot handle this ValVT.");
1885 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1886 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1889 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1891 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1893 return false; // CC must always match
1896 static const unsigned Mips64IntRegs[8] =
1897 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1898 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1899 static const unsigned Mips64DPRegs[8] =
1900 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1901 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1903 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1904 CCValAssign::LocInfo LocInfo,
1905 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1906 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1907 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1908 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1910 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1912 // If byval is 16-byte aligned, the first arg register must be even.
1913 if ((Align == 16) && (FirstIdx % 2)) {
1914 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1918 // Mark the registers allocated.
1919 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1920 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1922 // Allocate space on caller's stack.
1923 unsigned Offset = State.AllocateStack(Size, Align);
1926 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1929 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1934 #include "MipsGenCallingConv.inc"
1937 AnalyzeMips64CallOperands(CCState CCInfo,
1938 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1939 unsigned NumOps = Outs.size();
1940 for (unsigned i = 0; i != NumOps; ++i) {
1941 MVT ArgVT = Outs[i].VT;
1942 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1945 if (Outs[i].IsFixed)
1946 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1948 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1952 dbgs() << "Call operand #" << i << " has unhandled type "
1953 << EVT(ArgVT).getEVTString();
1955 llvm_unreachable(0);
1960 //===----------------------------------------------------------------------===//
1961 // Call Calling Convention Implementation
1962 //===----------------------------------------------------------------------===//
1964 static const unsigned O32IntRegsSize = 4;
1966 static const unsigned O32IntRegs[] = {
1967 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1970 // Return next O32 integer argument register.
1971 static unsigned getNextIntArgReg(unsigned Reg) {
1972 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1973 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1976 // Write ByVal Arg to arg registers and stack.
1978 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1979 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1980 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1981 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1982 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1983 MVT PtrType, bool isLittle) {
1984 unsigned LocMemOffset = VA.getLocMemOffset();
1985 unsigned Offset = 0;
1986 uint32_t RemainingSize = Flags.getByValSize();
1987 unsigned ByValAlign = Flags.getByValAlign();
1989 // Copy the first 4 words of byval arg to registers A0 - A3.
1990 // FIXME: Use a stricter alignment if it enables better optimization in passes
1992 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1993 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1994 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1995 DAG.getConstant(Offset, MVT::i32));
1996 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1997 MachinePointerInfo(),
1998 false, false, false, std::min(ByValAlign,
2000 MemOpChains.push_back(LoadVal.getValue(1));
2001 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2002 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2005 if (RemainingSize == 0)
2008 // If there still is a register available for argument passing, write the
2009 // remaining part of the structure to it using subword loads and shifts.
2010 if (LocMemOffset < 4 * 4) {
2011 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2012 "There must be one to three bytes remaining.");
2013 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2014 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2015 DAG.getConstant(Offset, MVT::i32));
2016 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2017 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2018 LoadPtr, MachinePointerInfo(),
2019 MVT::getIntegerVT(LoadSize * 8), false,
2021 MemOpChains.push_back(LoadVal.getValue(1));
2023 // If target is big endian, shift it to the most significant half-word or
2026 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2027 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2030 RemainingSize -= LoadSize;
2032 // Read second subword if necessary.
2033 if (RemainingSize != 0) {
2034 assert(RemainingSize == 1 && "There must be one byte remaining.");
2035 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2036 DAG.getConstant(Offset, MVT::i32));
2037 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2038 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2039 LoadPtr, MachinePointerInfo(),
2040 MVT::i8, false, false, Alignment);
2041 MemOpChains.push_back(Subword.getValue(1));
2042 // Insert the loaded byte to LoadVal.
2043 // FIXME: Use INS if supported by target.
2044 unsigned ShiftAmt = isLittle ? 16 : 8;
2045 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2046 DAG.getConstant(ShiftAmt, MVT::i32));
2047 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2050 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2051 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2055 // Create a fixed object on stack at offset LocMemOffset and copy
2056 // remaining part of byval arg to it using memcpy.
2057 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2058 DAG.getConstant(Offset, MVT::i32));
2059 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2060 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2061 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2062 DAG.getConstant(RemainingSize, MVT::i32),
2063 std::min(ByValAlign, (unsigned)4),
2064 /*isVolatile=*/false, /*AlwaysInline=*/false,
2065 MachinePointerInfo(0), MachinePointerInfo(0));
2068 // Copy Mips64 byVal arg to registers and stack.
2070 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2071 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2072 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2073 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2074 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2075 EVT PtrTy, bool isLittle) {
2076 unsigned ByValSize = Flags.getByValSize();
2077 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2078 bool IsRegLoc = VA.isRegLoc();
2079 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2080 unsigned LocMemOffset = 0;
2081 unsigned MemCpySize = ByValSize;
2084 LocMemOffset = VA.getLocMemOffset();
2086 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2088 const unsigned *RegEnd = Mips64IntRegs + 8;
2090 // Copy double words to registers.
2091 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2092 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2093 DAG.getConstant(Offset, PtrTy));
2094 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2095 MachinePointerInfo(), false, false, false,
2097 MemOpChains.push_back(LoadVal.getValue(1));
2098 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2101 // Return if the struct has been fully copied.
2102 if (!(MemCpySize = ByValSize - Offset))
2105 // If there is an argument register available, copy the remainder of the
2106 // byval argument with sub-doubleword loads and shifts.
2107 if (Reg != RegEnd) {
2108 assert((ByValSize < Offset + 8) &&
2109 "Size of the remainder should be smaller than 8-byte.");
2111 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2112 unsigned RemSize = ByValSize - Offset;
2114 if (RemSize < LoadSize)
2117 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2118 DAG.getConstant(Offset, PtrTy));
2120 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2121 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2122 false, false, Alignment);
2123 MemOpChains.push_back(LoadVal.getValue(1));
2125 // Offset in number of bits from double word boundary.
2126 unsigned OffsetDW = (Offset % 8) * 8;
2127 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2128 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2129 DAG.getConstant(Shamt, MVT::i32));
2131 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2134 Alignment = std::min(Alignment, LoadSize);
2137 RegsToPass.push_back(std::make_pair(*Reg, Val));
2142 assert(MemCpySize && "MemCpySize must not be zero.");
2144 // Create a fixed object on stack at offset LocMemOffset and copy
2145 // remainder of byval arg to it with memcpy.
2146 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2147 DAG.getConstant(Offset, PtrTy));
2148 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2149 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2150 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2151 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2152 /*isVolatile=*/false, /*AlwaysInline=*/false,
2153 MachinePointerInfo(0), MachinePointerInfo(0));
2156 /// LowerCall - functions arguments are copied from virtual regs to
2157 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2158 /// TODO: isTailCall.
2160 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2161 CallingConv::ID CallConv, bool isVarArg,
2163 const SmallVectorImpl<ISD::OutputArg> &Outs,
2164 const SmallVectorImpl<SDValue> &OutVals,
2165 const SmallVectorImpl<ISD::InputArg> &Ins,
2166 DebugLoc dl, SelectionDAG &DAG,
2167 SmallVectorImpl<SDValue> &InVals) const {
2168 // MIPs target does not yet support tail call optimization.
2171 MachineFunction &MF = DAG.getMachineFunction();
2172 MachineFrameInfo *MFI = MF.getFrameInfo();
2173 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2174 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2175 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2177 // Analyze operands of the call, assigning locations to each operand.
2178 SmallVector<CCValAssign, 16> ArgLocs;
2179 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2180 getTargetMachine(), ArgLocs, *DAG.getContext());
2183 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2185 AnalyzeMips64CallOperands(CCInfo, Outs);
2187 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2189 // Get a count of how many bytes are to be pushed on the stack.
2190 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2192 // Chain is the output chain of the last Load/Store or CopyToReg node.
2193 // ByValChain is the output chain of the last Memcpy node created for copying
2194 // byval arguments to the stack.
2195 SDValue Chain, CallSeqStart, ByValChain;
2196 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2197 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2198 ByValChain = InChain;
2200 // If this is the first call, create a stack frame object that points to
2201 // a location to which .cprestore saves $gp.
2202 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2203 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2205 // Get the frame index of the stack frame object that points to the location
2206 // of dynamically allocated area on the stack.
2207 int DynAllocFI = MipsFI->getDynAllocFI();
2209 // Update size of the maximum argument space.
2210 // For O32, a minimum of four words (16 bytes) of argument space is
2213 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2215 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2217 if (MaxCallFrameSize < NextStackOffset) {
2218 MipsFI->setMaxCallFrameSize(NextStackOffset);
2220 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2221 // allocated stack space. These offsets must be aligned to a boundary
2222 // determined by the stack alignment of the ABI.
2223 unsigned StackAlignment = TFL->getStackAlignment();
2224 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2225 StackAlignment * StackAlignment;
2227 if (MipsFI->needGPSaveRestore())
2228 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2230 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2233 // With EABI is it possible to have 16 args on registers.
2234 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2235 SmallVector<SDValue, 8> MemOpChains;
2237 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2239 // Walk the register/memloc assignments, inserting copies/loads.
2240 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2241 SDValue Arg = OutVals[i];
2242 CCValAssign &VA = ArgLocs[i];
2243 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2244 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2247 if (Flags.isByVal()) {
2248 assert(Flags.getByValSize() &&
2249 "ByVal args of size 0 should have been ignored by front-end.");
2251 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2252 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2253 Subtarget->isLittle());
2255 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2256 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2257 Subtarget->isLittle());
2261 // Promote the value if needed.
2262 switch (VA.getLocInfo()) {
2263 default: llvm_unreachable("Unknown loc info!");
2264 case CCValAssign::Full:
2265 if (VA.isRegLoc()) {
2266 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2267 (ValVT == MVT::f64 && LocVT == MVT::i64))
2268 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2269 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2270 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2271 Arg, DAG.getConstant(0, MVT::i32));
2272 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2273 Arg, DAG.getConstant(1, MVT::i32));
2274 if (!Subtarget->isLittle())
2276 unsigned LocRegLo = VA.getLocReg();
2277 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2278 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2279 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2284 case CCValAssign::SExt:
2285 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2287 case CCValAssign::ZExt:
2288 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2290 case CCValAssign::AExt:
2291 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2295 // Arguments that can be passed on register must be kept at
2296 // RegsToPass vector
2297 if (VA.isRegLoc()) {
2298 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2302 // Register can't get to this point...
2303 assert(VA.isMemLoc());
2305 // Create the frame index object for this incoming parameter
2306 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2307 VA.getLocMemOffset(), true);
2308 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2310 // emit ISD::STORE whichs stores the
2311 // parameter value to a stack Location
2312 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2313 MachinePointerInfo(),
2317 // Extend range of indices of frame objects for outgoing arguments that were
2318 // created during this function call. Skip this step if no such objects were
2321 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2323 // If a memcpy has been created to copy a byval arg to a stack, replace the
2324 // chain input of CallSeqStart with ByValChain.
2325 if (InChain != ByValChain)
2326 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2327 NextStackOffsetVal);
2329 // Transform all store nodes into one single node because all store
2330 // nodes are independent of each other.
2331 if (!MemOpChains.empty())
2332 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2333 &MemOpChains[0], MemOpChains.size());
2335 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2336 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2337 // node so that legalize doesn't hack it.
2338 unsigned char OpFlag;
2339 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2340 bool GlobalOrExternal = false;
2343 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2344 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2345 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2346 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2347 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2349 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2352 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2353 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2354 getPointerTy(), 0, OpFlag);
2357 GlobalOrExternal = true;
2359 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2360 if (IsN64 || (!IsO32 && IsPIC))
2361 OpFlag = MipsII::MO_GOT_DISP;
2362 else if (!IsPIC) // !N64 && static
2363 OpFlag = MipsII::MO_NO_FLAG;
2365 OpFlag = MipsII::MO_GOT_CALL;
2366 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2367 getPointerTy(), OpFlag);
2368 GlobalOrExternal = true;
2373 // Create nodes that load address of callee and copy it to T9
2375 if (GlobalOrExternal) {
2376 // Load callee address
2377 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(), Callee);
2378 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2379 Callee, MachinePointerInfo::getGOT(),
2380 false, false, false, 0);
2382 // Use GOT+LO if callee has internal linkage.
2383 if (CalleeLo.getNode()) {
2384 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2385 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2391 // T9 should contain the address of the callee function if
2392 // -reloction-model=pic or it is an indirect call.
2393 if (IsPICCall || !GlobalOrExternal) {
2395 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2396 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2397 InFlag = Chain.getValue(1);
2398 Callee = DAG.getRegister(T9Reg, getPointerTy());
2401 // Build a sequence of copy-to-reg nodes chained together with token
2402 // chain and flag operands which copy the outgoing args into registers.
2403 // The InFlag in necessary since all emitted instructions must be
2405 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2406 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2407 RegsToPass[i].second, InFlag);
2408 InFlag = Chain.getValue(1);
2411 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2412 // = Chain, Callee, Reg#1, Reg#2, ...
2414 // Returns a chain & a flag for retval copy to use.
2415 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2416 SmallVector<SDValue, 8> Ops;
2417 Ops.push_back(Chain);
2418 Ops.push_back(Callee);
2420 // Add argument registers to the end of the list so that they are
2421 // known live into the call.
2422 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2423 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2424 RegsToPass[i].second.getValueType()));
2426 if (InFlag.getNode())
2427 Ops.push_back(InFlag);
2429 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2430 InFlag = Chain.getValue(1);
2432 // Create the CALLSEQ_END node.
2433 Chain = DAG.getCALLSEQ_END(Chain,
2434 DAG.getIntPtrConstant(NextStackOffset, true),
2435 DAG.getIntPtrConstant(0, true), InFlag);
2436 InFlag = Chain.getValue(1);
2438 // Handle result values, copying them out of physregs into vregs that we
2440 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2441 Ins, dl, DAG, InVals);
2444 /// LowerCallResult - Lower the result values of a call into the
2445 /// appropriate copies out of appropriate physical registers.
2447 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2448 CallingConv::ID CallConv, bool isVarArg,
2449 const SmallVectorImpl<ISD::InputArg> &Ins,
2450 DebugLoc dl, SelectionDAG &DAG,
2451 SmallVectorImpl<SDValue> &InVals) const {
2452 // Assign locations to each value returned by this call.
2453 SmallVector<CCValAssign, 16> RVLocs;
2454 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2455 getTargetMachine(), RVLocs, *DAG.getContext());
2457 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2459 // Copy all of the result registers out of their specified physreg.
2460 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2461 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2462 RVLocs[i].getValVT(), InFlag).getValue(1);
2463 InFlag = Chain.getValue(2);
2464 InVals.push_back(Chain.getValue(0));
2470 //===----------------------------------------------------------------------===//
2471 // Formal Arguments Calling Convention Implementation
2472 //===----------------------------------------------------------------------===//
2473 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2474 std::vector<SDValue>& OutChains,
2475 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2476 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2477 unsigned LocMem = VA.getLocMemOffset();
2478 unsigned FirstWord = LocMem / 4;
2480 // copy register A0 - A3 to frame object
2481 for (unsigned i = 0; i < NumWords; ++i) {
2482 unsigned CurWord = FirstWord + i;
2483 if (CurWord >= O32IntRegsSize)
2486 unsigned SrcReg = O32IntRegs[CurWord];
2487 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2488 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2489 DAG.getConstant(i * 4, MVT::i32));
2490 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2491 StorePtr, MachinePointerInfo(), false,
2493 OutChains.push_back(Store);
2497 // Create frame object on stack and copy registers used for byval passing to it.
2499 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2500 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2501 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2502 MachineFrameInfo *MFI, bool IsRegLoc,
2503 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2505 const unsigned *Reg = Mips64IntRegs + 8;
2506 int FOOffset; // Frame object offset from virtual frame pointer.
2509 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2510 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2513 FOOffset = VA.getLocMemOffset();
2515 // Create frame object.
2516 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2517 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2518 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2519 InVals.push_back(FIN);
2521 // Copy arg registers.
2522 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2524 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2525 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2526 DAG.getConstant(I * 8, PtrTy));
2527 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2528 StorePtr, MachinePointerInfo(), false,
2530 OutChains.push_back(Store);
2536 /// LowerFormalArguments - transform physical registers into virtual registers
2537 /// and generate load operations for arguments places on the stack.
2539 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2540 CallingConv::ID CallConv,
2542 const SmallVectorImpl<ISD::InputArg>
2544 DebugLoc dl, SelectionDAG &DAG,
2545 SmallVectorImpl<SDValue> &InVals)
2547 MachineFunction &MF = DAG.getMachineFunction();
2548 MachineFrameInfo *MFI = MF.getFrameInfo();
2549 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2551 MipsFI->setVarArgsFrameIndex(0);
2553 // Used with vargs to acumulate store chains.
2554 std::vector<SDValue> OutChains;
2556 // Assign locations to all of the incoming arguments.
2557 SmallVector<CCValAssign, 16> ArgLocs;
2558 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2559 getTargetMachine(), ArgLocs, *DAG.getContext());
2562 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2564 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2566 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2568 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2569 CCValAssign &VA = ArgLocs[i];
2570 EVT ValVT = VA.getValVT();
2571 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2572 bool IsRegLoc = VA.isRegLoc();
2574 if (Flags.isByVal()) {
2575 assert(Flags.getByValSize() &&
2576 "ByVal args of size 0 should have been ignored by front-end.");
2578 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2579 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2581 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2582 InVals.push_back(FIN);
2583 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2585 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2586 MFI, IsRegLoc, InVals, MipsFI,
2591 // Arguments stored on registers
2593 EVT RegVT = VA.getLocVT();
2594 unsigned ArgReg = VA.getLocReg();
2595 TargetRegisterClass *RC = 0;
2597 if (RegVT == MVT::i32)
2598 RC = Mips::CPURegsRegisterClass;
2599 else if (RegVT == MVT::i64)
2600 RC = Mips::CPU64RegsRegisterClass;
2601 else if (RegVT == MVT::f32)
2602 RC = Mips::FGR32RegisterClass;
2603 else if (RegVT == MVT::f64)
2604 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2606 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2608 // Transform the arguments stored on
2609 // physical registers into virtual ones
2610 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2611 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2613 // If this is an 8 or 16-bit value, it has been passed promoted
2614 // to 32 bits. Insert an assert[sz]ext to capture this, then
2615 // truncate to the right size.
2616 if (VA.getLocInfo() != CCValAssign::Full) {
2617 unsigned Opcode = 0;
2618 if (VA.getLocInfo() == CCValAssign::SExt)
2619 Opcode = ISD::AssertSext;
2620 else if (VA.getLocInfo() == CCValAssign::ZExt)
2621 Opcode = ISD::AssertZext;
2623 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2624 DAG.getValueType(ValVT));
2625 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2628 // Handle floating point arguments passed in integer registers.
2629 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2630 (RegVT == MVT::i64 && ValVT == MVT::f64))
2631 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2632 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2633 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2634 getNextIntArgReg(ArgReg), RC);
2635 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2636 if (!Subtarget->isLittle())
2637 std::swap(ArgValue, ArgValue2);
2638 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2639 ArgValue, ArgValue2);
2642 InVals.push_back(ArgValue);
2643 } else { // VA.isRegLoc()
2646 assert(VA.isMemLoc());
2648 // The stack pointer offset is relative to the caller stack frame.
2649 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2650 VA.getLocMemOffset(), true);
2652 // Create load nodes to retrieve arguments from the stack
2653 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2654 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2655 MachinePointerInfo::getFixedStack(LastFI),
2656 false, false, false, 0));
2660 // The mips ABIs for returning structs by value requires that we copy
2661 // the sret argument into $v0 for the return. Save the argument into
2662 // a virtual register so that we can access it from the return points.
2663 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2664 unsigned Reg = MipsFI->getSRetReturnReg();
2666 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2667 MipsFI->setSRetReturnReg(Reg);
2669 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2670 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2674 unsigned NumOfRegs = IsO32 ? 4 : 8;
2675 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2676 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2677 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2678 TargetRegisterClass *RC
2679 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2680 unsigned RegSize = RC->getSize();
2681 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2683 // Offset of the first variable argument from stack pointer.
2684 int FirstVaArgOffset;
2686 if (IsO32 || (Idx == NumOfRegs)) {
2688 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2690 FirstVaArgOffset = RegSlotOffset;
2692 // Record the frame index of the first variable argument
2693 // which is a value necessary to VASTART.
2694 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2695 MipsFI->setVarArgsFrameIndex(LastFI);
2697 // Copy the integer registers that have not been used for argument passing
2698 // to the argument register save area. For O32, the save area is allocated
2699 // in the caller's stack frame, while for N32/64, it is allocated in the
2700 // callee's stack frame.
2701 for (int StackOffset = RegSlotOffset;
2702 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2703 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2704 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2705 MVT::getIntegerVT(RegSize * 8));
2706 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2707 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2708 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2709 MachinePointerInfo(),
2714 MipsFI->setLastInArgFI(LastFI);
2716 // All stores are grouped in one node to allow the matching between
2717 // the size of Ins and InVals. This only happens when on varg functions
2718 if (!OutChains.empty()) {
2719 OutChains.push_back(Chain);
2720 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2721 &OutChains[0], OutChains.size());
2727 //===----------------------------------------------------------------------===//
2728 // Return Value Calling Convention Implementation
2729 //===----------------------------------------------------------------------===//
2732 MipsTargetLowering::LowerReturn(SDValue Chain,
2733 CallingConv::ID CallConv, bool isVarArg,
2734 const SmallVectorImpl<ISD::OutputArg> &Outs,
2735 const SmallVectorImpl<SDValue> &OutVals,
2736 DebugLoc dl, SelectionDAG &DAG) const {
2738 // CCValAssign - represent the assignment of
2739 // the return value to a location
2740 SmallVector<CCValAssign, 16> RVLocs;
2742 // CCState - Info about the registers and stack slot.
2743 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2744 getTargetMachine(), RVLocs, *DAG.getContext());
2746 // Analize return values.
2747 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2749 // If this is the first return lowered for this function, add
2750 // the regs to the liveout set for the function.
2751 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2752 for (unsigned i = 0; i != RVLocs.size(); ++i)
2753 if (RVLocs[i].isRegLoc())
2754 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2759 // Copy the result values into the output registers.
2760 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2761 CCValAssign &VA = RVLocs[i];
2762 assert(VA.isRegLoc() && "Can only return in registers!");
2764 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2767 // guarantee that all emitted copies are
2768 // stuck together, avoiding something bad
2769 Flag = Chain.getValue(1);
2772 // The mips ABIs for returning structs by value requires that we copy
2773 // the sret argument into $v0 for the return. We saved the argument into
2774 // a virtual register in the entry block, so now we copy the value out
2776 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2777 MachineFunction &MF = DAG.getMachineFunction();
2778 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2779 unsigned Reg = MipsFI->getSRetReturnReg();
2782 llvm_unreachable("sret virtual register not created in the entry block");
2783 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2785 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2786 Flag = Chain.getValue(1);
2789 // Return on Mips is always a "jr $ra"
2791 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2792 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2794 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2795 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2798 //===----------------------------------------------------------------------===//
2799 // Mips Inline Assembly Support
2800 //===----------------------------------------------------------------------===//
2802 /// getConstraintType - Given a constraint letter, return the type of
2803 /// constraint it is for this target.
2804 MipsTargetLowering::ConstraintType MipsTargetLowering::
2805 getConstraintType(const std::string &Constraint) const
2807 // Mips specific constrainy
2808 // GCC config/mips/constraints.md
2810 // 'd' : An address register. Equivalent to r
2811 // unless generating MIPS16 code.
2812 // 'y' : Equivalent to r; retained for
2813 // backwards compatibility.
2814 // 'f' : Floating Point registers.
2815 if (Constraint.size() == 1) {
2816 switch (Constraint[0]) {
2821 return C_RegisterClass;
2825 return TargetLowering::getConstraintType(Constraint);
2828 /// Examine constraint type and operand type and determine a weight value.
2829 /// This object must already have been set up with the operand type
2830 /// and the current alternative constraint selected.
2831 TargetLowering::ConstraintWeight
2832 MipsTargetLowering::getSingleConstraintMatchWeight(
2833 AsmOperandInfo &info, const char *constraint) const {
2834 ConstraintWeight weight = CW_Invalid;
2835 Value *CallOperandVal = info.CallOperandVal;
2836 // If we don't have a value, we can't do a match,
2837 // but allow it at the lowest weight.
2838 if (CallOperandVal == NULL)
2840 Type *type = CallOperandVal->getType();
2841 // Look at the constraint type.
2842 switch (*constraint) {
2844 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2848 if (type->isIntegerTy())
2849 weight = CW_Register;
2852 if (type->isFloatTy())
2853 weight = CW_Register;
2859 /// Given a register class constraint, like 'r', if this corresponds directly
2860 /// to an LLVM register class, return a register of 0 and the register class
2862 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2863 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2865 if (Constraint.size() == 1) {
2866 switch (Constraint[0]) {
2867 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2868 case 'y': // Same as 'r'. Exists for compatibility.
2870 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2873 return std::make_pair(0U, Mips::FGR32RegisterClass);
2875 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2876 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2880 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2884 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2885 // The Mips target isn't yet aware of offsets.
2889 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2890 if (VT != MVT::f32 && VT != MVT::f64)
2892 if (Imm.isNegZero())
2894 return Imm.isZero();