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 "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
38 // If I is a shifted mask, set the size (Size) and the first bit of the
39 // mask (Pos), and return true.
40 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
41 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
42 if (!isUInt<32>(I) || !isShiftedMask_32(I))
45 Size = CountPopulation_32(I);
46 Pos = CountTrailingZeros_32(I);
50 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
52 case MipsISD::JmpLink: return "MipsISD::JmpLink";
53 case MipsISD::Hi: return "MipsISD::Hi";
54 case MipsISD::Lo: return "MipsISD::Lo";
55 case MipsISD::GPRel: return "MipsISD::GPRel";
56 case MipsISD::TlsGd: return "MipsISD::TlsGd";
57 case MipsISD::TprelHi: return "MipsISD::TprelHi";
58 case MipsISD::TprelLo: return "MipsISD::TprelLo";
59 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
60 case MipsISD::Ret: return "MipsISD::Ret";
61 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
62 case MipsISD::FPCmp: return "MipsISD::FPCmp";
63 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
64 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
65 case MipsISD::FPRound: return "MipsISD::FPRound";
66 case MipsISD::MAdd: return "MipsISD::MAdd";
67 case MipsISD::MAddu: return "MipsISD::MAddu";
68 case MipsISD::MSub: return "MipsISD::MSub";
69 case MipsISD::MSubu: return "MipsISD::MSubu";
70 case MipsISD::DivRem: return "MipsISD::DivRem";
71 case MipsISD::DivRemU: return "MipsISD::DivRemU";
72 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
73 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
74 case MipsISD::WrapperPIC: return "MipsISD::WrapperPIC";
75 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
76 case MipsISD::Sync: return "MipsISD::Sync";
77 case MipsISD::Ext: return "MipsISD::Ext";
78 case MipsISD::Ins: return "MipsISD::Ins";
84 MipsTargetLowering(MipsTargetMachine &TM)
85 : TargetLowering(TM, new MipsTargetObjectFile()),
86 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
87 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
88 IsO32(Subtarget->isABI_O32()) {
90 // Mips does not have i1 type, so use i32 for
91 // setcc operations results (slt, sgt, ...).
92 setBooleanContents(ZeroOrOneBooleanContent);
93 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
95 // Set up the register classes
96 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
97 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
100 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
102 // When dealing with single precision only, use libcalls
103 if (!Subtarget->isSingleFloat()) {
105 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
107 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
110 // Load extented operations for i1 types must be promoted
111 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
112 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
113 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
115 // MIPS doesn't have extending float->double load/store
116 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
117 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
119 // Used by legalize types to correctly generate the setcc result.
120 // Without this, every float setcc comes with a AND/OR with the result,
121 // we don't want this, since the fpcmp result goes to a flag register,
122 // which is used implicitly by brcond and select operations.
123 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
125 // Mips Custom Operations
126 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
127 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
128 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
129 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
130 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
132 setOperationAction(ISD::SELECT, MVT::f32, Custom);
133 setOperationAction(ISD::SELECT, MVT::f64, Custom);
134 setOperationAction(ISD::SELECT, MVT::i32, Custom);
135 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
136 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
137 setOperationAction(ISD::VASTART, MVT::Other, Custom);
139 setOperationAction(ISD::SDIV, MVT::i32, Expand);
140 setOperationAction(ISD::SREM, MVT::i32, Expand);
141 setOperationAction(ISD::UDIV, MVT::i32, Expand);
142 setOperationAction(ISD::UREM, MVT::i32, Expand);
143 setOperationAction(ISD::SDIV, MVT::i64, Expand);
144 setOperationAction(ISD::SREM, MVT::i64, Expand);
145 setOperationAction(ISD::UDIV, MVT::i64, Expand);
146 setOperationAction(ISD::UREM, MVT::i64, Expand);
148 // Operations not directly supported by Mips.
149 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
150 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
151 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
152 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
153 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
154 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
155 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
156 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
157 setOperationAction(ISD::ROTL, MVT::i32, Expand);
158 setOperationAction(ISD::ROTL, MVT::i64, Expand);
160 if (!Subtarget->hasMips32r2())
161 setOperationAction(ISD::ROTR, MVT::i32, Expand);
163 if (!Subtarget->hasMips64r2())
164 setOperationAction(ISD::ROTR, MVT::i64, Expand);
166 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
167 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
168 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
169 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
170 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
171 setOperationAction(ISD::FSIN, MVT::f32, Expand);
172 setOperationAction(ISD::FSIN, MVT::f64, Expand);
173 setOperationAction(ISD::FCOS, MVT::f32, Expand);
174 setOperationAction(ISD::FCOS, MVT::f64, Expand);
175 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
176 setOperationAction(ISD::FPOW, MVT::f32, Expand);
177 setOperationAction(ISD::FPOW, MVT::f64, Expand);
178 setOperationAction(ISD::FLOG, MVT::f32, Expand);
179 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
180 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
181 setOperationAction(ISD::FEXP, MVT::f32, Expand);
182 setOperationAction(ISD::FMA, MVT::f32, Expand);
183 setOperationAction(ISD::FMA, MVT::f64, Expand);
185 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
186 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
188 setOperationAction(ISD::VAARG, MVT::Other, Expand);
189 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190 setOperationAction(ISD::VAEND, MVT::Other, Expand);
192 // Use the default for now
193 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
194 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
196 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
197 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
199 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
200 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
202 setInsertFencesForAtomic(true);
204 if (Subtarget->isSingleFloat())
205 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
207 if (!Subtarget->hasSEInReg()) {
208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
212 if (!Subtarget->hasBitCount())
213 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
215 if (!Subtarget->hasSwap())
216 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
218 setTargetDAGCombine(ISD::ADDE);
219 setTargetDAGCombine(ISD::SUBE);
220 setTargetDAGCombine(ISD::SDIVREM);
221 setTargetDAGCombine(ISD::UDIVREM);
222 setTargetDAGCombine(ISD::SETCC);
223 setTargetDAGCombine(ISD::AND);
224 setTargetDAGCombine(ISD::OR);
226 setMinFunctionAlignment(2);
228 setStackPointerRegisterToSaveRestore(Mips::SP);
229 computeRegisterProperties();
231 setExceptionPointerRegister(Mips::A0);
232 setExceptionSelectorRegister(Mips::A1);
235 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
236 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
237 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
240 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
245 // Transforms a subgraph in CurDAG if the following pattern is found:
246 // (addc multLo, Lo0), (adde multHi, Hi0),
248 // multHi/Lo: product of multiplication
249 // Lo0: initial value of Lo register
250 // Hi0: initial value of Hi register
251 // Return true if pattern matching was successful.
252 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
253 // ADDENode's second operand must be a flag output of an ADDC node in order
254 // for the matching to be successful.
255 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
257 if (ADDCNode->getOpcode() != ISD::ADDC)
260 SDValue MultHi = ADDENode->getOperand(0);
261 SDValue MultLo = ADDCNode->getOperand(0);
262 SDNode* MultNode = MultHi.getNode();
263 unsigned MultOpc = MultHi.getOpcode();
265 // MultHi and MultLo must be generated by the same node,
266 if (MultLo.getNode() != MultNode)
269 // and it must be a multiplication.
270 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
273 // MultLo amd MultHi must be the first and second output of MultNode
275 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
278 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
279 // of the values of MultNode, in which case MultNode will be removed in later
281 // If there exist users other than ADDENode or ADDCNode, this function returns
282 // here, which will result in MultNode being mapped to a single MULT
283 // instruction node rather than a pair of MULT and MADD instructions being
285 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
288 SDValue Chain = CurDAG->getEntryNode();
289 DebugLoc dl = ADDENode->getDebugLoc();
291 // create MipsMAdd(u) node
292 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
294 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
296 MultNode->getOperand(0),// Factor 0
297 MultNode->getOperand(1),// Factor 1
298 ADDCNode->getOperand(1),// Lo0
299 ADDENode->getOperand(1));// Hi0
301 // create CopyFromReg nodes
302 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
304 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
306 CopyFromLo.getValue(2));
308 // replace uses of adde and addc here
309 if (!SDValue(ADDCNode, 0).use_empty())
310 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
312 if (!SDValue(ADDENode, 0).use_empty())
313 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
319 // Transforms a subgraph in CurDAG if the following pattern is found:
320 // (addc Lo0, multLo), (sube Hi0, multHi),
322 // multHi/Lo: product of multiplication
323 // Lo0: initial value of Lo register
324 // Hi0: initial value of Hi register
325 // Return true if pattern matching was successful.
326 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
327 // SUBENode's second operand must be a flag output of an SUBC node in order
328 // for the matching to be successful.
329 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
331 if (SUBCNode->getOpcode() != ISD::SUBC)
334 SDValue MultHi = SUBENode->getOperand(1);
335 SDValue MultLo = SUBCNode->getOperand(1);
336 SDNode* MultNode = MultHi.getNode();
337 unsigned MultOpc = MultHi.getOpcode();
339 // MultHi and MultLo must be generated by the same node,
340 if (MultLo.getNode() != MultNode)
343 // and it must be a multiplication.
344 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
347 // MultLo amd MultHi must be the first and second output of MultNode
349 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
352 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
353 // of the values of MultNode, in which case MultNode will be removed in later
355 // If there exist users other than SUBENode or SUBCNode, this function returns
356 // here, which will result in MultNode being mapped to a single MULT
357 // instruction node rather than a pair of MULT and MSUB instructions being
359 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
362 SDValue Chain = CurDAG->getEntryNode();
363 DebugLoc dl = SUBENode->getDebugLoc();
365 // create MipsSub(u) node
366 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
368 SDValue MSub = CurDAG->getNode(MultOpc, dl,
370 MultNode->getOperand(0),// Factor 0
371 MultNode->getOperand(1),// Factor 1
372 SUBCNode->getOperand(0),// Lo0
373 SUBENode->getOperand(0));// Hi0
375 // create CopyFromReg nodes
376 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
378 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
380 CopyFromLo.getValue(2));
382 // replace uses of sube and subc here
383 if (!SDValue(SUBCNode, 0).use_empty())
384 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
386 if (!SDValue(SUBENode, 0).use_empty())
387 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
392 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
393 TargetLowering::DAGCombinerInfo &DCI,
394 const MipsSubtarget* Subtarget) {
395 if (DCI.isBeforeLegalize())
398 if (Subtarget->hasMips32() && SelectMadd(N, &DAG))
399 return SDValue(N, 0);
404 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
405 TargetLowering::DAGCombinerInfo &DCI,
406 const MipsSubtarget* Subtarget) {
407 if (DCI.isBeforeLegalize())
410 if (Subtarget->hasMips32() && SelectMsub(N, &DAG))
411 return SDValue(N, 0);
416 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
417 TargetLowering::DAGCombinerInfo &DCI,
418 const MipsSubtarget* Subtarget) {
419 if (DCI.isBeforeLegalizeOps())
422 EVT Ty = N->getValueType(0);
423 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
424 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
425 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
427 DebugLoc dl = N->getDebugLoc();
429 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
430 N->getOperand(0), N->getOperand(1));
431 SDValue InChain = DAG.getEntryNode();
432 SDValue InGlue = DivRem;
435 if (N->hasAnyUseOfValue(0)) {
436 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
438 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
439 InChain = CopyFromLo.getValue(1);
440 InGlue = CopyFromLo.getValue(2);
444 if (N->hasAnyUseOfValue(1)) {
445 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
453 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
455 default: llvm_unreachable("Unknown fp condition code!");
457 case ISD::SETOEQ: return Mips::FCOND_OEQ;
458 case ISD::SETUNE: return Mips::FCOND_UNE;
460 case ISD::SETOLT: return Mips::FCOND_OLT;
462 case ISD::SETOGT: return Mips::FCOND_OGT;
464 case ISD::SETOLE: return Mips::FCOND_OLE;
466 case ISD::SETOGE: return Mips::FCOND_OGE;
467 case ISD::SETULT: return Mips::FCOND_ULT;
468 case ISD::SETULE: return Mips::FCOND_ULE;
469 case ISD::SETUGT: return Mips::FCOND_UGT;
470 case ISD::SETUGE: return Mips::FCOND_UGE;
471 case ISD::SETUO: return Mips::FCOND_UN;
472 case ISD::SETO: return Mips::FCOND_OR;
474 case ISD::SETONE: return Mips::FCOND_ONE;
475 case ISD::SETUEQ: return Mips::FCOND_UEQ;
480 // Returns true if condition code has to be inverted.
481 static bool InvertFPCondCode(Mips::CondCode CC) {
482 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
485 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
488 assert(false && "Illegal Condition Code");
492 // Creates and returns an FPCmp node from a setcc node.
493 // Returns Op if setcc is not a floating point comparison.
494 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
495 // must be a SETCC node
496 if (Op.getOpcode() != ISD::SETCC)
499 SDValue LHS = Op.getOperand(0);
501 if (!LHS.getValueType().isFloatingPoint())
504 SDValue RHS = Op.getOperand(1);
505 DebugLoc dl = Op.getDebugLoc();
507 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
508 // node if necessary.
509 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
511 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
512 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
515 // Creates and returns a CMovFPT/F node.
516 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
517 SDValue False, DebugLoc DL) {
518 bool invert = InvertFPCondCode((Mips::CondCode)
519 cast<ConstantSDNode>(Cond.getOperand(2))
522 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
523 True.getValueType(), True, False, Cond);
526 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
527 TargetLowering::DAGCombinerInfo &DCI,
528 const MipsSubtarget* Subtarget) {
529 if (DCI.isBeforeLegalizeOps())
532 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
534 if (Cond.getOpcode() != MipsISD::FPCmp)
537 SDValue True = DAG.getConstant(1, MVT::i32);
538 SDValue False = DAG.getConstant(0, MVT::i32);
540 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
543 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
544 TargetLowering::DAGCombinerInfo &DCI,
545 const MipsSubtarget* Subtarget) {
546 // Pattern match EXT.
547 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
548 // => ext $dst, $src, size, pos
549 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
552 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
554 // Op's first operand must be a shift right.
555 if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
558 // The second operand of the shift must be an immediate.
561 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
564 Pos = CN->getZExtValue();
566 uint64_t SMPos, SMSize;
567 // Op's second operand must be a shifted mask.
568 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
569 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
572 // Return if the shifted mask does not start at bit 0 or the sum of its size
573 // and Pos exceeds the word's size.
574 if (SMPos != 0 || Pos + SMSize > 32)
577 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
578 ShiftRight.getOperand(0),
579 DAG.getConstant(Pos, MVT::i32),
580 DAG.getConstant(SMSize, MVT::i32));
583 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
584 TargetLowering::DAGCombinerInfo &DCI,
585 const MipsSubtarget* Subtarget) {
586 // Pattern match INS.
587 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
588 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
589 // => ins $dst, $src, size, pos, $src1
590 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
593 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
594 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
597 // See if Op's first operand matches (and $src1 , mask0).
598 if (And0.getOpcode() != ISD::AND)
601 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
602 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
605 // See if Op's second operand matches (and (shl $src, pos), mask1).
606 if (And1.getOpcode() != ISD::AND)
609 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
610 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
613 // The shift masks must have the same position and size.
614 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
617 SDValue Shl = And1.getOperand(0);
618 if (Shl.getOpcode() != ISD::SHL)
621 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
624 unsigned Shamt = CN->getZExtValue();
626 // Return if the shift amount and the first bit position of mask are not the
631 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
633 DAG.getConstant(SMPos0, MVT::i32),
634 DAG.getConstant(SMSize0, MVT::i32),
638 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
640 SelectionDAG &DAG = DCI.DAG;
641 unsigned opc = N->getOpcode();
646 return PerformADDECombine(N, DAG, DCI, Subtarget);
648 return PerformSUBECombine(N, DAG, DCI, Subtarget);
651 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
653 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
655 return PerformANDCombine(N, DAG, DCI, Subtarget);
657 return PerformORCombine(N, DAG, DCI, Subtarget);
663 SDValue MipsTargetLowering::
664 LowerOperation(SDValue Op, SelectionDAG &DAG) const
666 switch (Op.getOpcode())
668 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
669 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
670 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
671 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
672 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
673 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
674 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
675 case ISD::SELECT: return LowerSELECT(Op, DAG);
676 case ISD::VASTART: return LowerVASTART(Op, DAG);
677 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
678 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
679 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
680 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
685 //===----------------------------------------------------------------------===//
686 // Lower helper functions
687 //===----------------------------------------------------------------------===//
689 // AddLiveIn - This helper function adds the specified physical register to the
690 // MachineFunction as a live in value. It also creates a corresponding
691 // virtual register for it.
693 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
695 assert(RC->contains(PReg) && "Not the correct regclass!");
696 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
697 MF.getRegInfo().addLiveIn(PReg, VReg);
701 // Get fp branch code (not opcode) from condition code.
702 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
703 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
704 return Mips::BRANCH_T;
706 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
707 return Mips::BRANCH_F;
709 return Mips::BRANCH_INVALID;
713 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
715 const MipsSubtarget* Subtarget,
716 const TargetInstrInfo *TII,
717 bool isFPCmp, unsigned Opc) {
718 // There is no need to expand CMov instructions if target has
719 // conditional moves.
720 if (Subtarget->hasCondMov())
723 // To "insert" a SELECT_CC instruction, we actually have to insert the
724 // diamond control-flow pattern. The incoming instruction knows the
725 // destination vreg to set, the condition code register to branch on, the
726 // true/false values to select between, and a branch opcode to use.
727 const BasicBlock *LLVM_BB = BB->getBasicBlock();
728 MachineFunction::iterator It = BB;
735 // bNE r1, r0, copy1MBB
736 // fallthrough --> copy0MBB
737 MachineBasicBlock *thisMBB = BB;
738 MachineFunction *F = BB->getParent();
739 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
740 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
741 F->insert(It, copy0MBB);
742 F->insert(It, sinkMBB);
744 // Transfer the remainder of BB and its successor edges to sinkMBB.
745 sinkMBB->splice(sinkMBB->begin(), BB,
746 llvm::next(MachineBasicBlock::iterator(MI)),
748 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
750 // Next, add the true and fallthrough blocks as its successors.
751 BB->addSuccessor(copy0MBB);
752 BB->addSuccessor(sinkMBB);
754 // Emit the right instruction according to the type of the operands compared
756 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
758 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
759 .addReg(Mips::ZERO).addMBB(sinkMBB);
763 // # fallthrough to sinkMBB
766 // Update machine-CFG edges
767 BB->addSuccessor(sinkMBB);
770 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
775 BuildMI(*BB, BB->begin(), dl,
776 TII->get(Mips::PHI), MI->getOperand(0).getReg())
777 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
778 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
780 BuildMI(*BB, BB->begin(), dl,
781 TII->get(Mips::PHI), MI->getOperand(0).getReg())
782 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
783 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
785 MI->eraseFromParent(); // The pseudo instruction is gone now.
790 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
791 MachineBasicBlock *BB) const {
792 switch (MI->getOpcode()) {
794 assert(false && "Unexpected instr type to insert");
796 case Mips::ATOMIC_LOAD_ADD_I8:
797 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
798 case Mips::ATOMIC_LOAD_ADD_I16:
799 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
800 case Mips::ATOMIC_LOAD_ADD_I32:
801 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
803 case Mips::ATOMIC_LOAD_AND_I8:
804 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
805 case Mips::ATOMIC_LOAD_AND_I16:
806 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
807 case Mips::ATOMIC_LOAD_AND_I32:
808 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
810 case Mips::ATOMIC_LOAD_OR_I8:
811 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
812 case Mips::ATOMIC_LOAD_OR_I16:
813 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
814 case Mips::ATOMIC_LOAD_OR_I32:
815 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
817 case Mips::ATOMIC_LOAD_XOR_I8:
818 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
819 case Mips::ATOMIC_LOAD_XOR_I16:
820 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
821 case Mips::ATOMIC_LOAD_XOR_I32:
822 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
824 case Mips::ATOMIC_LOAD_NAND_I8:
825 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
826 case Mips::ATOMIC_LOAD_NAND_I16:
827 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
828 case Mips::ATOMIC_LOAD_NAND_I32:
829 return EmitAtomicBinary(MI, BB, 4, 0, true);
831 case Mips::ATOMIC_LOAD_SUB_I8:
832 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
833 case Mips::ATOMIC_LOAD_SUB_I16:
834 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
835 case Mips::ATOMIC_LOAD_SUB_I32:
836 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
838 case Mips::ATOMIC_SWAP_I8:
839 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
840 case Mips::ATOMIC_SWAP_I16:
841 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
842 case Mips::ATOMIC_SWAP_I32:
843 return EmitAtomicBinary(MI, BB, 4, 0);
845 case Mips::ATOMIC_CMP_SWAP_I8:
846 return EmitAtomicCmpSwapPartword(MI, BB, 1);
847 case Mips::ATOMIC_CMP_SWAP_I16:
848 return EmitAtomicCmpSwapPartword(MI, BB, 2);
849 case Mips::ATOMIC_CMP_SWAP_I32:
850 return EmitAtomicCmpSwap(MI, BB, 4);
854 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
855 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
857 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
858 unsigned Size, unsigned BinOpcode,
860 assert(Size == 4 && "Unsupported size for EmitAtomicBinary.");
862 MachineFunction *MF = BB->getParent();
863 MachineRegisterInfo &RegInfo = MF->getRegInfo();
864 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
865 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
866 DebugLoc dl = MI->getDebugLoc();
868 unsigned OldVal = MI->getOperand(0).getReg();
869 unsigned Ptr = MI->getOperand(1).getReg();
870 unsigned Incr = MI->getOperand(2).getReg();
872 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
873 unsigned AndRes = RegInfo.createVirtualRegister(RC);
874 unsigned Success = RegInfo.createVirtualRegister(RC);
876 // insert new blocks after the current block
877 const BasicBlock *LLVM_BB = BB->getBasicBlock();
878 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
879 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
880 MachineFunction::iterator It = BB;
882 MF->insert(It, loopMBB);
883 MF->insert(It, exitMBB);
885 // Transfer the remainder of BB and its successor edges to exitMBB.
886 exitMBB->splice(exitMBB->begin(), BB,
887 llvm::next(MachineBasicBlock::iterator(MI)),
889 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
893 // fallthrough --> loopMBB
894 BB->addSuccessor(loopMBB);
895 loopMBB->addSuccessor(loopMBB);
896 loopMBB->addSuccessor(exitMBB);
900 // <binop> storeval, oldval, incr
901 // sc success, storeval, 0(ptr)
902 // beq success, $0, loopMBB
904 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(Ptr).addImm(0);
906 // and andres, oldval, incr
907 // nor storeval, $0, andres
908 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr);
909 BuildMI(BB, dl, TII->get(Mips::NOR), StoreVal)
910 .addReg(Mips::ZERO).addReg(AndRes);
911 } else if (BinOpcode) {
912 // <binop> storeval, oldval, incr
913 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
917 BuildMI(BB, dl, TII->get(Mips::SC), Success)
918 .addReg(StoreVal).addReg(Ptr).addImm(0);
919 BuildMI(BB, dl, TII->get(Mips::BEQ))
920 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
922 MI->eraseFromParent(); // The instruction is gone now.
928 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
929 MachineBasicBlock *BB,
930 unsigned Size, unsigned BinOpcode,
932 assert((Size == 1 || Size == 2) &&
933 "Unsupported size for EmitAtomicBinaryPartial.");
935 MachineFunction *MF = BB->getParent();
936 MachineRegisterInfo &RegInfo = MF->getRegInfo();
937 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
938 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
939 DebugLoc dl = MI->getDebugLoc();
941 unsigned Dest = MI->getOperand(0).getReg();
942 unsigned Ptr = MI->getOperand(1).getReg();
943 unsigned Incr = MI->getOperand(2).getReg();
945 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
946 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
947 unsigned Mask = RegInfo.createVirtualRegister(RC);
948 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
949 unsigned NewVal = RegInfo.createVirtualRegister(RC);
950 unsigned OldVal = RegInfo.createVirtualRegister(RC);
951 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
952 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
953 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
954 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
955 unsigned AndRes = RegInfo.createVirtualRegister(RC);
956 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
957 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
958 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
959 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
960 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
961 unsigned SllRes = RegInfo.createVirtualRegister(RC);
962 unsigned Success = RegInfo.createVirtualRegister(RC);
964 // insert new blocks after the current block
965 const BasicBlock *LLVM_BB = BB->getBasicBlock();
966 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
967 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
968 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
969 MachineFunction::iterator It = BB;
971 MF->insert(It, loopMBB);
972 MF->insert(It, sinkMBB);
973 MF->insert(It, exitMBB);
975 // Transfer the remainder of BB and its successor edges to exitMBB.
976 exitMBB->splice(exitMBB->begin(), BB,
977 llvm::next(MachineBasicBlock::iterator(MI)),
979 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
981 BB->addSuccessor(loopMBB);
982 loopMBB->addSuccessor(loopMBB);
983 loopMBB->addSuccessor(sinkMBB);
984 sinkMBB->addSuccessor(exitMBB);
987 // addiu masklsb2,$0,-4 # 0xfffffffc
988 // and alignedaddr,ptr,masklsb2
989 // andi ptrlsb2,ptr,3
990 // sll shiftamt,ptrlsb2,3
991 // ori maskupper,$0,255 # 0xff
992 // sll mask,maskupper,shiftamt
994 // sll incr2,incr,shiftamt
996 int64_t MaskImm = (Size == 1) ? 255 : 65535;
997 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
998 .addReg(Mips::ZERO).addImm(-4);
999 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1000 .addReg(Ptr).addReg(MaskLSB2);
1001 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1002 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1003 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1004 .addReg(Mips::ZERO).addImm(MaskImm);
1005 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1006 .addReg(ShiftAmt).addReg(MaskUpper);
1007 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1008 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1011 // atomic.load.binop
1013 // ll oldval,0(alignedaddr)
1014 // binop binopres,oldval,incr2
1015 // and newval,binopres,mask
1016 // and maskedoldval0,oldval,mask2
1017 // or storeval,maskedoldval0,newval
1018 // sc success,storeval,0(alignedaddr)
1019 // beq success,$0,loopMBB
1023 // ll oldval,0(alignedaddr)
1024 // and newval,incr2,mask
1025 // and maskedoldval0,oldval,mask2
1026 // or storeval,maskedoldval0,newval
1027 // sc success,storeval,0(alignedaddr)
1028 // beq success,$0,loopMBB
1031 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1033 // and andres, oldval, incr2
1034 // nor binopres, $0, andres
1035 // and newval, binopres, mask
1036 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1037 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1038 .addReg(Mips::ZERO).addReg(AndRes);
1039 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1040 } else if (BinOpcode) {
1041 // <binop> binopres, oldval, incr2
1042 // and newval, binopres, mask
1043 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1044 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1045 } else {// atomic.swap
1046 // and newval, incr2, mask
1047 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1050 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1051 .addReg(OldVal).addReg(Mask2);
1052 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1053 .addReg(MaskedOldVal0).addReg(NewVal);
1054 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1055 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1056 BuildMI(BB, dl, TII->get(Mips::BEQ))
1057 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1060 // and maskedoldval1,oldval,mask
1061 // srl srlres,maskedoldval1,shiftamt
1062 // sll sllres,srlres,24
1063 // sra dest,sllres,24
1065 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1067 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1068 .addReg(OldVal).addReg(Mask);
1069 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1070 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1071 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1072 .addReg(SrlRes).addImm(ShiftImm);
1073 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1074 .addReg(SllRes).addImm(ShiftImm);
1076 MI->eraseFromParent(); // The instruction is gone now.
1082 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1083 MachineBasicBlock *BB,
1084 unsigned Size) const {
1085 assert(Size == 4 && "Unsupported size for EmitAtomicCmpSwap.");
1087 MachineFunction *MF = BB->getParent();
1088 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1089 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1090 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1091 DebugLoc dl = MI->getDebugLoc();
1093 unsigned Dest = MI->getOperand(0).getReg();
1094 unsigned Ptr = MI->getOperand(1).getReg();
1095 unsigned OldVal = MI->getOperand(2).getReg();
1096 unsigned NewVal = MI->getOperand(3).getReg();
1098 unsigned Success = RegInfo.createVirtualRegister(RC);
1100 // insert new blocks after the current block
1101 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1102 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1103 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1104 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1105 MachineFunction::iterator It = BB;
1107 MF->insert(It, loop1MBB);
1108 MF->insert(It, loop2MBB);
1109 MF->insert(It, exitMBB);
1111 // Transfer the remainder of BB and its successor edges to exitMBB.
1112 exitMBB->splice(exitMBB->begin(), BB,
1113 llvm::next(MachineBasicBlock::iterator(MI)),
1115 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1119 // fallthrough --> loop1MBB
1120 BB->addSuccessor(loop1MBB);
1121 loop1MBB->addSuccessor(exitMBB);
1122 loop1MBB->addSuccessor(loop2MBB);
1123 loop2MBB->addSuccessor(loop1MBB);
1124 loop2MBB->addSuccessor(exitMBB);
1128 // bne dest, oldval, exitMBB
1130 BuildMI(BB, dl, TII->get(Mips::LL), Dest).addReg(Ptr).addImm(0);
1131 BuildMI(BB, dl, TII->get(Mips::BNE))
1132 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1135 // sc success, newval, 0(ptr)
1136 // beq success, $0, loop1MBB
1138 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1139 .addReg(NewVal).addReg(Ptr).addImm(0);
1140 BuildMI(BB, dl, TII->get(Mips::BEQ))
1141 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1143 MI->eraseFromParent(); // The instruction is gone now.
1149 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1150 MachineBasicBlock *BB,
1151 unsigned Size) const {
1152 assert((Size == 1 || Size == 2) &&
1153 "Unsupported size for EmitAtomicCmpSwapPartial.");
1155 MachineFunction *MF = BB->getParent();
1156 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1157 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1158 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1159 DebugLoc dl = MI->getDebugLoc();
1161 unsigned Dest = MI->getOperand(0).getReg();
1162 unsigned Ptr = MI->getOperand(1).getReg();
1163 unsigned CmpVal = MI->getOperand(2).getReg();
1164 unsigned NewVal = MI->getOperand(3).getReg();
1166 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1167 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1168 unsigned Mask = RegInfo.createVirtualRegister(RC);
1169 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1170 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1171 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1172 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1173 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1174 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1175 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1176 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1177 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1178 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1179 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1180 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1181 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1182 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1183 unsigned Success = RegInfo.createVirtualRegister(RC);
1185 // insert new blocks after the current block
1186 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1187 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1188 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1189 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1190 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1191 MachineFunction::iterator It = BB;
1193 MF->insert(It, loop1MBB);
1194 MF->insert(It, loop2MBB);
1195 MF->insert(It, sinkMBB);
1196 MF->insert(It, exitMBB);
1198 // Transfer the remainder of BB and its successor edges to exitMBB.
1199 exitMBB->splice(exitMBB->begin(), BB,
1200 llvm::next(MachineBasicBlock::iterator(MI)),
1202 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1204 BB->addSuccessor(loop1MBB);
1205 loop1MBB->addSuccessor(sinkMBB);
1206 loop1MBB->addSuccessor(loop2MBB);
1207 loop2MBB->addSuccessor(loop1MBB);
1208 loop2MBB->addSuccessor(sinkMBB);
1209 sinkMBB->addSuccessor(exitMBB);
1211 // FIXME: computation of newval2 can be moved to loop2MBB.
1213 // addiu masklsb2,$0,-4 # 0xfffffffc
1214 // and alignedaddr,ptr,masklsb2
1215 // andi ptrlsb2,ptr,3
1216 // sll shiftamt,ptrlsb2,3
1217 // ori maskupper,$0,255 # 0xff
1218 // sll mask,maskupper,shiftamt
1219 // nor mask2,$0,mask
1220 // andi maskedcmpval,cmpval,255
1221 // sll shiftedcmpval,maskedcmpval,shiftamt
1222 // andi maskednewval,newval,255
1223 // sll shiftednewval,maskednewval,shiftamt
1224 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1225 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1226 .addReg(Mips::ZERO).addImm(-4);
1227 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1228 .addReg(Ptr).addReg(MaskLSB2);
1229 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1230 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1231 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1232 .addReg(Mips::ZERO).addImm(MaskImm);
1233 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1234 .addReg(ShiftAmt).addReg(MaskUpper);
1235 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1236 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1237 .addReg(CmpVal).addImm(MaskImm);
1238 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1239 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1240 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1241 .addReg(NewVal).addImm(MaskImm);
1242 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1243 .addReg(ShiftAmt).addReg(MaskedNewVal);
1246 // ll oldval,0(alginedaddr)
1247 // and maskedoldval0,oldval,mask
1248 // bne maskedoldval0,shiftedcmpval,sinkMBB
1250 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1251 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1252 .addReg(OldVal).addReg(Mask);
1253 BuildMI(BB, dl, TII->get(Mips::BNE))
1254 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1257 // and maskedoldval1,oldval,mask2
1258 // or storeval,maskedoldval1,shiftednewval
1259 // sc success,storeval,0(alignedaddr)
1260 // beq success,$0,loop1MBB
1262 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1263 .addReg(OldVal).addReg(Mask2);
1264 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1265 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1266 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1267 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1268 BuildMI(BB, dl, TII->get(Mips::BEQ))
1269 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1272 // srl srlres,maskedoldval0,shiftamt
1273 // sll sllres,srlres,24
1274 // sra dest,sllres,24
1276 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1278 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1279 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1280 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1281 .addReg(SrlRes).addImm(ShiftImm);
1282 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1283 .addReg(SllRes).addImm(ShiftImm);
1285 MI->eraseFromParent(); // The instruction is gone now.
1290 //===----------------------------------------------------------------------===//
1291 // Misc Lower Operation implementation
1292 //===----------------------------------------------------------------------===//
1293 SDValue MipsTargetLowering::
1294 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1296 MachineFunction &MF = DAG.getMachineFunction();
1297 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1299 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1300 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1301 "Cannot lower if the alignment of the allocated space is larger than \
1302 that of the stack.");
1304 SDValue Chain = Op.getOperand(0);
1305 SDValue Size = Op.getOperand(1);
1306 DebugLoc dl = Op.getDebugLoc();
1308 // Get a reference from Mips stack pointer
1309 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
1311 // Subtract the dynamic size from the actual stack size to
1312 // obtain the new stack size.
1313 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
1315 // The Sub result contains the new stack start address, so it
1316 // must be placed in the stack pointer register.
1317 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
1320 // This node always has two return values: a new stack pointer
1321 // value and a chain
1322 SDVTList VTLs = DAG.getVTList(MVT::i32, MVT::Other);
1323 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1324 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1326 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1329 SDValue MipsTargetLowering::
1330 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1332 // The first operand is the chain, the second is the condition, the third is
1333 // the block to branch to if the condition is true.
1334 SDValue Chain = Op.getOperand(0);
1335 SDValue Dest = Op.getOperand(2);
1336 DebugLoc dl = Op.getDebugLoc();
1338 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1340 // Return if flag is not set by a floating point comparison.
1341 if (CondRes.getOpcode() != MipsISD::FPCmp)
1344 SDValue CCNode = CondRes.getOperand(2);
1346 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1347 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1349 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1353 SDValue MipsTargetLowering::
1354 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1356 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1358 // Return if flag is not set by a floating point comparison.
1359 if (Cond.getOpcode() != MipsISD::FPCmp)
1362 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1366 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1367 SelectionDAG &DAG) const {
1368 // FIXME there isn't actually debug info here
1369 DebugLoc dl = Op.getDebugLoc();
1370 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1372 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1373 SDVTList VTs = DAG.getVTList(MVT::i32);
1375 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1377 // %gp_rel relocation
1378 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1379 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1381 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1382 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1383 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1385 // %hi/%lo relocation
1386 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1388 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1390 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1391 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1392 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1395 EVT ValTy = Op.getValueType();
1396 bool HasGotOfst = (GV->hasInternalLinkage() ||
1397 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1398 unsigned GotFlag = IsN64 ?
1399 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1401 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1402 GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1403 SDValue ResNode = DAG.getLoad(ValTy, dl,
1404 DAG.getEntryNode(), GA, MachinePointerInfo(),
1406 // On functions and global targets not internal linked only
1407 // a load from got/GP is necessary for PIC to work.
1410 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1411 IsN64 ? MipsII::MO_GOT_OFST :
1413 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1414 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1417 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1418 SelectionDAG &DAG) const {
1419 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1420 // FIXME there isn't actually debug info here
1421 DebugLoc dl = Op.getDebugLoc();
1423 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1424 // %hi/%lo relocation
1425 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1427 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1429 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1430 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1431 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1434 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1436 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1437 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1439 SDValue Load = DAG.getLoad(MVT::i32, dl,
1440 DAG.getEntryNode(), BAGOTOffset,
1441 MachinePointerInfo(), false, false, 0);
1442 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1443 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1446 SDValue MipsTargetLowering::
1447 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1449 // If the relocation model is PIC, use the General Dynamic TLS Model,
1450 // otherwise use the Initial Exec or Local Exec TLS Model.
1451 // TODO: implement Local Dynamic TLS model
1453 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1454 DebugLoc dl = GA->getDebugLoc();
1455 const GlobalValue *GV = GA->getGlobal();
1456 EVT PtrVT = getPointerTy();
1458 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1459 // General Dynamic TLS Model
1460 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1461 0, MipsII::MO_TLSGD);
1462 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1463 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1464 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1468 Entry.Node = Argument;
1469 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1470 Args.push_back(Entry);
1471 std::pair<SDValue, SDValue> CallResult =
1472 LowerCallTo(DAG.getEntryNode(),
1473 (Type *) Type::getInt32Ty(*DAG.getContext()),
1474 false, false, false, false, 0, CallingConv::C, false, true,
1475 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1478 return CallResult.first;
1482 if (GV->isDeclaration()) {
1483 // Initial Exec TLS Model
1484 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1485 MipsII::MO_GOTTPREL);
1486 Offset = DAG.getLoad(MVT::i32, dl,
1487 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1490 // Local Exec TLS Model
1491 SDVTList VTs = DAG.getVTList(MVT::i32);
1492 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1493 MipsII::MO_TPREL_HI);
1494 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1495 MipsII::MO_TPREL_LO);
1496 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1497 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1498 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1501 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1502 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1505 SDValue MipsTargetLowering::
1506 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1510 // FIXME there isn't actually debug info here
1511 DebugLoc dl = Op.getDebugLoc();
1512 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1513 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1515 EVT PtrVT = Op.getValueType();
1516 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1518 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1521 SDValue Ops[] = { JTI };
1522 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1523 } else {// Emit Load from Global Pointer
1524 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1525 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1526 MachinePointerInfo(),
1530 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1532 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1533 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1538 SDValue MipsTargetLowering::
1539 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1542 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1543 const Constant *C = N->getConstVal();
1544 // FIXME there isn't actually debug info here
1545 DebugLoc dl = Op.getDebugLoc();
1547 // gp_rel relocation
1548 // FIXME: we should reference the constant pool using small data sections,
1549 // but the asm printer currently doesn't support this feature without
1550 // hacking it. This feature should come soon so we can uncomment the
1552 //if (IsInSmallSection(C->getType())) {
1553 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1554 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1555 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1557 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1558 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1559 N->getOffset(), MipsII::MO_ABS_HI);
1560 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1561 N->getOffset(), MipsII::MO_ABS_LO);
1562 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1563 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1564 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1566 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1567 N->getOffset(), MipsII::MO_GOT);
1568 CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1569 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1570 CP, MachinePointerInfo::getConstantPool(),
1572 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1573 N->getOffset(), MipsII::MO_ABS_LO);
1574 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1575 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1581 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1582 MachineFunction &MF = DAG.getMachineFunction();
1583 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1585 DebugLoc dl = Op.getDebugLoc();
1586 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1589 // vastart just stores the address of the VarArgsFrameIndex slot into the
1590 // memory location argument.
1591 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1592 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1593 MachinePointerInfo(SV),
1597 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1598 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1599 DebugLoc dl = Op.getDebugLoc();
1600 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1601 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1602 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1603 DAG.getConstant(0x7fffffff, MVT::i32));
1604 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1605 DAG.getConstant(0x80000000, MVT::i32));
1606 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1607 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1610 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1612 // Use ext/ins instructions if target architecture is Mips32r2.
1613 // Eliminate redundant mfc1 and mtc1 instructions.
1614 unsigned LoIdx = 0, HiIdx = 1;
1617 std::swap(LoIdx, HiIdx);
1619 DebugLoc dl = Op.getDebugLoc();
1620 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1622 DAG.getConstant(LoIdx, MVT::i32));
1623 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1624 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1625 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1626 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1627 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1628 DAG.getConstant(0x7fffffff, MVT::i32));
1629 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1630 DAG.getConstant(0x80000000, MVT::i32));
1631 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1634 std::swap(Word0, Word1);
1636 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1639 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1641 EVT Ty = Op.getValueType();
1643 assert(Ty == MVT::f32 || Ty == MVT::f64);
1646 return LowerFCOPYSIGN32(Op, DAG);
1648 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1651 SDValue MipsTargetLowering::
1652 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1654 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1655 "Frame address can only be determined for current frame.");
1657 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1658 MFI->setFrameAddressIsTaken(true);
1659 EVT VT = Op.getValueType();
1660 DebugLoc dl = Op.getDebugLoc();
1661 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::FP, VT);
1665 // TODO: set SType according to the desired memory barrier behavior.
1666 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1667 SelectionDAG& DAG) const {
1669 DebugLoc dl = Op.getDebugLoc();
1670 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1671 DAG.getConstant(SType, MVT::i32));
1674 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1675 SelectionDAG& DAG) const {
1676 // FIXME: Need pseudo-fence for 'singlethread' fences
1677 // FIXME: Set SType for weaker fences where supported/appropriate.
1679 DebugLoc dl = Op.getDebugLoc();
1680 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1681 DAG.getConstant(SType, MVT::i32));
1684 //===----------------------------------------------------------------------===//
1685 // Calling Convention Implementation
1686 //===----------------------------------------------------------------------===//
1688 #include "MipsGenCallingConv.inc"
1690 //===----------------------------------------------------------------------===//
1691 // TODO: Implement a generic logic using tblgen that can support this.
1692 // Mips O32 ABI rules:
1694 // i32 - Passed in A0, A1, A2, A3 and stack
1695 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1696 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1697 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1698 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1699 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1702 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1703 //===----------------------------------------------------------------------===//
1705 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1706 MVT LocVT, CCValAssign::LocInfo LocInfo,
1707 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1709 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1711 static const unsigned IntRegs[] = {
1712 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1714 static const unsigned F32Regs[] = {
1715 Mips::F12, Mips::F14
1717 static const unsigned F64Regs[] = {
1722 if (ArgFlags.isByVal()) {
1723 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1724 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1725 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1726 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1727 r < std::min(IntRegsSize, NextReg); ++r)
1728 State.AllocateReg(IntRegs[r]);
1732 // Promote i8 and i16
1733 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1735 if (ArgFlags.isSExt())
1736 LocInfo = CCValAssign::SExt;
1737 else if (ArgFlags.isZExt())
1738 LocInfo = CCValAssign::ZExt;
1740 LocInfo = CCValAssign::AExt;
1745 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1746 // is true: function is vararg, argument is 3rd or higher, there is previous
1747 // argument which is not f32 or f64.
1748 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1749 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1750 unsigned OrigAlign = ArgFlags.getOrigAlign();
1751 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1753 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1754 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1755 // If this is the first part of an i64 arg,
1756 // the allocated register must be either A0 or A2.
1757 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1758 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1760 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1761 // Allocate int register and shadow next int register. If first
1762 // available register is Mips::A1 or Mips::A3, shadow it too.
1763 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1764 if (Reg == Mips::A1 || Reg == Mips::A3)
1765 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1766 State.AllocateReg(IntRegs, IntRegsSize);
1768 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1769 // we are guaranteed to find an available float register
1770 if (ValVT == MVT::f32) {
1771 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1772 // Shadow int register
1773 State.AllocateReg(IntRegs, IntRegsSize);
1775 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1776 // Shadow int registers
1777 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1778 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1779 State.AllocateReg(IntRegs, IntRegsSize);
1780 State.AllocateReg(IntRegs, IntRegsSize);
1783 llvm_unreachable("Cannot handle this ValVT.");
1785 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1786 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1789 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1791 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1793 return false; // CC must always match
1796 //===----------------------------------------------------------------------===//
1797 // Call Calling Convention Implementation
1798 //===----------------------------------------------------------------------===//
1800 static const unsigned O32IntRegsSize = 4;
1802 static const unsigned O32IntRegs[] = {
1803 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1806 // Return next O32 integer argument register.
1807 static unsigned getNextIntArgReg(unsigned Reg) {
1808 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1809 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1812 // Write ByVal Arg to arg registers and stack.
1814 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1815 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1816 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1817 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1818 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1819 MVT PtrType, bool isLittle) {
1820 unsigned LocMemOffset = VA.getLocMemOffset();
1821 unsigned Offset = 0;
1822 uint32_t RemainingSize = Flags.getByValSize();
1823 unsigned ByValAlign = Flags.getByValAlign();
1825 // Copy the first 4 words of byval arg to registers A0 - A3.
1826 // FIXME: Use a stricter alignment if it enables better optimization in passes
1828 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1829 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1830 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1831 DAG.getConstant(Offset, MVT::i32));
1832 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1833 MachinePointerInfo(),
1834 false, false, std::min(ByValAlign,
1836 MemOpChains.push_back(LoadVal.getValue(1));
1837 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1838 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1841 if (RemainingSize == 0)
1844 // If there still is a register available for argument passing, write the
1845 // remaining part of the structure to it using subword loads and shifts.
1846 if (LocMemOffset < 4 * 4) {
1847 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
1848 "There must be one to three bytes remaining.");
1849 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
1850 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1851 DAG.getConstant(Offset, MVT::i32));
1852 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
1853 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
1854 LoadPtr, MachinePointerInfo(),
1855 MVT::getIntegerVT(LoadSize * 8), false,
1857 MemOpChains.push_back(LoadVal.getValue(1));
1859 // If target is big endian, shift it to the most significant half-word or
1862 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
1863 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
1866 RemainingSize -= LoadSize;
1868 // Read second subword if necessary.
1869 if (RemainingSize != 0) {
1870 assert(RemainingSize == 1 && "There must be one byte remaining.");
1871 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1872 DAG.getConstant(Offset, MVT::i32));
1873 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
1874 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
1875 LoadPtr, MachinePointerInfo(),
1876 MVT::i8, false, false, Alignment);
1877 MemOpChains.push_back(Subword.getValue(1));
1878 // Insert the loaded byte to LoadVal.
1879 // FIXME: Use INS if supported by target.
1880 unsigned ShiftAmt = isLittle ? 16 : 8;
1881 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
1882 DAG.getConstant(ShiftAmt, MVT::i32));
1883 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
1886 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1887 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1891 // Create a fixed object on stack at offset LocMemOffset and copy
1892 // remaining part of byval arg to it using memcpy.
1893 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1894 DAG.getConstant(Offset, MVT::i32));
1895 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
1896 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1897 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
1898 DAG.getConstant(RemainingSize, MVT::i32),
1899 std::min(ByValAlign, (unsigned)4),
1900 /*isVolatile=*/false, /*AlwaysInline=*/false,
1901 MachinePointerInfo(0), MachinePointerInfo(0));
1904 /// LowerCall - functions arguments are copied from virtual regs to
1905 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1906 /// TODO: isTailCall.
1908 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
1909 CallingConv::ID CallConv, bool isVarArg,
1911 const SmallVectorImpl<ISD::OutputArg> &Outs,
1912 const SmallVectorImpl<SDValue> &OutVals,
1913 const SmallVectorImpl<ISD::InputArg> &Ins,
1914 DebugLoc dl, SelectionDAG &DAG,
1915 SmallVectorImpl<SDValue> &InVals) const {
1916 // MIPs target does not yet support tail call optimization.
1919 MachineFunction &MF = DAG.getMachineFunction();
1920 MachineFrameInfo *MFI = MF.getFrameInfo();
1921 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1922 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1923 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1925 // Analyze operands of the call, assigning locations to each operand.
1926 SmallVector<CCValAssign, 16> ArgLocs;
1927 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1928 getTargetMachine(), ArgLocs, *DAG.getContext());
1931 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1933 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1935 // Get a count of how many bytes are to be pushed on the stack.
1936 unsigned NextStackOffset = CCInfo.getNextStackOffset();
1938 // Chain is the output chain of the last Load/Store or CopyToReg node.
1939 // ByValChain is the output chain of the last Memcpy node created for copying
1940 // byval arguments to the stack.
1941 SDValue Chain, CallSeqStart, ByValChain;
1942 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
1943 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
1944 ByValChain = InChain;
1946 // If this is the first call, create a stack frame object that points to
1947 // a location to which .cprestore saves $gp.
1948 if (IsPIC && !MipsFI->getGPFI())
1949 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1951 // Get the frame index of the stack frame object that points to the location
1952 // of dynamically allocated area on the stack.
1953 int DynAllocFI = MipsFI->getDynAllocFI();
1955 // Update size of the maximum argument space.
1956 // For O32, a minimum of four words (16 bytes) of argument space is
1959 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1961 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1963 if (MaxCallFrameSize < NextStackOffset) {
1964 MipsFI->setMaxCallFrameSize(NextStackOffset);
1966 // Set the offsets relative to $sp of the $gp restore slot and dynamically
1967 // allocated stack space. These offsets must be aligned to a boundary
1968 // determined by the stack alignment of the ABI.
1969 unsigned StackAlignment = TFL->getStackAlignment();
1970 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
1971 StackAlignment * StackAlignment;
1974 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
1976 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
1979 // With EABI is it possible to have 16 args on registers.
1980 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1981 SmallVector<SDValue, 8> MemOpChains;
1983 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
1985 // Walk the register/memloc assignments, inserting copies/loads.
1986 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1987 SDValue Arg = OutVals[i];
1988 CCValAssign &VA = ArgLocs[i];
1990 // Promote the value if needed.
1991 switch (VA.getLocInfo()) {
1992 default: llvm_unreachable("Unknown loc info!");
1993 case CCValAssign::Full:
1994 if (IsO32 && VA.isRegLoc()) {
1995 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1996 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1997 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1998 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1999 Arg, DAG.getConstant(0, MVT::i32));
2000 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2001 Arg, DAG.getConstant(1, MVT::i32));
2002 if (!Subtarget->isLittle())
2004 unsigned LocRegLo = VA.getLocReg();
2005 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2006 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2007 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2012 case CCValAssign::SExt:
2013 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2015 case CCValAssign::ZExt:
2016 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2018 case CCValAssign::AExt:
2019 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2023 // Arguments that can be passed on register must be kept at
2024 // RegsToPass vector
2025 if (VA.isRegLoc()) {
2026 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2030 // Register can't get to this point...
2031 assert(VA.isMemLoc());
2034 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2035 if (Flags.isByVal()) {
2037 "No support for ByVal args by ABIs other than O32 yet.");
2038 assert(Flags.getByValSize() &&
2039 "ByVal args of size 0 should have been ignored by front-end.");
2040 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI, MFI,
2041 DAG, Arg, VA, Flags, getPointerTy(), Subtarget->isLittle());
2045 // Create the frame index object for this incoming parameter
2046 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2047 VA.getLocMemOffset(), true);
2048 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2050 // emit ISD::STORE whichs stores the
2051 // parameter value to a stack Location
2052 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2053 MachinePointerInfo(),
2057 // Extend range of indices of frame objects for outgoing arguments that were
2058 // created during this function call. Skip this step if no such objects were
2061 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2063 // If a memcpy has been created to copy a byval arg to a stack, replace the
2064 // chain input of CallSeqStart with ByValChain.
2065 if (InChain != ByValChain)
2066 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2067 NextStackOffsetVal);
2069 // Transform all store nodes into one single node because all store
2070 // nodes are independent of each other.
2071 if (!MemOpChains.empty())
2072 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2073 &MemOpChains[0], MemOpChains.size());
2075 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2076 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2077 // node so that legalize doesn't hack it.
2078 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2079 bool LoadSymAddr = false;
2082 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2083 if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
2084 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2085 getPointerTy(), 0,MipsII:: MO_GOT);
2086 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2087 0, MipsII::MO_ABS_LO);
2089 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2090 getPointerTy(), 0, OpFlag);
2095 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2096 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2097 getPointerTy(), OpFlag);
2103 // Create nodes that load address of callee and copy it to T9
2106 // Load callee address
2107 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
2108 SDValue LoadValue = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), Callee,
2109 MachinePointerInfo::getGOT(),
2112 // Use GOT+LO if callee has internal linkage.
2113 if (CalleeLo.getNode()) {
2114 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
2115 Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
2121 Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
2122 InFlag = Chain.getValue(1);
2123 Callee = DAG.getRegister(Mips::T9, MVT::i32);
2126 // Build a sequence of copy-to-reg nodes chained together with token
2127 // chain and flag operands which copy the outgoing args into registers.
2128 // The InFlag in necessary since all emitted instructions must be
2130 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2131 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2132 RegsToPass[i].second, InFlag);
2133 InFlag = Chain.getValue(1);
2136 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2137 // = Chain, Callee, Reg#1, Reg#2, ...
2139 // Returns a chain & a flag for retval copy to use.
2140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2141 SmallVector<SDValue, 8> Ops;
2142 Ops.push_back(Chain);
2143 Ops.push_back(Callee);
2145 // Add argument registers to the end of the list so that they are
2146 // known live into the call.
2147 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2148 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2149 RegsToPass[i].second.getValueType()));
2151 if (InFlag.getNode())
2152 Ops.push_back(InFlag);
2154 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2155 InFlag = Chain.getValue(1);
2157 // Create the CALLSEQ_END node.
2158 Chain = DAG.getCALLSEQ_END(Chain,
2159 DAG.getIntPtrConstant(NextStackOffset, true),
2160 DAG.getIntPtrConstant(0, true), InFlag);
2161 InFlag = Chain.getValue(1);
2163 // Handle result values, copying them out of physregs into vregs that we
2165 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2166 Ins, dl, DAG, InVals);
2169 /// LowerCallResult - Lower the result values of a call into the
2170 /// appropriate copies out of appropriate physical registers.
2172 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2173 CallingConv::ID CallConv, bool isVarArg,
2174 const SmallVectorImpl<ISD::InputArg> &Ins,
2175 DebugLoc dl, SelectionDAG &DAG,
2176 SmallVectorImpl<SDValue> &InVals) const {
2177 // Assign locations to each value returned by this call.
2178 SmallVector<CCValAssign, 16> RVLocs;
2179 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2180 getTargetMachine(), RVLocs, *DAG.getContext());
2182 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2184 // Copy all of the result registers out of their specified physreg.
2185 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2186 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2187 RVLocs[i].getValVT(), InFlag).getValue(1);
2188 InFlag = Chain.getValue(2);
2189 InVals.push_back(Chain.getValue(0));
2195 //===----------------------------------------------------------------------===//
2196 // Formal Arguments Calling Convention Implementation
2197 //===----------------------------------------------------------------------===//
2198 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2199 std::vector<SDValue>& OutChains,
2200 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2201 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2202 unsigned LocMem = VA.getLocMemOffset();
2203 unsigned FirstWord = LocMem / 4;
2205 // copy register A0 - A3 to frame object
2206 for (unsigned i = 0; i < NumWords; ++i) {
2207 unsigned CurWord = FirstWord + i;
2208 if (CurWord >= O32IntRegsSize)
2211 unsigned SrcReg = O32IntRegs[CurWord];
2212 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2213 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2214 DAG.getConstant(i * 4, MVT::i32));
2215 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2216 StorePtr, MachinePointerInfo(), false,
2218 OutChains.push_back(Store);
2222 /// LowerFormalArguments - transform physical registers into virtual registers
2223 /// and generate load operations for arguments places on the stack.
2225 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2226 CallingConv::ID CallConv,
2228 const SmallVectorImpl<ISD::InputArg>
2230 DebugLoc dl, SelectionDAG &DAG,
2231 SmallVectorImpl<SDValue> &InVals)
2233 MachineFunction &MF = DAG.getMachineFunction();
2234 MachineFrameInfo *MFI = MF.getFrameInfo();
2235 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2237 MipsFI->setVarArgsFrameIndex(0);
2239 // Used with vargs to acumulate store chains.
2240 std::vector<SDValue> OutChains;
2242 // Assign locations to all of the incoming arguments.
2243 SmallVector<CCValAssign, 16> ArgLocs;
2244 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2245 getTargetMachine(), ArgLocs, *DAG.getContext());
2248 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2250 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2252 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2254 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2255 CCValAssign &VA = ArgLocs[i];
2257 // Arguments stored on registers
2258 if (VA.isRegLoc()) {
2259 EVT RegVT = VA.getLocVT();
2260 unsigned ArgReg = VA.getLocReg();
2261 TargetRegisterClass *RC = 0;
2263 if (RegVT == MVT::i32)
2264 RC = Mips::CPURegsRegisterClass;
2265 else if (RegVT == MVT::i64)
2266 RC = Mips::CPU64RegsRegisterClass;
2267 else if (RegVT == MVT::f32)
2268 RC = Mips::FGR32RegisterClass;
2269 else if (RegVT == MVT::f64)
2270 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2272 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2274 // Transform the arguments stored on
2275 // physical registers into virtual ones
2276 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2277 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2279 // If this is an 8 or 16-bit value, it has been passed promoted
2280 // to 32 bits. Insert an assert[sz]ext to capture this, then
2281 // truncate to the right size.
2282 if (VA.getLocInfo() != CCValAssign::Full) {
2283 unsigned Opcode = 0;
2284 if (VA.getLocInfo() == CCValAssign::SExt)
2285 Opcode = ISD::AssertSext;
2286 else if (VA.getLocInfo() == CCValAssign::ZExt)
2287 Opcode = ISD::AssertZext;
2289 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2290 DAG.getValueType(VA.getValVT()));
2291 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2294 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
2296 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
2297 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
2298 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
2299 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2300 getNextIntArgReg(ArgReg), RC);
2301 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2302 if (!Subtarget->isLittle())
2303 std::swap(ArgValue, ArgValue2);
2304 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2305 ArgValue, ArgValue2);
2309 InVals.push_back(ArgValue);
2310 } else { // VA.isRegLoc()
2313 assert(VA.isMemLoc());
2315 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2317 if (Flags.isByVal()) {
2319 "No support for ByVal args by ABIs other than O32 yet.");
2320 assert(Flags.getByValSize() &&
2321 "ByVal args of size 0 should have been ignored by front-end.");
2322 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2323 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2325 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2326 InVals.push_back(FIN);
2327 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2332 // The stack pointer offset is relative to the caller stack frame.
2333 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2334 VA.getLocMemOffset(), true);
2336 // Create load nodes to retrieve arguments from the stack
2337 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2338 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2339 MachinePointerInfo::getFixedStack(LastFI),
2344 // The mips ABIs for returning structs by value requires that we copy
2345 // the sret argument into $v0 for the return. Save the argument into
2346 // a virtual register so that we can access it from the return points.
2347 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2348 unsigned Reg = MipsFI->getSRetReturnReg();
2350 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2351 MipsFI->setSRetReturnReg(Reg);
2353 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2354 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2357 if (isVarArg && IsO32) {
2358 // Record the frame index of the first variable argument
2359 // which is a value necessary to VASTART.
2360 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2361 assert(NextStackOffset % 4 == 0 &&
2362 "NextStackOffset must be aligned to 4-byte boundaries.");
2363 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2364 MipsFI->setVarArgsFrameIndex(LastFI);
2366 // If NextStackOffset is smaller than o32's 16-byte reserved argument area,
2367 // copy the integer registers that have not been used for argument passing
2368 // to the caller's stack frame.
2369 for (; NextStackOffset < 16; NextStackOffset += 4) {
2370 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
2371 unsigned Idx = NextStackOffset / 4;
2372 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
2373 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
2374 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2375 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2376 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2377 MachinePointerInfo(),
2382 MipsFI->setLastInArgFI(LastFI);
2384 // All stores are grouped in one node to allow the matching between
2385 // the size of Ins and InVals. This only happens when on varg functions
2386 if (!OutChains.empty()) {
2387 OutChains.push_back(Chain);
2388 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2389 &OutChains[0], OutChains.size());
2395 //===----------------------------------------------------------------------===//
2396 // Return Value Calling Convention Implementation
2397 //===----------------------------------------------------------------------===//
2400 MipsTargetLowering::LowerReturn(SDValue Chain,
2401 CallingConv::ID CallConv, bool isVarArg,
2402 const SmallVectorImpl<ISD::OutputArg> &Outs,
2403 const SmallVectorImpl<SDValue> &OutVals,
2404 DebugLoc dl, SelectionDAG &DAG) const {
2406 // CCValAssign - represent the assignment of
2407 // the return value to a location
2408 SmallVector<CCValAssign, 16> RVLocs;
2410 // CCState - Info about the registers and stack slot.
2411 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2412 getTargetMachine(), RVLocs, *DAG.getContext());
2414 // Analize return values.
2415 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2417 // If this is the first return lowered for this function, add
2418 // the regs to the liveout set for the function.
2419 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2420 for (unsigned i = 0; i != RVLocs.size(); ++i)
2421 if (RVLocs[i].isRegLoc())
2422 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2427 // Copy the result values into the output registers.
2428 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2429 CCValAssign &VA = RVLocs[i];
2430 assert(VA.isRegLoc() && "Can only return in registers!");
2432 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2435 // guarantee that all emitted copies are
2436 // stuck together, avoiding something bad
2437 Flag = Chain.getValue(1);
2440 // The mips ABIs for returning structs by value requires that we copy
2441 // the sret argument into $v0 for the return. We saved the argument into
2442 // a virtual register in the entry block, so now we copy the value out
2444 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2445 MachineFunction &MF = DAG.getMachineFunction();
2446 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2447 unsigned Reg = MipsFI->getSRetReturnReg();
2450 llvm_unreachable("sret virtual register not created in the entry block");
2451 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2453 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2454 Flag = Chain.getValue(1);
2457 // Return on Mips is always a "jr $ra"
2459 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2460 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2462 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2463 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2466 //===----------------------------------------------------------------------===//
2467 // Mips Inline Assembly Support
2468 //===----------------------------------------------------------------------===//
2470 /// getConstraintType - Given a constraint letter, return the type of
2471 /// constraint it is for this target.
2472 MipsTargetLowering::ConstraintType MipsTargetLowering::
2473 getConstraintType(const std::string &Constraint) const
2475 // Mips specific constrainy
2476 // GCC config/mips/constraints.md
2478 // 'd' : An address register. Equivalent to r
2479 // unless generating MIPS16 code.
2480 // 'y' : Equivalent to r; retained for
2481 // backwards compatibility.
2482 // 'f' : Floating Point registers.
2483 if (Constraint.size() == 1) {
2484 switch (Constraint[0]) {
2489 return C_RegisterClass;
2493 return TargetLowering::getConstraintType(Constraint);
2496 /// Examine constraint type and operand type and determine a weight value.
2497 /// This object must already have been set up with the operand type
2498 /// and the current alternative constraint selected.
2499 TargetLowering::ConstraintWeight
2500 MipsTargetLowering::getSingleConstraintMatchWeight(
2501 AsmOperandInfo &info, const char *constraint) const {
2502 ConstraintWeight weight = CW_Invalid;
2503 Value *CallOperandVal = info.CallOperandVal;
2504 // If we don't have a value, we can't do a match,
2505 // but allow it at the lowest weight.
2506 if (CallOperandVal == NULL)
2508 Type *type = CallOperandVal->getType();
2509 // Look at the constraint type.
2510 switch (*constraint) {
2512 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2516 if (type->isIntegerTy())
2517 weight = CW_Register;
2520 if (type->isFloatTy())
2521 weight = CW_Register;
2527 /// Given a register class constraint, like 'r', if this corresponds directly
2528 /// to an LLVM register class, return a register of 0 and the register class
2530 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2531 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2533 if (Constraint.size() == 1) {
2534 switch (Constraint[0]) {
2535 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2536 case 'y': // Same as 'r'. Exists for compatibility.
2538 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2541 return std::make_pair(0U, Mips::FGR32RegisterClass);
2543 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2544 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2548 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2552 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2553 // The Mips target isn't yet aware of offsets.
2557 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2558 if (VT != MVT::f32 && VT != MVT::f64)
2560 if (Imm.isNegZero())
2562 return Imm.isZero();