1 //=== --MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
39 // If I is a shifted mask, set the size (Size) and the first bit of the
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43 if (!isShiftedMask_64(I))
46 Size = CountPopulation_64(I);
47 Pos = CountTrailingZeros_64(I);
51 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
52 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
53 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
56 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
58 case MipsISD::JmpLink: return "MipsISD::JmpLink";
59 case MipsISD::Hi: return "MipsISD::Hi";
60 case MipsISD::Lo: return "MipsISD::Lo";
61 case MipsISD::GPRel: return "MipsISD::GPRel";
62 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
63 case MipsISD::Ret: return "MipsISD::Ret";
64 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
65 case MipsISD::FPCmp: return "MipsISD::FPCmp";
66 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
67 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
68 case MipsISD::FPRound: return "MipsISD::FPRound";
69 case MipsISD::MAdd: return "MipsISD::MAdd";
70 case MipsISD::MAddu: return "MipsISD::MAddu";
71 case MipsISD::MSub: return "MipsISD::MSub";
72 case MipsISD::MSubu: return "MipsISD::MSubu";
73 case MipsISD::DivRem: return "MipsISD::DivRem";
74 case MipsISD::DivRemU: return "MipsISD::DivRemU";
75 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
76 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
77 case MipsISD::Wrapper: return "MipsISD::Wrapper";
78 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
79 case MipsISD::Sync: return "MipsISD::Sync";
80 case MipsISD::Ext: return "MipsISD::Ext";
81 case MipsISD::Ins: return "MipsISD::Ins";
87 MipsTargetLowering(MipsTargetMachine &TM)
88 : TargetLowering(TM, new MipsTargetObjectFile()),
89 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
90 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
91 IsO32(Subtarget->isABI_O32()) {
93 // Mips does not have i1 type, so use i32 for
94 // setcc operations results (slt, sgt, ...).
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
98 // Set up the register classes
99 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
102 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
104 if (!TM.Options.UseSoftFloat) {
105 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
107 // When dealing with single precision only, use libcalls
108 if (!Subtarget->isSingleFloat()) {
110 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
112 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
116 // Load extented operations for i1 types must be promoted
117 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
118 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121 // MIPS doesn't have extending float->double load/store
122 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
123 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
125 // Used by legalize types to correctly generate the setcc result.
126 // Without this, every float setcc comes with a AND/OR with the result,
127 // we don't want this, since the fpcmp result goes to a flag register,
128 // which is used implicitly by brcond and select operations.
129 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
131 // Mips Custom Operations
132 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
133 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
134 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
135 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
136 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
137 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
138 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
139 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
140 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
141 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT, MVT::f64, Custom);
144 setOperationAction(ISD::SELECT, MVT::i32, Custom);
145 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
146 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
147 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
148 setOperationAction(ISD::VASTART, MVT::Other, Custom);
150 setOperationAction(ISD::SDIV, MVT::i32, Expand);
151 setOperationAction(ISD::SREM, MVT::i32, Expand);
152 setOperationAction(ISD::UDIV, MVT::i32, Expand);
153 setOperationAction(ISD::UREM, MVT::i32, Expand);
154 setOperationAction(ISD::SDIV, MVT::i64, Expand);
155 setOperationAction(ISD::SREM, MVT::i64, Expand);
156 setOperationAction(ISD::UDIV, MVT::i64, Expand);
157 setOperationAction(ISD::UREM, MVT::i64, Expand);
159 // Operations not directly supported by Mips.
160 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
161 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
162 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
163 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
164 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
165 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
166 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
167 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
168 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
169 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
170 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
171 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
172 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
173 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
174 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
175 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
176 setOperationAction(ISD::ROTL, MVT::i32, Expand);
177 setOperationAction(ISD::ROTL, MVT::i64, Expand);
179 if (!Subtarget->hasMips32r2())
180 setOperationAction(ISD::ROTR, MVT::i32, Expand);
182 if (!Subtarget->hasMips64r2())
183 setOperationAction(ISD::ROTR, MVT::i64, Expand);
185 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
186 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
187 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
189 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
190 setOperationAction(ISD::FSIN, MVT::f32, Expand);
191 setOperationAction(ISD::FSIN, MVT::f64, Expand);
192 setOperationAction(ISD::FCOS, MVT::f32, Expand);
193 setOperationAction(ISD::FCOS, MVT::f64, Expand);
194 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
195 setOperationAction(ISD::FPOW, MVT::f32, Expand);
196 setOperationAction(ISD::FPOW, MVT::f64, Expand);
197 setOperationAction(ISD::FLOG, MVT::f32, Expand);
198 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
199 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
200 setOperationAction(ISD::FEXP, MVT::f32, Expand);
201 setOperationAction(ISD::FMA, MVT::f32, Expand);
202 setOperationAction(ISD::FMA, MVT::f64, Expand);
204 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
205 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
206 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
207 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
209 setOperationAction(ISD::VAARG, MVT::Other, Expand);
210 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
211 setOperationAction(ISD::VAEND, MVT::Other, Expand);
213 // Use the default for now
214 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
215 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
217 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
218 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
220 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
221 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
222 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
223 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
225 setInsertFencesForAtomic(true);
227 if (Subtarget->isSingleFloat())
228 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
230 if (!Subtarget->hasSEInReg()) {
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
235 if (!Subtarget->hasBitCount()) {
236 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
237 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
240 if (!Subtarget->hasSwap()) {
241 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
242 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
245 setTargetDAGCombine(ISD::ADDE);
246 setTargetDAGCombine(ISD::SUBE);
247 setTargetDAGCombine(ISD::SDIVREM);
248 setTargetDAGCombine(ISD::UDIVREM);
249 setTargetDAGCombine(ISD::SETCC);
250 setTargetDAGCombine(ISD::AND);
251 setTargetDAGCombine(ISD::OR);
253 setMinFunctionAlignment(2);
255 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
256 computeRegisterProperties();
258 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
259 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
262 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
263 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
272 return Subtarget->hasMips32r2Or64();
278 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
283 // Transforms a subgraph in CurDAG if the following pattern is found:
284 // (addc multLo, Lo0), (adde multHi, Hi0),
286 // multHi/Lo: product of multiplication
287 // Lo0: initial value of Lo register
288 // Hi0: initial value of Hi register
289 // Return true if pattern matching was successful.
290 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
291 // ADDENode's second operand must be a flag output of an ADDC node in order
292 // for the matching to be successful.
293 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
295 if (ADDCNode->getOpcode() != ISD::ADDC)
298 SDValue MultHi = ADDENode->getOperand(0);
299 SDValue MultLo = ADDCNode->getOperand(0);
300 SDNode* MultNode = MultHi.getNode();
301 unsigned MultOpc = MultHi.getOpcode();
303 // MultHi and MultLo must be generated by the same node,
304 if (MultLo.getNode() != MultNode)
307 // and it must be a multiplication.
308 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
311 // MultLo amd MultHi must be the first and second output of MultNode
313 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
316 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
317 // of the values of MultNode, in which case MultNode will be removed in later
319 // If there exist users other than ADDENode or ADDCNode, this function returns
320 // here, which will result in MultNode being mapped to a single MULT
321 // instruction node rather than a pair of MULT and MADD instructions being
323 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
326 SDValue Chain = CurDAG->getEntryNode();
327 DebugLoc dl = ADDENode->getDebugLoc();
329 // create MipsMAdd(u) node
330 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
332 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
333 MultNode->getOperand(0),// Factor 0
334 MultNode->getOperand(1),// Factor 1
335 ADDCNode->getOperand(1),// Lo0
336 ADDENode->getOperand(1));// Hi0
338 // create CopyFromReg nodes
339 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
341 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
343 CopyFromLo.getValue(2));
345 // replace uses of adde and addc here
346 if (!SDValue(ADDCNode, 0).use_empty())
347 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
349 if (!SDValue(ADDENode, 0).use_empty())
350 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
356 // Transforms a subgraph in CurDAG if the following pattern is found:
357 // (addc Lo0, multLo), (sube Hi0, multHi),
359 // multHi/Lo: product of multiplication
360 // Lo0: initial value of Lo register
361 // Hi0: initial value of Hi register
362 // Return true if pattern matching was successful.
363 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
364 // SUBENode's second operand must be a flag output of an SUBC node in order
365 // for the matching to be successful.
366 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
368 if (SUBCNode->getOpcode() != ISD::SUBC)
371 SDValue MultHi = SUBENode->getOperand(1);
372 SDValue MultLo = SUBCNode->getOperand(1);
373 SDNode* MultNode = MultHi.getNode();
374 unsigned MultOpc = MultHi.getOpcode();
376 // MultHi and MultLo must be generated by the same node,
377 if (MultLo.getNode() != MultNode)
380 // and it must be a multiplication.
381 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
384 // MultLo amd MultHi must be the first and second output of MultNode
386 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
389 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
390 // of the values of MultNode, in which case MultNode will be removed in later
392 // If there exist users other than SUBENode or SUBCNode, this function returns
393 // here, which will result in MultNode being mapped to a single MULT
394 // instruction node rather than a pair of MULT and MSUB instructions being
396 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
399 SDValue Chain = CurDAG->getEntryNode();
400 DebugLoc dl = SUBENode->getDebugLoc();
402 // create MipsSub(u) node
403 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
405 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
406 MultNode->getOperand(0),// Factor 0
407 MultNode->getOperand(1),// Factor 1
408 SUBCNode->getOperand(0),// Lo0
409 SUBENode->getOperand(0));// Hi0
411 // create CopyFromReg nodes
412 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
414 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
416 CopyFromLo.getValue(2));
418 // replace uses of sube and subc here
419 if (!SDValue(SUBCNode, 0).use_empty())
420 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
422 if (!SDValue(SUBENode, 0).use_empty())
423 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
428 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
429 TargetLowering::DAGCombinerInfo &DCI,
430 const MipsSubtarget* Subtarget) {
431 if (DCI.isBeforeLegalize())
434 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
436 return SDValue(N, 0);
441 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
442 TargetLowering::DAGCombinerInfo &DCI,
443 const MipsSubtarget* Subtarget) {
444 if (DCI.isBeforeLegalize())
447 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
449 return SDValue(N, 0);
454 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
455 TargetLowering::DAGCombinerInfo &DCI,
456 const MipsSubtarget* Subtarget) {
457 if (DCI.isBeforeLegalizeOps())
460 EVT Ty = N->getValueType(0);
461 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
462 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
463 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
465 DebugLoc dl = N->getDebugLoc();
467 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
468 N->getOperand(0), N->getOperand(1));
469 SDValue InChain = DAG.getEntryNode();
470 SDValue InGlue = DivRem;
473 if (N->hasAnyUseOfValue(0)) {
474 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
476 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
477 InChain = CopyFromLo.getValue(1);
478 InGlue = CopyFromLo.getValue(2);
482 if (N->hasAnyUseOfValue(1)) {
483 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
485 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
491 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
493 default: llvm_unreachable("Unknown fp condition code!");
495 case ISD::SETOEQ: return Mips::FCOND_OEQ;
496 case ISD::SETUNE: return Mips::FCOND_UNE;
498 case ISD::SETOLT: return Mips::FCOND_OLT;
500 case ISD::SETOGT: return Mips::FCOND_OGT;
502 case ISD::SETOLE: return Mips::FCOND_OLE;
504 case ISD::SETOGE: return Mips::FCOND_OGE;
505 case ISD::SETULT: return Mips::FCOND_ULT;
506 case ISD::SETULE: return Mips::FCOND_ULE;
507 case ISD::SETUGT: return Mips::FCOND_UGT;
508 case ISD::SETUGE: return Mips::FCOND_UGE;
509 case ISD::SETUO: return Mips::FCOND_UN;
510 case ISD::SETO: return Mips::FCOND_OR;
512 case ISD::SETONE: return Mips::FCOND_ONE;
513 case ISD::SETUEQ: return Mips::FCOND_UEQ;
518 // Returns true if condition code has to be inverted.
519 static bool InvertFPCondCode(Mips::CondCode CC) {
520 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
523 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
524 "Illegal Condition Code");
529 // Creates and returns an FPCmp node from a setcc node.
530 // Returns Op if setcc is not a floating point comparison.
531 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
532 // must be a SETCC node
533 if (Op.getOpcode() != ISD::SETCC)
536 SDValue LHS = Op.getOperand(0);
538 if (!LHS.getValueType().isFloatingPoint())
541 SDValue RHS = Op.getOperand(1);
542 DebugLoc dl = Op.getDebugLoc();
544 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
545 // node if necessary.
546 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
548 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
549 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
552 // Creates and returns a CMovFPT/F node.
553 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
554 SDValue False, DebugLoc DL) {
555 bool invert = InvertFPCondCode((Mips::CondCode)
556 cast<ConstantSDNode>(Cond.getOperand(2))
559 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
560 True.getValueType(), True, False, Cond);
563 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
564 TargetLowering::DAGCombinerInfo &DCI,
565 const MipsSubtarget* Subtarget) {
566 if (DCI.isBeforeLegalizeOps())
569 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
571 if (Cond.getOpcode() != MipsISD::FPCmp)
574 SDValue True = DAG.getConstant(1, MVT::i32);
575 SDValue False = DAG.getConstant(0, MVT::i32);
577 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
580 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
581 TargetLowering::DAGCombinerInfo &DCI,
582 const MipsSubtarget* Subtarget) {
583 // Pattern match EXT.
584 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
585 // => ext $dst, $src, size, pos
586 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
589 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
590 unsigned ShiftRightOpc = ShiftRight.getOpcode();
592 // Op's first operand must be a shift right.
593 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
596 // The second operand of the shift must be an immediate.
598 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
601 uint64_t Pos = CN->getZExtValue();
602 uint64_t SMPos, SMSize;
604 // Op's second operand must be a shifted mask.
605 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
606 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
609 // Return if the shifted mask does not start at bit 0 or the sum of its size
610 // and Pos exceeds the word's size.
611 EVT ValTy = N->getValueType(0);
612 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
615 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
616 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
617 DAG.getConstant(SMSize, MVT::i32));
620 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
621 TargetLowering::DAGCombinerInfo &DCI,
622 const MipsSubtarget* Subtarget) {
623 // Pattern match INS.
624 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
625 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
626 // => ins $dst, $src, size, pos, $src1
627 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
630 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
631 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
634 // See if Op's first operand matches (and $src1 , mask0).
635 if (And0.getOpcode() != ISD::AND)
638 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
639 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
642 // See if Op's second operand matches (and (shl $src, pos), mask1).
643 if (And1.getOpcode() != ISD::AND)
646 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
647 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
650 // The shift masks must have the same position and size.
651 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
654 SDValue Shl = And1.getOperand(0);
655 if (Shl.getOpcode() != ISD::SHL)
658 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
661 unsigned Shamt = CN->getZExtValue();
663 // Return if the shift amount and the first bit position of mask are not the
665 EVT ValTy = N->getValueType(0);
666 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
669 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
670 DAG.getConstant(SMPos0, MVT::i32),
671 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
674 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
676 SelectionDAG &DAG = DCI.DAG;
677 unsigned opc = N->getOpcode();
682 return PerformADDECombine(N, DAG, DCI, Subtarget);
684 return PerformSUBECombine(N, DAG, DCI, Subtarget);
687 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
689 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
691 return PerformANDCombine(N, DAG, DCI, Subtarget);
693 return PerformORCombine(N, DAG, DCI, Subtarget);
699 SDValue MipsTargetLowering::
700 LowerOperation(SDValue Op, SelectionDAG &DAG) const
702 switch (Op.getOpcode())
704 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
705 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
706 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
707 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
708 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
709 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
710 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
711 case ISD::SELECT: return LowerSELECT(Op, DAG);
712 case ISD::VASTART: return LowerVASTART(Op, DAG);
713 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
714 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
715 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
716 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
721 //===----------------------------------------------------------------------===//
722 // Lower helper functions
723 //===----------------------------------------------------------------------===//
725 // AddLiveIn - This helper function adds the specified physical register to the
726 // MachineFunction as a live in value. It also creates a corresponding
727 // virtual register for it.
729 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
731 assert(RC->contains(PReg) && "Not the correct regclass!");
732 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
733 MF.getRegInfo().addLiveIn(PReg, VReg);
737 // Get fp branch code (not opcode) from condition code.
738 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
739 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
740 return Mips::BRANCH_T;
742 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
743 "Invalid CondCode.");
745 return Mips::BRANCH_F;
749 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
751 const MipsSubtarget* Subtarget,
752 const TargetInstrInfo *TII,
753 bool isFPCmp, unsigned Opc) {
754 // There is no need to expand CMov instructions if target has
755 // conditional moves.
756 if (Subtarget->hasCondMov())
759 // To "insert" a SELECT_CC instruction, we actually have to insert the
760 // diamond control-flow pattern. The incoming instruction knows the
761 // destination vreg to set, the condition code register to branch on, the
762 // true/false values to select between, and a branch opcode to use.
763 const BasicBlock *LLVM_BB = BB->getBasicBlock();
764 MachineFunction::iterator It = BB;
771 // bNE r1, r0, copy1MBB
772 // fallthrough --> copy0MBB
773 MachineBasicBlock *thisMBB = BB;
774 MachineFunction *F = BB->getParent();
775 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
776 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
777 F->insert(It, copy0MBB);
778 F->insert(It, sinkMBB);
780 // Transfer the remainder of BB and its successor edges to sinkMBB.
781 sinkMBB->splice(sinkMBB->begin(), BB,
782 llvm::next(MachineBasicBlock::iterator(MI)),
784 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
786 // Next, add the true and fallthrough blocks as its successors.
787 BB->addSuccessor(copy0MBB);
788 BB->addSuccessor(sinkMBB);
790 // Emit the right instruction according to the type of the operands compared
792 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
794 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
795 .addReg(Mips::ZERO).addMBB(sinkMBB);
799 // # fallthrough to sinkMBB
802 // Update machine-CFG edges
803 BB->addSuccessor(sinkMBB);
806 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
811 BuildMI(*BB, BB->begin(), dl,
812 TII->get(Mips::PHI), MI->getOperand(0).getReg())
813 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
814 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
816 BuildMI(*BB, BB->begin(), dl,
817 TII->get(Mips::PHI), MI->getOperand(0).getReg())
818 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
819 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
821 MI->eraseFromParent(); // The pseudo instruction is gone now.
826 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
827 MachineBasicBlock *BB) const {
828 switch (MI->getOpcode()) {
829 default: llvm_unreachable("Unexpected instr type to insert");
830 case Mips::ATOMIC_LOAD_ADD_I8:
831 case Mips::ATOMIC_LOAD_ADD_I8_P8:
832 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
833 case Mips::ATOMIC_LOAD_ADD_I16:
834 case Mips::ATOMIC_LOAD_ADD_I16_P8:
835 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
836 case Mips::ATOMIC_LOAD_ADD_I32:
837 case Mips::ATOMIC_LOAD_ADD_I32_P8:
838 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
839 case Mips::ATOMIC_LOAD_ADD_I64:
840 case Mips::ATOMIC_LOAD_ADD_I64_P8:
841 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
843 case Mips::ATOMIC_LOAD_AND_I8:
844 case Mips::ATOMIC_LOAD_AND_I8_P8:
845 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
846 case Mips::ATOMIC_LOAD_AND_I16:
847 case Mips::ATOMIC_LOAD_AND_I16_P8:
848 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
849 case Mips::ATOMIC_LOAD_AND_I32:
850 case Mips::ATOMIC_LOAD_AND_I32_P8:
851 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
852 case Mips::ATOMIC_LOAD_AND_I64:
853 case Mips::ATOMIC_LOAD_AND_I64_P8:
854 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
856 case Mips::ATOMIC_LOAD_OR_I8:
857 case Mips::ATOMIC_LOAD_OR_I8_P8:
858 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
859 case Mips::ATOMIC_LOAD_OR_I16:
860 case Mips::ATOMIC_LOAD_OR_I16_P8:
861 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
862 case Mips::ATOMIC_LOAD_OR_I32:
863 case Mips::ATOMIC_LOAD_OR_I32_P8:
864 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
865 case Mips::ATOMIC_LOAD_OR_I64:
866 case Mips::ATOMIC_LOAD_OR_I64_P8:
867 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
869 case Mips::ATOMIC_LOAD_XOR_I8:
870 case Mips::ATOMIC_LOAD_XOR_I8_P8:
871 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
872 case Mips::ATOMIC_LOAD_XOR_I16:
873 case Mips::ATOMIC_LOAD_XOR_I16_P8:
874 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
875 case Mips::ATOMIC_LOAD_XOR_I32:
876 case Mips::ATOMIC_LOAD_XOR_I32_P8:
877 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
878 case Mips::ATOMIC_LOAD_XOR_I64:
879 case Mips::ATOMIC_LOAD_XOR_I64_P8:
880 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
882 case Mips::ATOMIC_LOAD_NAND_I8:
883 case Mips::ATOMIC_LOAD_NAND_I8_P8:
884 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
885 case Mips::ATOMIC_LOAD_NAND_I16:
886 case Mips::ATOMIC_LOAD_NAND_I16_P8:
887 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
888 case Mips::ATOMIC_LOAD_NAND_I32:
889 case Mips::ATOMIC_LOAD_NAND_I32_P8:
890 return EmitAtomicBinary(MI, BB, 4, 0, true);
891 case Mips::ATOMIC_LOAD_NAND_I64:
892 case Mips::ATOMIC_LOAD_NAND_I64_P8:
893 return EmitAtomicBinary(MI, BB, 8, 0, true);
895 case Mips::ATOMIC_LOAD_SUB_I8:
896 case Mips::ATOMIC_LOAD_SUB_I8_P8:
897 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
898 case Mips::ATOMIC_LOAD_SUB_I16:
899 case Mips::ATOMIC_LOAD_SUB_I16_P8:
900 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
901 case Mips::ATOMIC_LOAD_SUB_I32:
902 case Mips::ATOMIC_LOAD_SUB_I32_P8:
903 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
904 case Mips::ATOMIC_LOAD_SUB_I64:
905 case Mips::ATOMIC_LOAD_SUB_I64_P8:
906 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
908 case Mips::ATOMIC_SWAP_I8:
909 case Mips::ATOMIC_SWAP_I8_P8:
910 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
911 case Mips::ATOMIC_SWAP_I16:
912 case Mips::ATOMIC_SWAP_I16_P8:
913 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
914 case Mips::ATOMIC_SWAP_I32:
915 case Mips::ATOMIC_SWAP_I32_P8:
916 return EmitAtomicBinary(MI, BB, 4, 0);
917 case Mips::ATOMIC_SWAP_I64:
918 case Mips::ATOMIC_SWAP_I64_P8:
919 return EmitAtomicBinary(MI, BB, 8, 0);
921 case Mips::ATOMIC_CMP_SWAP_I8:
922 case Mips::ATOMIC_CMP_SWAP_I8_P8:
923 return EmitAtomicCmpSwapPartword(MI, BB, 1);
924 case Mips::ATOMIC_CMP_SWAP_I16:
925 case Mips::ATOMIC_CMP_SWAP_I16_P8:
926 return EmitAtomicCmpSwapPartword(MI, BB, 2);
927 case Mips::ATOMIC_CMP_SWAP_I32:
928 case Mips::ATOMIC_CMP_SWAP_I32_P8:
929 return EmitAtomicCmpSwap(MI, BB, 4);
930 case Mips::ATOMIC_CMP_SWAP_I64:
931 case Mips::ATOMIC_CMP_SWAP_I64_P8:
932 return EmitAtomicCmpSwap(MI, BB, 8);
936 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
937 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
939 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
940 unsigned Size, unsigned BinOpcode,
942 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
944 MachineFunction *MF = BB->getParent();
945 MachineRegisterInfo &RegInfo = MF->getRegInfo();
946 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
947 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
948 DebugLoc dl = MI->getDebugLoc();
949 unsigned LL, SC, AND, NOR, ZERO, BEQ;
952 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
953 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
960 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
961 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
964 ZERO = Mips::ZERO_64;
968 unsigned OldVal = MI->getOperand(0).getReg();
969 unsigned Ptr = MI->getOperand(1).getReg();
970 unsigned Incr = MI->getOperand(2).getReg();
972 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
973 unsigned AndRes = RegInfo.createVirtualRegister(RC);
974 unsigned Success = RegInfo.createVirtualRegister(RC);
976 // insert new blocks after the current block
977 const BasicBlock *LLVM_BB = BB->getBasicBlock();
978 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
979 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
980 MachineFunction::iterator It = BB;
982 MF->insert(It, loopMBB);
983 MF->insert(It, exitMBB);
985 // Transfer the remainder of BB and its successor edges to exitMBB.
986 exitMBB->splice(exitMBB->begin(), BB,
987 llvm::next(MachineBasicBlock::iterator(MI)),
989 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
993 // fallthrough --> loopMBB
994 BB->addSuccessor(loopMBB);
995 loopMBB->addSuccessor(loopMBB);
996 loopMBB->addSuccessor(exitMBB);
1000 // <binop> storeval, oldval, incr
1001 // sc success, storeval, 0(ptr)
1002 // beq success, $0, loopMBB
1004 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1006 // and andres, oldval, incr
1007 // nor storeval, $0, andres
1008 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1009 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1010 } else if (BinOpcode) {
1011 // <binop> storeval, oldval, incr
1012 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1016 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1017 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1019 MI->eraseFromParent(); // The instruction is gone now.
1025 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1026 MachineBasicBlock *BB,
1027 unsigned Size, unsigned BinOpcode,
1029 assert((Size == 1 || Size == 2) &&
1030 "Unsupported size for EmitAtomicBinaryPartial.");
1032 MachineFunction *MF = BB->getParent();
1033 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1034 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1035 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1036 DebugLoc dl = MI->getDebugLoc();
1037 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1038 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1040 unsigned Dest = MI->getOperand(0).getReg();
1041 unsigned Ptr = MI->getOperand(1).getReg();
1042 unsigned Incr = MI->getOperand(2).getReg();
1044 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1045 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1046 unsigned Mask = RegInfo.createVirtualRegister(RC);
1047 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1048 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1049 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1050 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1051 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1052 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1053 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1054 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1055 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1056 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1057 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1058 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1059 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1060 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1061 unsigned Success = RegInfo.createVirtualRegister(RC);
1063 // insert new blocks after the current block
1064 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1065 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1066 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1067 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1068 MachineFunction::iterator It = BB;
1070 MF->insert(It, loopMBB);
1071 MF->insert(It, sinkMBB);
1072 MF->insert(It, exitMBB);
1074 // Transfer the remainder of BB and its successor edges to exitMBB.
1075 exitMBB->splice(exitMBB->begin(), BB,
1076 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1077 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1079 BB->addSuccessor(loopMBB);
1080 loopMBB->addSuccessor(loopMBB);
1081 loopMBB->addSuccessor(sinkMBB);
1082 sinkMBB->addSuccessor(exitMBB);
1085 // addiu masklsb2,$0,-4 # 0xfffffffc
1086 // and alignedaddr,ptr,masklsb2
1087 // andi ptrlsb2,ptr,3
1088 // sll shiftamt,ptrlsb2,3
1089 // ori maskupper,$0,255 # 0xff
1090 // sll mask,maskupper,shiftamt
1091 // nor mask2,$0,mask
1092 // sll incr2,incr,shiftamt
1094 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1095 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1096 .addReg(Mips::ZERO).addImm(-4);
1097 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1098 .addReg(Ptr).addReg(MaskLSB2);
1099 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1100 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1101 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1102 .addReg(Mips::ZERO).addImm(MaskImm);
1103 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1104 .addReg(ShiftAmt).addReg(MaskUpper);
1105 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1106 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1108 // atomic.load.binop
1110 // ll oldval,0(alignedaddr)
1111 // binop binopres,oldval,incr2
1112 // and newval,binopres,mask
1113 // and maskedoldval0,oldval,mask2
1114 // or storeval,maskedoldval0,newval
1115 // sc success,storeval,0(alignedaddr)
1116 // beq success,$0,loopMBB
1120 // ll oldval,0(alignedaddr)
1121 // and newval,incr2,mask
1122 // and maskedoldval0,oldval,mask2
1123 // or storeval,maskedoldval0,newval
1124 // sc success,storeval,0(alignedaddr)
1125 // beq success,$0,loopMBB
1128 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1130 // and andres, oldval, incr2
1131 // nor binopres, $0, andres
1132 // and newval, binopres, mask
1133 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1134 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1135 .addReg(Mips::ZERO).addReg(AndRes);
1136 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1137 } else if (BinOpcode) {
1138 // <binop> binopres, oldval, incr2
1139 // and newval, binopres, mask
1140 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1141 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1142 } else {// atomic.swap
1143 // and newval, incr2, mask
1144 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1147 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1148 .addReg(OldVal).addReg(Mask2);
1149 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1150 .addReg(MaskedOldVal0).addReg(NewVal);
1151 BuildMI(BB, dl, TII->get(SC), Success)
1152 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1153 BuildMI(BB, dl, TII->get(Mips::BEQ))
1154 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1157 // and maskedoldval1,oldval,mask
1158 // srl srlres,maskedoldval1,shiftamt
1159 // sll sllres,srlres,24
1160 // sra dest,sllres,24
1162 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1164 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1165 .addReg(OldVal).addReg(Mask);
1166 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1167 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1168 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1169 .addReg(SrlRes).addImm(ShiftImm);
1170 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1171 .addReg(SllRes).addImm(ShiftImm);
1173 MI->eraseFromParent(); // The instruction is gone now.
1179 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1180 MachineBasicBlock *BB,
1181 unsigned Size) const {
1182 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1184 MachineFunction *MF = BB->getParent();
1185 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1186 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1187 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1188 DebugLoc dl = MI->getDebugLoc();
1189 unsigned LL, SC, ZERO, BNE, BEQ;
1192 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1193 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1199 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1200 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1201 ZERO = Mips::ZERO_64;
1206 unsigned Dest = MI->getOperand(0).getReg();
1207 unsigned Ptr = MI->getOperand(1).getReg();
1208 unsigned OldVal = MI->getOperand(2).getReg();
1209 unsigned NewVal = MI->getOperand(3).getReg();
1211 unsigned Success = RegInfo.createVirtualRegister(RC);
1213 // insert new blocks after the current block
1214 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1215 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1216 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1217 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1218 MachineFunction::iterator It = BB;
1220 MF->insert(It, loop1MBB);
1221 MF->insert(It, loop2MBB);
1222 MF->insert(It, exitMBB);
1224 // Transfer the remainder of BB and its successor edges to exitMBB.
1225 exitMBB->splice(exitMBB->begin(), BB,
1226 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1227 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1231 // fallthrough --> loop1MBB
1232 BB->addSuccessor(loop1MBB);
1233 loop1MBB->addSuccessor(exitMBB);
1234 loop1MBB->addSuccessor(loop2MBB);
1235 loop2MBB->addSuccessor(loop1MBB);
1236 loop2MBB->addSuccessor(exitMBB);
1240 // bne dest, oldval, exitMBB
1242 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1243 BuildMI(BB, dl, TII->get(BNE))
1244 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1247 // sc success, newval, 0(ptr)
1248 // beq success, $0, loop1MBB
1250 BuildMI(BB, dl, TII->get(SC), Success)
1251 .addReg(NewVal).addReg(Ptr).addImm(0);
1252 BuildMI(BB, dl, TII->get(BEQ))
1253 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1255 MI->eraseFromParent(); // The instruction is gone now.
1261 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1262 MachineBasicBlock *BB,
1263 unsigned Size) const {
1264 assert((Size == 1 || Size == 2) &&
1265 "Unsupported size for EmitAtomicCmpSwapPartial.");
1267 MachineFunction *MF = BB->getParent();
1268 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1269 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1270 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1271 DebugLoc dl = MI->getDebugLoc();
1272 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1273 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1275 unsigned Dest = MI->getOperand(0).getReg();
1276 unsigned Ptr = MI->getOperand(1).getReg();
1277 unsigned CmpVal = MI->getOperand(2).getReg();
1278 unsigned NewVal = MI->getOperand(3).getReg();
1280 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1281 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1282 unsigned Mask = RegInfo.createVirtualRegister(RC);
1283 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1284 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1285 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1286 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1287 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1288 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1289 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1290 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1291 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1292 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1293 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1294 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1295 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1296 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1297 unsigned Success = RegInfo.createVirtualRegister(RC);
1299 // insert new blocks after the current block
1300 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1301 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1302 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1303 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1304 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1305 MachineFunction::iterator It = BB;
1307 MF->insert(It, loop1MBB);
1308 MF->insert(It, loop2MBB);
1309 MF->insert(It, sinkMBB);
1310 MF->insert(It, exitMBB);
1312 // Transfer the remainder of BB and its successor edges to exitMBB.
1313 exitMBB->splice(exitMBB->begin(), BB,
1314 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1315 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1317 BB->addSuccessor(loop1MBB);
1318 loop1MBB->addSuccessor(sinkMBB);
1319 loop1MBB->addSuccessor(loop2MBB);
1320 loop2MBB->addSuccessor(loop1MBB);
1321 loop2MBB->addSuccessor(sinkMBB);
1322 sinkMBB->addSuccessor(exitMBB);
1324 // FIXME: computation of newval2 can be moved to loop2MBB.
1326 // addiu masklsb2,$0,-4 # 0xfffffffc
1327 // and alignedaddr,ptr,masklsb2
1328 // andi ptrlsb2,ptr,3
1329 // sll shiftamt,ptrlsb2,3
1330 // ori maskupper,$0,255 # 0xff
1331 // sll mask,maskupper,shiftamt
1332 // nor mask2,$0,mask
1333 // andi maskedcmpval,cmpval,255
1334 // sll shiftedcmpval,maskedcmpval,shiftamt
1335 // andi maskednewval,newval,255
1336 // sll shiftednewval,maskednewval,shiftamt
1337 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1338 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1339 .addReg(Mips::ZERO).addImm(-4);
1340 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1341 .addReg(Ptr).addReg(MaskLSB2);
1342 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1343 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1344 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1345 .addReg(Mips::ZERO).addImm(MaskImm);
1346 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1347 .addReg(ShiftAmt).addReg(MaskUpper);
1348 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1349 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1350 .addReg(CmpVal).addImm(MaskImm);
1351 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1352 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1353 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1354 .addReg(NewVal).addImm(MaskImm);
1355 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1356 .addReg(ShiftAmt).addReg(MaskedNewVal);
1359 // ll oldval,0(alginedaddr)
1360 // and maskedoldval0,oldval,mask
1361 // bne maskedoldval0,shiftedcmpval,sinkMBB
1363 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1364 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1365 .addReg(OldVal).addReg(Mask);
1366 BuildMI(BB, dl, TII->get(Mips::BNE))
1367 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1370 // and maskedoldval1,oldval,mask2
1371 // or storeval,maskedoldval1,shiftednewval
1372 // sc success,storeval,0(alignedaddr)
1373 // beq success,$0,loop1MBB
1375 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1376 .addReg(OldVal).addReg(Mask2);
1377 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1378 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1379 BuildMI(BB, dl, TII->get(SC), Success)
1380 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1381 BuildMI(BB, dl, TII->get(Mips::BEQ))
1382 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1385 // srl srlres,maskedoldval0,shiftamt
1386 // sll sllres,srlres,24
1387 // sra dest,sllres,24
1389 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1391 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1392 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1393 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1394 .addReg(SrlRes).addImm(ShiftImm);
1395 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1396 .addReg(SllRes).addImm(ShiftImm);
1398 MI->eraseFromParent(); // The instruction is gone now.
1403 //===----------------------------------------------------------------------===//
1404 // Misc Lower Operation implementation
1405 //===----------------------------------------------------------------------===//
1406 SDValue MipsTargetLowering::
1407 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1409 MachineFunction &MF = DAG.getMachineFunction();
1410 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1411 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1413 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1414 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1415 "Cannot lower if the alignment of the allocated space is larger than \
1416 that of the stack.");
1418 SDValue Chain = Op.getOperand(0);
1419 SDValue Size = Op.getOperand(1);
1420 DebugLoc dl = Op.getDebugLoc();
1422 // Get a reference from Mips stack pointer
1423 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1425 // Subtract the dynamic size from the actual stack size to
1426 // obtain the new stack size.
1427 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1429 // The Sub result contains the new stack start address, so it
1430 // must be placed in the stack pointer register.
1431 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1433 // This node always has two return values: a new stack pointer
1434 // value and a chain
1435 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1436 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1437 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1439 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1442 SDValue MipsTargetLowering::
1443 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1445 // The first operand is the chain, the second is the condition, the third is
1446 // the block to branch to if the condition is true.
1447 SDValue Chain = Op.getOperand(0);
1448 SDValue Dest = Op.getOperand(2);
1449 DebugLoc dl = Op.getDebugLoc();
1451 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1453 // Return if flag is not set by a floating point comparison.
1454 if (CondRes.getOpcode() != MipsISD::FPCmp)
1457 SDValue CCNode = CondRes.getOperand(2);
1459 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1460 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1462 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1466 SDValue MipsTargetLowering::
1467 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1469 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1471 // Return if flag is not set by a floating point comparison.
1472 if (Cond.getOpcode() != MipsISD::FPCmp)
1475 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1479 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1480 SelectionDAG &DAG) const {
1481 // FIXME there isn't actually debug info here
1482 DebugLoc dl = Op.getDebugLoc();
1483 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1485 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1486 SDVTList VTs = DAG.getVTList(MVT::i32);
1488 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1490 // %gp_rel relocation
1491 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1492 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1494 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1495 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1496 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1498 // %hi/%lo relocation
1499 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1501 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1503 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1504 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1505 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1508 EVT ValTy = Op.getValueType();
1509 bool HasGotOfst = (GV->hasInternalLinkage() ||
1510 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1511 unsigned GotFlag = IsN64 ?
1512 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1513 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1514 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1515 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1516 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1517 MachinePointerInfo(), false, false, false, 0);
1518 // On functions and global targets not internal linked only
1519 // a load from got/GP is necessary for PIC to work.
1522 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1523 IsN64 ? MipsII::MO_GOT_OFST :
1525 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1526 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1529 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1530 SelectionDAG &DAG) const {
1531 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1532 // FIXME there isn't actually debug info here
1533 DebugLoc dl = Op.getDebugLoc();
1535 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1536 // %hi/%lo relocation
1537 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1538 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1539 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1540 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1541 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1544 EVT ValTy = Op.getValueType();
1545 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1546 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1547 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1548 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1549 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1550 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1551 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1552 MachinePointerInfo(), false, false, false, 0);
1553 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1554 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1557 SDValue MipsTargetLowering::
1558 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1560 // If the relocation model is PIC, use the General Dynamic TLS Model or
1561 // Local Dynamic TLS model, otherwise use the Initial Exec or
1562 // Local Exec TLS Model.
1564 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1565 DebugLoc dl = GA->getDebugLoc();
1566 const GlobalValue *GV = GA->getGlobal();
1567 EVT PtrVT = getPointerTy();
1569 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1570 // General Dynamic TLS Model
1571 bool LocalDynamic = GV->hasInternalLinkage();
1572 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1573 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1574 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1575 GetGlobalReg(DAG, PtrVT), TGA);
1576 unsigned PtrSize = PtrVT.getSizeInBits();
1577 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1579 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1583 Entry.Node = Argument;
1585 Args.push_back(Entry);
1587 std::pair<SDValue, SDValue> CallResult =
1588 LowerCallTo(DAG.getEntryNode(), PtrTy,
1589 false, false, false, false, 0, CallingConv::C, false, true,
1590 TlsGetAddr, Args, DAG, dl);
1592 SDValue Ret = CallResult.first;
1597 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1598 MipsII::MO_DTPREL_HI);
1599 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1600 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1601 MipsII::MO_DTPREL_LO);
1602 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1603 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1604 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1608 if (GV->isDeclaration()) {
1609 // Initial Exec TLS Model
1610 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1611 MipsII::MO_GOTTPREL);
1612 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1614 Offset = DAG.getLoad(PtrVT, dl,
1615 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1616 false, false, false, 0);
1618 // Local Exec TLS Model
1619 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1620 MipsII::MO_TPREL_HI);
1621 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1622 MipsII::MO_TPREL_LO);
1623 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1624 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1625 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1628 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1629 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1632 SDValue MipsTargetLowering::
1633 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1635 SDValue HiPart, JTI, JTILo;
1636 // FIXME there isn't actually debug info here
1637 DebugLoc dl = Op.getDebugLoc();
1638 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1639 EVT PtrVT = Op.getValueType();
1640 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1642 if (!IsPIC && !IsN64) {
1643 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1644 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1645 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1646 } else {// Emit Load from Global Pointer
1647 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1648 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1649 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1650 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1652 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1653 MachinePointerInfo(), false, false, false, 0);
1654 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1657 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1658 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1661 SDValue MipsTargetLowering::
1662 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1665 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1666 const Constant *C = N->getConstVal();
1667 // FIXME there isn't actually debug info here
1668 DebugLoc dl = Op.getDebugLoc();
1670 // gp_rel relocation
1671 // FIXME: we should reference the constant pool using small data sections,
1672 // but the asm printer currently doesn't support this feature without
1673 // hacking it. This feature should come soon so we can uncomment the
1675 //if (IsInSmallSection(C->getType())) {
1676 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1677 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1678 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1680 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1681 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1682 N->getOffset(), MipsII::MO_ABS_HI);
1683 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1684 N->getOffset(), MipsII::MO_ABS_LO);
1685 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1686 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1687 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1689 EVT ValTy = Op.getValueType();
1690 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1691 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1692 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1693 N->getOffset(), GOTFlag);
1694 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1695 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1696 MachinePointerInfo::getConstantPool(), false,
1698 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1699 N->getOffset(), OFSTFlag);
1700 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1701 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1707 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1708 MachineFunction &MF = DAG.getMachineFunction();
1709 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1711 DebugLoc dl = Op.getDebugLoc();
1712 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1715 // vastart just stores the address of the VarArgsFrameIndex slot into the
1716 // memory location argument.
1717 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1718 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1719 MachinePointerInfo(SV), false, false, 0);
1722 // Called if the size of integer registers is large enough to hold the whole
1723 // floating point number.
1724 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1725 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1726 EVT ValTy = Op.getValueType();
1727 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1728 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1729 DebugLoc dl = Op.getDebugLoc();
1730 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1731 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1732 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1733 DAG.getConstant(Mask - 1, IntValTy));
1734 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1735 DAG.getConstant(Mask, IntValTy));
1736 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1737 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1740 // Called if the size of integer registers is not large enough to hold the whole
1741 // floating point number (e.g. f64 & 32-bit integer register).
1743 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1745 // Use ext/ins instructions if target architecture is Mips32r2.
1746 // Eliminate redundant mfc1 and mtc1 instructions.
1747 unsigned LoIdx = 0, HiIdx = 1;
1750 std::swap(LoIdx, HiIdx);
1752 DebugLoc dl = Op.getDebugLoc();
1753 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1755 DAG.getConstant(LoIdx, MVT::i32));
1756 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1757 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1758 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1759 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1760 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1761 DAG.getConstant(0x7fffffff, MVT::i32));
1762 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1763 DAG.getConstant(0x80000000, MVT::i32));
1764 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1767 std::swap(Word0, Word1);
1769 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1773 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1774 EVT Ty = Op.getValueType();
1776 assert(Ty == MVT::f32 || Ty == MVT::f64);
1778 if (Ty == MVT::f32 || HasMips64)
1779 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1781 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1784 SDValue MipsTargetLowering::
1785 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1787 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1788 "Frame address can only be determined for current frame.");
1790 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1791 MFI->setFrameAddressIsTaken(true);
1792 EVT VT = Op.getValueType();
1793 DebugLoc dl = Op.getDebugLoc();
1794 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1795 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1799 // TODO: set SType according to the desired memory barrier behavior.
1801 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1803 DebugLoc dl = Op.getDebugLoc();
1804 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1805 DAG.getConstant(SType, MVT::i32));
1808 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1809 SelectionDAG& DAG) const {
1810 // FIXME: Need pseudo-fence for 'singlethread' fences
1811 // FIXME: Set SType for weaker fences where supported/appropriate.
1813 DebugLoc dl = Op.getDebugLoc();
1814 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1815 DAG.getConstant(SType, MVT::i32));
1818 //===----------------------------------------------------------------------===//
1819 // Calling Convention Implementation
1820 //===----------------------------------------------------------------------===//
1822 //===----------------------------------------------------------------------===//
1823 // TODO: Implement a generic logic using tblgen that can support this.
1824 // Mips O32 ABI rules:
1826 // i32 - Passed in A0, A1, A2, A3 and stack
1827 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1828 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1829 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1830 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1831 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1834 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1835 //===----------------------------------------------------------------------===//
1837 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1838 MVT LocVT, CCValAssign::LocInfo LocInfo,
1839 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1841 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1843 static const unsigned IntRegs[] = {
1844 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1846 static const unsigned F32Regs[] = {
1847 Mips::F12, Mips::F14
1849 static const unsigned F64Regs[] = {
1854 if (ArgFlags.isByVal()) {
1855 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1856 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1857 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1858 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1859 r < std::min(IntRegsSize, NextReg); ++r)
1860 State.AllocateReg(IntRegs[r]);
1864 // Promote i8 and i16
1865 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1867 if (ArgFlags.isSExt())
1868 LocInfo = CCValAssign::SExt;
1869 else if (ArgFlags.isZExt())
1870 LocInfo = CCValAssign::ZExt;
1872 LocInfo = CCValAssign::AExt;
1877 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1878 // is true: function is vararg, argument is 3rd or higher, there is previous
1879 // argument which is not f32 or f64.
1880 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1881 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1882 unsigned OrigAlign = ArgFlags.getOrigAlign();
1883 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1885 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1886 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1887 // If this is the first part of an i64 arg,
1888 // the allocated register must be either A0 or A2.
1889 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1890 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1892 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1893 // Allocate int register and shadow next int register. If first
1894 // available register is Mips::A1 or Mips::A3, shadow it too.
1895 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1896 if (Reg == Mips::A1 || Reg == Mips::A3)
1897 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1898 State.AllocateReg(IntRegs, IntRegsSize);
1900 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1901 // we are guaranteed to find an available float register
1902 if (ValVT == MVT::f32) {
1903 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1904 // Shadow int register
1905 State.AllocateReg(IntRegs, IntRegsSize);
1907 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1908 // Shadow int registers
1909 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1910 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1911 State.AllocateReg(IntRegs, IntRegsSize);
1912 State.AllocateReg(IntRegs, IntRegsSize);
1915 llvm_unreachable("Cannot handle this ValVT.");
1917 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1918 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1921 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1923 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1925 return false; // CC must always match
1928 static const unsigned Mips64IntRegs[8] =
1929 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1930 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1931 static const unsigned Mips64DPRegs[8] =
1932 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1933 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1935 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1936 CCValAssign::LocInfo LocInfo,
1937 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1938 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1939 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1940 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1942 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1944 // If byval is 16-byte aligned, the first arg register must be even.
1945 if ((Align == 16) && (FirstIdx % 2)) {
1946 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1950 // Mark the registers allocated.
1951 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1952 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1954 // Allocate space on caller's stack.
1955 unsigned Offset = State.AllocateStack(Size, Align);
1958 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1961 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1966 #include "MipsGenCallingConv.inc"
1969 AnalyzeMips64CallOperands(CCState &CCInfo,
1970 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1971 unsigned NumOps = Outs.size();
1972 for (unsigned i = 0; i != NumOps; ++i) {
1973 MVT ArgVT = Outs[i].VT;
1974 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1977 if (Outs[i].IsFixed)
1978 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1980 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1984 dbgs() << "Call operand #" << i << " has unhandled type "
1985 << EVT(ArgVT).getEVTString();
1987 llvm_unreachable(0);
1992 //===----------------------------------------------------------------------===//
1993 // Call Calling Convention Implementation
1994 //===----------------------------------------------------------------------===//
1996 static const unsigned O32IntRegsSize = 4;
1998 static const unsigned O32IntRegs[] = {
1999 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2002 // Return next O32 integer argument register.
2003 static unsigned getNextIntArgReg(unsigned Reg) {
2004 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2005 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2008 // Write ByVal Arg to arg registers and stack.
2010 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2011 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2012 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2013 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2014 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2015 MVT PtrType, bool isLittle) {
2016 unsigned LocMemOffset = VA.getLocMemOffset();
2017 unsigned Offset = 0;
2018 uint32_t RemainingSize = Flags.getByValSize();
2019 unsigned ByValAlign = Flags.getByValAlign();
2021 // Copy the first 4 words of byval arg to registers A0 - A3.
2022 // FIXME: Use a stricter alignment if it enables better optimization in passes
2024 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2025 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2026 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2027 DAG.getConstant(Offset, MVT::i32));
2028 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2029 MachinePointerInfo(), false, false, false,
2030 std::min(ByValAlign, (unsigned )4));
2031 MemOpChains.push_back(LoadVal.getValue(1));
2032 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2033 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2036 if (RemainingSize == 0)
2039 // If there still is a register available for argument passing, write the
2040 // remaining part of the structure to it using subword loads and shifts.
2041 if (LocMemOffset < 4 * 4) {
2042 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2043 "There must be one to three bytes remaining.");
2044 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2045 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2046 DAG.getConstant(Offset, MVT::i32));
2047 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2048 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2049 LoadPtr, MachinePointerInfo(),
2050 MVT::getIntegerVT(LoadSize * 8), false,
2052 MemOpChains.push_back(LoadVal.getValue(1));
2054 // If target is big endian, shift it to the most significant half-word or
2057 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2058 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2061 RemainingSize -= LoadSize;
2063 // Read second subword if necessary.
2064 if (RemainingSize != 0) {
2065 assert(RemainingSize == 1 && "There must be one byte remaining.");
2066 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2067 DAG.getConstant(Offset, MVT::i32));
2068 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2069 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2070 LoadPtr, MachinePointerInfo(),
2071 MVT::i8, false, false, Alignment);
2072 MemOpChains.push_back(Subword.getValue(1));
2073 // Insert the loaded byte to LoadVal.
2074 // FIXME: Use INS if supported by target.
2075 unsigned ShiftAmt = isLittle ? 16 : 8;
2076 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2077 DAG.getConstant(ShiftAmt, MVT::i32));
2078 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2081 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2082 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2086 // Create a fixed object on stack at offset LocMemOffset and copy
2087 // remaining part of byval arg to it using memcpy.
2088 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2089 DAG.getConstant(Offset, MVT::i32));
2090 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2091 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2092 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2093 DAG.getConstant(RemainingSize, MVT::i32),
2094 std::min(ByValAlign, (unsigned)4),
2095 /*isVolatile=*/false, /*AlwaysInline=*/false,
2096 MachinePointerInfo(0), MachinePointerInfo(0));
2099 // Copy Mips64 byVal arg to registers and stack.
2101 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2102 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2103 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2104 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2105 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2106 EVT PtrTy, bool isLittle) {
2107 unsigned ByValSize = Flags.getByValSize();
2108 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2109 bool IsRegLoc = VA.isRegLoc();
2110 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2111 unsigned LocMemOffset = 0;
2112 unsigned MemCpySize = ByValSize;
2115 LocMemOffset = VA.getLocMemOffset();
2117 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2119 const unsigned *RegEnd = Mips64IntRegs + 8;
2121 // Copy double words to registers.
2122 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2123 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2124 DAG.getConstant(Offset, PtrTy));
2125 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2126 MachinePointerInfo(), false, false, false,
2128 MemOpChains.push_back(LoadVal.getValue(1));
2129 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2132 // Return if the struct has been fully copied.
2133 if (!(MemCpySize = ByValSize - Offset))
2136 // If there is an argument register available, copy the remainder of the
2137 // byval argument with sub-doubleword loads and shifts.
2138 if (Reg != RegEnd) {
2139 assert((ByValSize < Offset + 8) &&
2140 "Size of the remainder should be smaller than 8-byte.");
2142 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2143 unsigned RemSize = ByValSize - Offset;
2145 if (RemSize < LoadSize)
2148 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2149 DAG.getConstant(Offset, PtrTy));
2151 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2152 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2153 false, false, Alignment);
2154 MemOpChains.push_back(LoadVal.getValue(1));
2156 // Offset in number of bits from double word boundary.
2157 unsigned OffsetDW = (Offset % 8) * 8;
2158 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2159 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2160 DAG.getConstant(Shamt, MVT::i32));
2162 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2165 Alignment = std::min(Alignment, LoadSize);
2168 RegsToPass.push_back(std::make_pair(*Reg, Val));
2173 assert(MemCpySize && "MemCpySize must not be zero.");
2175 // Create a fixed object on stack at offset LocMemOffset and copy
2176 // remainder of byval arg to it with memcpy.
2177 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2178 DAG.getConstant(Offset, PtrTy));
2179 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2180 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2181 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2182 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2183 /*isVolatile=*/false, /*AlwaysInline=*/false,
2184 MachinePointerInfo(0), MachinePointerInfo(0));
2187 /// LowerCall - functions arguments are copied from virtual regs to
2188 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2189 /// TODO: isTailCall.
2191 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2192 CallingConv::ID CallConv, bool isVarArg,
2194 const SmallVectorImpl<ISD::OutputArg> &Outs,
2195 const SmallVectorImpl<SDValue> &OutVals,
2196 const SmallVectorImpl<ISD::InputArg> &Ins,
2197 DebugLoc dl, SelectionDAG &DAG,
2198 SmallVectorImpl<SDValue> &InVals) const {
2199 // MIPs target does not yet support tail call optimization.
2202 MachineFunction &MF = DAG.getMachineFunction();
2203 MachineFrameInfo *MFI = MF.getFrameInfo();
2204 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2205 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2206 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2208 // Analyze operands of the call, assigning locations to each operand.
2209 SmallVector<CCValAssign, 16> ArgLocs;
2210 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2211 getTargetMachine(), ArgLocs, *DAG.getContext());
2214 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2216 AnalyzeMips64CallOperands(CCInfo, Outs);
2218 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2220 // Get a count of how many bytes are to be pushed on the stack.
2221 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2223 // Chain is the output chain of the last Load/Store or CopyToReg node.
2224 // ByValChain is the output chain of the last Memcpy node created for copying
2225 // byval arguments to the stack.
2226 SDValue Chain, CallSeqStart, ByValChain;
2227 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2228 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2229 ByValChain = InChain;
2231 // If this is the first call, create a stack frame object that points to
2232 // a location to which .cprestore saves $gp.
2233 if (IsO32 && IsPIC && MipsFI->globalBaseRegFixed() && !MipsFI->getGPFI())
2234 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2236 // Get the frame index of the stack frame object that points to the location
2237 // of dynamically allocated area on the stack.
2238 int DynAllocFI = MipsFI->getDynAllocFI();
2240 // Update size of the maximum argument space.
2241 // For O32, a minimum of four words (16 bytes) of argument space is
2244 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2246 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2248 if (MaxCallFrameSize < NextStackOffset) {
2249 MipsFI->setMaxCallFrameSize(NextStackOffset);
2251 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2252 // allocated stack space. These offsets must be aligned to a boundary
2253 // determined by the stack alignment of the ABI.
2254 unsigned StackAlignment = TFL->getStackAlignment();
2255 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2256 StackAlignment * StackAlignment;
2258 if (MipsFI->needGPSaveRestore())
2259 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2261 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2264 // With EABI is it possible to have 16 args on registers.
2265 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2266 SmallVector<SDValue, 8> MemOpChains;
2268 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2270 // Walk the register/memloc assignments, inserting copies/loads.
2271 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2272 SDValue Arg = OutVals[i];
2273 CCValAssign &VA = ArgLocs[i];
2274 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2275 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2278 if (Flags.isByVal()) {
2279 assert(Flags.getByValSize() &&
2280 "ByVal args of size 0 should have been ignored by front-end.");
2282 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2283 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2284 Subtarget->isLittle());
2286 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2287 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2288 Subtarget->isLittle());
2292 // Promote the value if needed.
2293 switch (VA.getLocInfo()) {
2294 default: llvm_unreachable("Unknown loc info!");
2295 case CCValAssign::Full:
2296 if (VA.isRegLoc()) {
2297 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2298 (ValVT == MVT::f64 && LocVT == MVT::i64))
2299 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2300 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2301 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2302 Arg, DAG.getConstant(0, MVT::i32));
2303 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2304 Arg, DAG.getConstant(1, MVT::i32));
2305 if (!Subtarget->isLittle())
2307 unsigned LocRegLo = VA.getLocReg();
2308 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2309 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2310 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2315 case CCValAssign::SExt:
2316 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2318 case CCValAssign::ZExt:
2319 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2321 case CCValAssign::AExt:
2322 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2326 // Arguments that can be passed on register must be kept at
2327 // RegsToPass vector
2328 if (VA.isRegLoc()) {
2329 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2333 // Register can't get to this point...
2334 assert(VA.isMemLoc());
2336 // Create the frame index object for this incoming parameter
2337 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2338 VA.getLocMemOffset(), true);
2339 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2341 // emit ISD::STORE whichs stores the
2342 // parameter value to a stack Location
2343 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2344 MachinePointerInfo(), false, false, 0));
2347 // Extend range of indices of frame objects for outgoing arguments that were
2348 // created during this function call. Skip this step if no such objects were
2351 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2353 // If a memcpy has been created to copy a byval arg to a stack, replace the
2354 // chain input of CallSeqStart with ByValChain.
2355 if (InChain != ByValChain)
2356 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2357 NextStackOffsetVal);
2359 // Transform all store nodes into one single node because all store
2360 // nodes are independent of each other.
2361 if (!MemOpChains.empty())
2362 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2363 &MemOpChains[0], MemOpChains.size());
2365 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2366 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2367 // node so that legalize doesn't hack it.
2368 unsigned char OpFlag;
2369 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2370 bool GlobalOrExternal = false;
2373 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2374 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2375 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2376 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2377 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2379 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2382 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2383 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2384 getPointerTy(), 0, OpFlag);
2387 GlobalOrExternal = true;
2389 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2390 if (IsN64 || (!IsO32 && IsPIC))
2391 OpFlag = MipsII::MO_GOT_DISP;
2392 else if (!IsPIC) // !N64 && static
2393 OpFlag = MipsII::MO_NO_FLAG;
2395 OpFlag = MipsII::MO_GOT_CALL;
2396 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2398 GlobalOrExternal = true;
2403 // Create nodes that load address of callee and copy it to T9
2405 if (GlobalOrExternal) {
2406 // Load callee address
2407 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2408 GetGlobalReg(DAG, getPointerTy()), Callee);
2409 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2410 Callee, MachinePointerInfo::getGOT(),
2411 false, false, false, 0);
2413 // Use GOT+LO if callee has internal linkage.
2414 if (CalleeLo.getNode()) {
2415 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2416 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2422 // T9 should contain the address of the callee function if
2423 // -reloction-model=pic or it is an indirect call.
2424 if (IsPICCall || !GlobalOrExternal) {
2426 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2427 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2428 InFlag = Chain.getValue(1);
2429 Callee = DAG.getRegister(T9Reg, getPointerTy());
2432 // Build a sequence of copy-to-reg nodes chained together with token
2433 // chain and flag operands which copy the outgoing args into registers.
2434 // The InFlag in necessary since all emitted instructions must be
2436 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2437 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2438 RegsToPass[i].second, InFlag);
2439 InFlag = Chain.getValue(1);
2442 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2443 // = Chain, Callee, Reg#1, Reg#2, ...
2445 // Returns a chain & a flag for retval copy to use.
2446 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2447 SmallVector<SDValue, 8> Ops;
2448 Ops.push_back(Chain);
2449 Ops.push_back(Callee);
2451 // Add argument registers to the end of the list so that they are
2452 // known live into the call.
2453 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2454 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2455 RegsToPass[i].second.getValueType()));
2457 if (InFlag.getNode())
2458 Ops.push_back(InFlag);
2460 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2461 InFlag = Chain.getValue(1);
2463 // Create the CALLSEQ_END node.
2464 Chain = DAG.getCALLSEQ_END(Chain,
2465 DAG.getIntPtrConstant(NextStackOffset, true),
2466 DAG.getIntPtrConstant(0, true), InFlag);
2467 InFlag = Chain.getValue(1);
2469 // Handle result values, copying them out of physregs into vregs that we
2471 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2472 Ins, dl, DAG, InVals);
2475 /// LowerCallResult - Lower the result values of a call into the
2476 /// appropriate copies out of appropriate physical registers.
2478 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2479 CallingConv::ID CallConv, bool isVarArg,
2480 const SmallVectorImpl<ISD::InputArg> &Ins,
2481 DebugLoc dl, SelectionDAG &DAG,
2482 SmallVectorImpl<SDValue> &InVals) const {
2483 // Assign locations to each value returned by this call.
2484 SmallVector<CCValAssign, 16> RVLocs;
2485 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2486 getTargetMachine(), RVLocs, *DAG.getContext());
2488 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2490 // Copy all of the result registers out of their specified physreg.
2491 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2492 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2493 RVLocs[i].getValVT(), InFlag).getValue(1);
2494 InFlag = Chain.getValue(2);
2495 InVals.push_back(Chain.getValue(0));
2501 //===----------------------------------------------------------------------===//
2502 // Formal Arguments Calling Convention Implementation
2503 //===----------------------------------------------------------------------===//
2504 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2505 std::vector<SDValue>& OutChains,
2506 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2507 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2508 unsigned LocMem = VA.getLocMemOffset();
2509 unsigned FirstWord = LocMem / 4;
2511 // copy register A0 - A3 to frame object
2512 for (unsigned i = 0; i < NumWords; ++i) {
2513 unsigned CurWord = FirstWord + i;
2514 if (CurWord >= O32IntRegsSize)
2517 unsigned SrcReg = O32IntRegs[CurWord];
2518 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2519 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2520 DAG.getConstant(i * 4, MVT::i32));
2521 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2522 StorePtr, MachinePointerInfo(), false,
2524 OutChains.push_back(Store);
2528 // Create frame object on stack and copy registers used for byval passing to it.
2530 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2531 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2532 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2533 MachineFrameInfo *MFI, bool IsRegLoc,
2534 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2536 const unsigned *Reg = Mips64IntRegs + 8;
2537 int FOOffset; // Frame object offset from virtual frame pointer.
2540 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2541 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2544 FOOffset = VA.getLocMemOffset();
2546 // Create frame object.
2547 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2548 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2549 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2550 InVals.push_back(FIN);
2552 // Copy arg registers.
2553 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2555 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2556 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2557 DAG.getConstant(I * 8, PtrTy));
2558 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2559 StorePtr, MachinePointerInfo(), false,
2561 OutChains.push_back(Store);
2567 /// LowerFormalArguments - transform physical registers into virtual registers
2568 /// and generate load operations for arguments places on the stack.
2570 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2571 CallingConv::ID CallConv,
2573 const SmallVectorImpl<ISD::InputArg> &Ins,
2574 DebugLoc dl, SelectionDAG &DAG,
2575 SmallVectorImpl<SDValue> &InVals)
2577 MachineFunction &MF = DAG.getMachineFunction();
2578 MachineFrameInfo *MFI = MF.getFrameInfo();
2579 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2581 MipsFI->setVarArgsFrameIndex(0);
2583 // Used with vargs to acumulate store chains.
2584 std::vector<SDValue> OutChains;
2586 // Assign locations to all of the incoming arguments.
2587 SmallVector<CCValAssign, 16> ArgLocs;
2588 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2589 getTargetMachine(), ArgLocs, *DAG.getContext());
2592 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2594 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2596 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2598 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2599 CCValAssign &VA = ArgLocs[i];
2600 EVT ValVT = VA.getValVT();
2601 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2602 bool IsRegLoc = VA.isRegLoc();
2604 if (Flags.isByVal()) {
2605 assert(Flags.getByValSize() &&
2606 "ByVal args of size 0 should have been ignored by front-end.");
2608 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2609 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2611 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2612 InVals.push_back(FIN);
2613 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2615 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2616 MFI, IsRegLoc, InVals, MipsFI,
2621 // Arguments stored on registers
2623 EVT RegVT = VA.getLocVT();
2624 unsigned ArgReg = VA.getLocReg();
2625 const TargetRegisterClass *RC;
2627 if (RegVT == MVT::i32)
2628 RC = Mips::CPURegsRegisterClass;
2629 else if (RegVT == MVT::i64)
2630 RC = Mips::CPU64RegsRegisterClass;
2631 else if (RegVT == MVT::f32)
2632 RC = Mips::FGR32RegisterClass;
2633 else if (RegVT == MVT::f64)
2634 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2636 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2638 // Transform the arguments stored on
2639 // physical registers into virtual ones
2640 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2641 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2643 // If this is an 8 or 16-bit value, it has been passed promoted
2644 // to 32 bits. Insert an assert[sz]ext to capture this, then
2645 // truncate to the right size.
2646 if (VA.getLocInfo() != CCValAssign::Full) {
2647 unsigned Opcode = 0;
2648 if (VA.getLocInfo() == CCValAssign::SExt)
2649 Opcode = ISD::AssertSext;
2650 else if (VA.getLocInfo() == CCValAssign::ZExt)
2651 Opcode = ISD::AssertZext;
2653 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2654 DAG.getValueType(ValVT));
2655 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2658 // Handle floating point arguments passed in integer registers.
2659 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2660 (RegVT == MVT::i64 && ValVT == MVT::f64))
2661 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2662 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2663 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2664 getNextIntArgReg(ArgReg), RC);
2665 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2666 if (!Subtarget->isLittle())
2667 std::swap(ArgValue, ArgValue2);
2668 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2669 ArgValue, ArgValue2);
2672 InVals.push_back(ArgValue);
2673 } else { // VA.isRegLoc()
2676 assert(VA.isMemLoc());
2678 // The stack pointer offset is relative to the caller stack frame.
2679 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2680 VA.getLocMemOffset(), true);
2682 // Create load nodes to retrieve arguments from the stack
2683 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2684 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2685 MachinePointerInfo::getFixedStack(LastFI),
2686 false, false, false, 0));
2690 // The mips ABIs for returning structs by value requires that we copy
2691 // the sret argument into $v0 for the return. Save the argument into
2692 // a virtual register so that we can access it from the return points.
2693 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2694 unsigned Reg = MipsFI->getSRetReturnReg();
2696 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2697 MipsFI->setSRetReturnReg(Reg);
2699 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2700 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2704 unsigned NumOfRegs = IsO32 ? 4 : 8;
2705 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2706 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2707 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2708 const TargetRegisterClass *RC
2709 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2710 unsigned RegSize = RC->getSize();
2711 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2713 // Offset of the first variable argument from stack pointer.
2714 int FirstVaArgOffset;
2716 if (IsO32 || (Idx == NumOfRegs)) {
2718 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2720 FirstVaArgOffset = RegSlotOffset;
2722 // Record the frame index of the first variable argument
2723 // which is a value necessary to VASTART.
2724 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2725 MipsFI->setVarArgsFrameIndex(LastFI);
2727 // Copy the integer registers that have not been used for argument passing
2728 // to the argument register save area. For O32, the save area is allocated
2729 // in the caller's stack frame, while for N32/64, it is allocated in the
2730 // callee's stack frame.
2731 for (int StackOffset = RegSlotOffset;
2732 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2733 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2734 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2735 MVT::getIntegerVT(RegSize * 8));
2736 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2737 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2738 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2739 MachinePointerInfo(), false, false, 0));
2743 MipsFI->setLastInArgFI(LastFI);
2745 // All stores are grouped in one node to allow the matching between
2746 // the size of Ins and InVals. This only happens when on varg functions
2747 if (!OutChains.empty()) {
2748 OutChains.push_back(Chain);
2749 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2750 &OutChains[0], OutChains.size());
2756 //===----------------------------------------------------------------------===//
2757 // Return Value Calling Convention Implementation
2758 //===----------------------------------------------------------------------===//
2761 MipsTargetLowering::LowerReturn(SDValue Chain,
2762 CallingConv::ID CallConv, bool isVarArg,
2763 const SmallVectorImpl<ISD::OutputArg> &Outs,
2764 const SmallVectorImpl<SDValue> &OutVals,
2765 DebugLoc dl, SelectionDAG &DAG) const {
2767 // CCValAssign - represent the assignment of
2768 // the return value to a location
2769 SmallVector<CCValAssign, 16> RVLocs;
2771 // CCState - Info about the registers and stack slot.
2772 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2773 getTargetMachine(), RVLocs, *DAG.getContext());
2775 // Analize return values.
2776 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2778 // If this is the first return lowered for this function, add
2779 // the regs to the liveout set for the function.
2780 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2781 for (unsigned i = 0; i != RVLocs.size(); ++i)
2782 if (RVLocs[i].isRegLoc())
2783 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2788 // Copy the result values into the output registers.
2789 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2790 CCValAssign &VA = RVLocs[i];
2791 assert(VA.isRegLoc() && "Can only return in registers!");
2793 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2795 // guarantee that all emitted copies are
2796 // stuck together, avoiding something bad
2797 Flag = Chain.getValue(1);
2800 // The mips ABIs for returning structs by value requires that we copy
2801 // the sret argument into $v0 for the return. We saved the argument into
2802 // a virtual register in the entry block, so now we copy the value out
2804 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2805 MachineFunction &MF = DAG.getMachineFunction();
2806 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2807 unsigned Reg = MipsFI->getSRetReturnReg();
2810 llvm_unreachable("sret virtual register not created in the entry block");
2811 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2813 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2814 Flag = Chain.getValue(1);
2817 // Return on Mips is always a "jr $ra"
2819 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2820 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2822 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2823 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2826 //===----------------------------------------------------------------------===//
2827 // Mips Inline Assembly Support
2828 //===----------------------------------------------------------------------===//
2830 /// getConstraintType - Given a constraint letter, return the type of
2831 /// constraint it is for this target.
2832 MipsTargetLowering::ConstraintType MipsTargetLowering::
2833 getConstraintType(const std::string &Constraint) const
2835 // Mips specific constrainy
2836 // GCC config/mips/constraints.md
2838 // 'd' : An address register. Equivalent to r
2839 // unless generating MIPS16 code.
2840 // 'y' : Equivalent to r; retained for
2841 // backwards compatibility.
2842 // 'f' : Floating Point registers.
2843 if (Constraint.size() == 1) {
2844 switch (Constraint[0]) {
2849 return C_RegisterClass;
2852 return TargetLowering::getConstraintType(Constraint);
2855 /// Examine constraint type and operand type and determine a weight value.
2856 /// This object must already have been set up with the operand type
2857 /// and the current alternative constraint selected.
2858 TargetLowering::ConstraintWeight
2859 MipsTargetLowering::getSingleConstraintMatchWeight(
2860 AsmOperandInfo &info, const char *constraint) const {
2861 ConstraintWeight weight = CW_Invalid;
2862 Value *CallOperandVal = info.CallOperandVal;
2863 // If we don't have a value, we can't do a match,
2864 // but allow it at the lowest weight.
2865 if (CallOperandVal == NULL)
2867 Type *type = CallOperandVal->getType();
2868 // Look at the constraint type.
2869 switch (*constraint) {
2871 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2875 if (type->isIntegerTy())
2876 weight = CW_Register;
2879 if (type->isFloatTy())
2880 weight = CW_Register;
2886 /// Given a register class constraint, like 'r', if this corresponds directly
2887 /// to an LLVM register class, return a register of 0 and the register class
2889 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2890 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2892 if (Constraint.size() == 1) {
2893 switch (Constraint[0]) {
2894 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2895 case 'y': // Same as 'r'. Exists for compatibility.
2898 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2899 assert(VT == MVT::i64 && "Unexpected type.");
2900 return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
2903 return std::make_pair(0U, Mips::FGR32RegisterClass);
2904 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2905 if (Subtarget->isFP64bit())
2906 return std::make_pair(0U, Mips::FGR64RegisterClass);
2908 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2912 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2916 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2917 // The Mips target isn't yet aware of offsets.
2921 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2922 if (VT != MVT::f32 && VT != MVT::f64)
2924 if (Imm.isNegZero())
2926 return Imm.isZero();
2929 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2931 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2933 return TargetLowering::getJumpTableEncoding();