1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "InstPrinter/MipsInstPrinter.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
38 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
40 case MipsISD::JmpLink: return "MipsISD::JmpLink";
41 case MipsISD::Hi: return "MipsISD::Hi";
42 case MipsISD::Lo: return "MipsISD::Lo";
43 case MipsISD::GPRel: return "MipsISD::GPRel";
44 case MipsISD::TlsGd: return "MipsISD::TlsGd";
45 case MipsISD::TprelHi: return "MipsISD::TprelHi";
46 case MipsISD::TprelLo: return "MipsISD::TprelLo";
47 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
48 case MipsISD::Ret: return "MipsISD::Ret";
49 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
50 case MipsISD::FPCmp: return "MipsISD::FPCmp";
51 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
52 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
53 case MipsISD::FPRound: return "MipsISD::FPRound";
54 case MipsISD::MAdd: return "MipsISD::MAdd";
55 case MipsISD::MAddu: return "MipsISD::MAddu";
56 case MipsISD::MSub: return "MipsISD::MSub";
57 case MipsISD::MSubu: return "MipsISD::MSubu";
58 case MipsISD::DivRem: return "MipsISD::DivRem";
59 case MipsISD::DivRemU: return "MipsISD::DivRemU";
60 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
61 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
62 case MipsISD::WrapperPIC: return "MipsISD::WrapperPIC";
63 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
64 case MipsISD::Sync: return "MipsISD::Sync";
70 MipsTargetLowering(MipsTargetMachine &TM)
71 : TargetLowering(TM, new MipsTargetObjectFile()) {
72 Subtarget = &TM.getSubtarget<MipsSubtarget>();
74 // Mips does not have i1 type, so use i32 for
75 // setcc operations results (slt, sgt, ...).
76 setBooleanContents(ZeroOrOneBooleanContent);
78 // Set up the register classes
79 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
80 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
82 // When dealing with single precision only, use libcalls
83 if (!Subtarget->isSingleFloat())
84 if (!Subtarget->isFP64bit())
85 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
87 // Load extented operations for i1 types must be promoted
88 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
89 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
90 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
92 // MIPS doesn't have extending float->double load/store
93 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
94 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
96 // Used by legalize types to correctly generate the setcc result.
97 // Without this, every float setcc comes with a AND/OR with the result,
98 // we don't want this, since the fpcmp result goes to a flag register,
99 // which is used implicitly by brcond and select operations.
100 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
102 // Mips Custom Operations
103 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
104 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
105 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
106 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
107 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
108 setOperationAction(ISD::SELECT, MVT::f32, Custom);
109 setOperationAction(ISD::SELECT, MVT::f64, Custom);
110 setOperationAction(ISD::SELECT, MVT::i32, Custom);
111 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
112 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
113 setOperationAction(ISD::VASTART, MVT::Other, Custom);
115 setOperationAction(ISD::SDIV, MVT::i32, Expand);
116 setOperationAction(ISD::SREM, MVT::i32, Expand);
117 setOperationAction(ISD::UDIV, MVT::i32, Expand);
118 setOperationAction(ISD::UREM, MVT::i32, Expand);
120 // Operations not directly supported by Mips.
121 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
122 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
123 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
124 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
125 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
127 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
128 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
129 setOperationAction(ISD::ROTL, MVT::i32, Expand);
131 if (!Subtarget->isMips32r2())
132 setOperationAction(ISD::ROTR, MVT::i32, Expand);
134 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
135 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
136 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
137 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
138 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
139 setOperationAction(ISD::FSIN, MVT::f32, Expand);
140 setOperationAction(ISD::FSIN, MVT::f64, Expand);
141 setOperationAction(ISD::FCOS, MVT::f32, Expand);
142 setOperationAction(ISD::FCOS, MVT::f64, Expand);
143 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
144 setOperationAction(ISD::FPOW, MVT::f32, Expand);
145 setOperationAction(ISD::FPOW, MVT::f64, Expand);
146 setOperationAction(ISD::FLOG, MVT::f32, Expand);
147 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
148 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
149 setOperationAction(ISD::FEXP, MVT::f32, Expand);
150 setOperationAction(ISD::FMA, MVT::f32, Expand);
151 setOperationAction(ISD::FMA, MVT::f64, Expand);
153 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
154 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
156 setOperationAction(ISD::VAARG, MVT::Other, Expand);
157 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
158 setOperationAction(ISD::VAEND, MVT::Other, Expand);
160 // Use the default for now
161 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
162 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
164 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
165 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
167 if (Subtarget->isSingleFloat())
168 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
170 if (!Subtarget->hasSEInReg()) {
171 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
172 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
175 if (!Subtarget->hasBitCount())
176 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
178 if (!Subtarget->hasSwap())
179 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
181 setTargetDAGCombine(ISD::ADDE);
182 setTargetDAGCombine(ISD::SUBE);
183 setTargetDAGCombine(ISD::SDIVREM);
184 setTargetDAGCombine(ISD::UDIVREM);
185 setTargetDAGCombine(ISD::SETCC);
187 setMinFunctionAlignment(2);
189 setStackPointerRegisterToSaveRestore(Mips::SP);
190 computeRegisterProperties();
192 setExceptionPointerRegister(Mips::A0);
193 setExceptionSelectorRegister(Mips::A1);
196 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
201 // Transforms a subgraph in CurDAG if the following pattern is found:
202 // (addc multLo, Lo0), (adde multHi, Hi0),
204 // multHi/Lo: product of multiplication
205 // Lo0: initial value of Lo register
206 // Hi0: initial value of Hi register
207 // Return true if pattern matching was successful.
208 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
209 // ADDENode's second operand must be a flag output of an ADDC node in order
210 // for the matching to be successful.
211 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
213 if (ADDCNode->getOpcode() != ISD::ADDC)
216 SDValue MultHi = ADDENode->getOperand(0);
217 SDValue MultLo = ADDCNode->getOperand(0);
218 SDNode* MultNode = MultHi.getNode();
219 unsigned MultOpc = MultHi.getOpcode();
221 // MultHi and MultLo must be generated by the same node,
222 if (MultLo.getNode() != MultNode)
225 // and it must be a multiplication.
226 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
229 // MultLo amd MultHi must be the first and second output of MultNode
231 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
234 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
235 // of the values of MultNode, in which case MultNode will be removed in later
237 // If there exist users other than ADDENode or ADDCNode, this function returns
238 // here, which will result in MultNode being mapped to a single MULT
239 // instruction node rather than a pair of MULT and MADD instructions being
241 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
244 SDValue Chain = CurDAG->getEntryNode();
245 DebugLoc dl = ADDENode->getDebugLoc();
247 // create MipsMAdd(u) node
248 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
250 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
252 MultNode->getOperand(0),// Factor 0
253 MultNode->getOperand(1),// Factor 1
254 ADDCNode->getOperand(1),// Lo0
255 ADDENode->getOperand(1));// Hi0
257 // create CopyFromReg nodes
258 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
260 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
262 CopyFromLo.getValue(2));
264 // replace uses of adde and addc here
265 if (!SDValue(ADDCNode, 0).use_empty())
266 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
268 if (!SDValue(ADDENode, 0).use_empty())
269 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
275 // Transforms a subgraph in CurDAG if the following pattern is found:
276 // (addc Lo0, multLo), (sube Hi0, multHi),
278 // multHi/Lo: product of multiplication
279 // Lo0: initial value of Lo register
280 // Hi0: initial value of Hi register
281 // Return true if pattern matching was successful.
282 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
283 // SUBENode's second operand must be a flag output of an SUBC node in order
284 // for the matching to be successful.
285 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
287 if (SUBCNode->getOpcode() != ISD::SUBC)
290 SDValue MultHi = SUBENode->getOperand(1);
291 SDValue MultLo = SUBCNode->getOperand(1);
292 SDNode* MultNode = MultHi.getNode();
293 unsigned MultOpc = MultHi.getOpcode();
295 // MultHi and MultLo must be generated by the same node,
296 if (MultLo.getNode() != MultNode)
299 // and it must be a multiplication.
300 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
303 // MultLo amd MultHi must be the first and second output of MultNode
305 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
308 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
309 // of the values of MultNode, in which case MultNode will be removed in later
311 // If there exist users other than SUBENode or SUBCNode, this function returns
312 // here, which will result in MultNode being mapped to a single MULT
313 // instruction node rather than a pair of MULT and MSUB instructions being
315 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
318 SDValue Chain = CurDAG->getEntryNode();
319 DebugLoc dl = SUBENode->getDebugLoc();
321 // create MipsSub(u) node
322 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
324 SDValue MSub = CurDAG->getNode(MultOpc, dl,
326 MultNode->getOperand(0),// Factor 0
327 MultNode->getOperand(1),// Factor 1
328 SUBCNode->getOperand(0),// Lo0
329 SUBENode->getOperand(0));// Hi0
331 // create CopyFromReg nodes
332 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
334 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
336 CopyFromLo.getValue(2));
338 // replace uses of sube and subc here
339 if (!SDValue(SUBCNode, 0).use_empty())
340 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
342 if (!SDValue(SUBENode, 0).use_empty())
343 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
348 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
349 TargetLowering::DAGCombinerInfo &DCI,
350 const MipsSubtarget* Subtarget) {
351 if (DCI.isBeforeLegalize())
354 if (Subtarget->isMips32() && SelectMadd(N, &DAG))
355 return SDValue(N, 0);
360 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
361 TargetLowering::DAGCombinerInfo &DCI,
362 const MipsSubtarget* Subtarget) {
363 if (DCI.isBeforeLegalize())
366 if (Subtarget->isMips32() && SelectMsub(N, &DAG))
367 return SDValue(N, 0);
372 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
373 TargetLowering::DAGCombinerInfo &DCI,
374 const MipsSubtarget* Subtarget) {
375 if (DCI.isBeforeLegalizeOps())
378 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
380 DebugLoc dl = N->getDebugLoc();
382 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
383 N->getOperand(0), N->getOperand(1));
384 SDValue InChain = DAG.getEntryNode();
385 SDValue InGlue = DivRem;
388 if (N->hasAnyUseOfValue(0)) {
389 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
391 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
392 InChain = CopyFromLo.getValue(1);
393 InGlue = CopyFromLo.getValue(2);
397 if (N->hasAnyUseOfValue(1)) {
398 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
399 Mips::HI, MVT::i32, InGlue);
400 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
406 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
408 default: llvm_unreachable("Unknown fp condition code!");
410 case ISD::SETOEQ: return Mips::FCOND_OEQ;
411 case ISD::SETUNE: return Mips::FCOND_UNE;
413 case ISD::SETOLT: return Mips::FCOND_OLT;
415 case ISD::SETOGT: return Mips::FCOND_OGT;
417 case ISD::SETOLE: return Mips::FCOND_OLE;
419 case ISD::SETOGE: return Mips::FCOND_OGE;
420 case ISD::SETULT: return Mips::FCOND_ULT;
421 case ISD::SETULE: return Mips::FCOND_ULE;
422 case ISD::SETUGT: return Mips::FCOND_UGT;
423 case ISD::SETUGE: return Mips::FCOND_UGE;
424 case ISD::SETUO: return Mips::FCOND_UN;
425 case ISD::SETO: return Mips::FCOND_OR;
427 case ISD::SETONE: return Mips::FCOND_ONE;
428 case ISD::SETUEQ: return Mips::FCOND_UEQ;
433 // Returns true if condition code has to be inverted.
434 static bool InvertFPCondCode(Mips::CondCode CC) {
435 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
438 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
441 assert(false && "Illegal Condition Code");
445 // Creates and returns an FPCmp node from a setcc node.
446 // Returns Op if setcc is not a floating point comparison.
447 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
448 // must be a SETCC node
449 if (Op.getOpcode() != ISD::SETCC)
452 SDValue LHS = Op.getOperand(0);
454 if (!LHS.getValueType().isFloatingPoint())
457 SDValue RHS = Op.getOperand(1);
458 DebugLoc dl = Op.getDebugLoc();
460 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
461 // node if necessary.
462 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
464 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
465 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
468 // Creates and returns a CMovFPT/F node.
469 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
470 SDValue False, DebugLoc DL) {
471 bool invert = InvertFPCondCode((Mips::CondCode)
472 cast<ConstantSDNode>(Cond.getOperand(2))
475 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
476 True.getValueType(), True, False, Cond);
479 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
480 TargetLowering::DAGCombinerInfo &DCI,
481 const MipsSubtarget* Subtarget) {
482 if (DCI.isBeforeLegalizeOps())
485 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
487 if (Cond.getOpcode() != MipsISD::FPCmp)
490 SDValue True = DAG.getConstant(1, MVT::i32);
491 SDValue False = DAG.getConstant(0, MVT::i32);
493 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
496 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
498 SelectionDAG &DAG = DCI.DAG;
499 unsigned opc = N->getOpcode();
504 return PerformADDECombine(N, DAG, DCI, Subtarget);
506 return PerformSUBECombine(N, DAG, DCI, Subtarget);
509 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
511 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
517 SDValue MipsTargetLowering::
518 LowerOperation(SDValue Op, SelectionDAG &DAG) const
520 switch (Op.getOpcode())
522 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
523 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
524 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
525 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
526 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
527 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
528 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
529 case ISD::SELECT: return LowerSELECT(Op, DAG);
530 case ISD::VASTART: return LowerVASTART(Op, DAG);
531 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
532 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
533 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
534 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
539 //===----------------------------------------------------------------------===//
540 // Lower helper functions
541 //===----------------------------------------------------------------------===//
543 // AddLiveIn - This helper function adds the specified physical register to the
544 // MachineFunction as a live in value. It also creates a corresponding
545 // virtual register for it.
547 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
549 assert(RC->contains(PReg) && "Not the correct regclass!");
550 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
551 MF.getRegInfo().addLiveIn(PReg, VReg);
555 // Get fp branch code (not opcode) from condition code.
556 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
557 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
558 return Mips::BRANCH_T;
560 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
561 return Mips::BRANCH_F;
563 return Mips::BRANCH_INVALID;
566 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
568 const MipsSubtarget* Subtarget,
569 const TargetInstrInfo *TII,
570 bool isFPCmp, unsigned Opc) {
571 // There is no need to expand CMov instructions if target has
572 // conditional moves.
573 if (Subtarget->hasCondMov())
576 // To "insert" a SELECT_CC instruction, we actually have to insert the
577 // diamond control-flow pattern. The incoming instruction knows the
578 // destination vreg to set, the condition code register to branch on, the
579 // true/false values to select between, and a branch opcode to use.
580 const BasicBlock *LLVM_BB = BB->getBasicBlock();
581 MachineFunction::iterator It = BB;
588 // bNE r1, r0, copy1MBB
589 // fallthrough --> copy0MBB
590 MachineBasicBlock *thisMBB = BB;
591 MachineFunction *F = BB->getParent();
592 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
593 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
594 F->insert(It, copy0MBB);
595 F->insert(It, sinkMBB);
597 // Transfer the remainder of BB and its successor edges to sinkMBB.
598 sinkMBB->splice(sinkMBB->begin(), BB,
599 llvm::next(MachineBasicBlock::iterator(MI)),
601 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
603 // Next, add the true and fallthrough blocks as its successors.
604 BB->addSuccessor(copy0MBB);
605 BB->addSuccessor(sinkMBB);
607 // Emit the right instruction according to the type of the operands compared
609 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
611 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
612 .addReg(Mips::ZERO).addMBB(sinkMBB);
616 // # fallthrough to sinkMBB
619 // Update machine-CFG edges
620 BB->addSuccessor(sinkMBB);
623 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
628 BuildMI(*BB, BB->begin(), dl,
629 TII->get(Mips::PHI), MI->getOperand(0).getReg())
630 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
631 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
633 BuildMI(*BB, BB->begin(), dl,
634 TII->get(Mips::PHI), MI->getOperand(0).getReg())
635 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
636 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
638 MI->eraseFromParent(); // The pseudo instruction is gone now.
643 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
644 MachineBasicBlock *BB) const {
645 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
646 DebugLoc dl = MI->getDebugLoc();
648 switch (MI->getOpcode()) {
650 assert(false && "Unexpected instr type to insert");
655 return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1F);
659 return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1T);
663 return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BNE);
667 return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BEQ);
669 case Mips::ATOMIC_LOAD_ADD_I8:
670 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
671 case Mips::ATOMIC_LOAD_ADD_I16:
672 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
673 case Mips::ATOMIC_LOAD_ADD_I32:
674 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
676 case Mips::ATOMIC_LOAD_AND_I8:
677 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
678 case Mips::ATOMIC_LOAD_AND_I16:
679 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
680 case Mips::ATOMIC_LOAD_AND_I32:
681 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
683 case Mips::ATOMIC_LOAD_OR_I8:
684 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
685 case Mips::ATOMIC_LOAD_OR_I16:
686 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
687 case Mips::ATOMIC_LOAD_OR_I32:
688 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
690 case Mips::ATOMIC_LOAD_XOR_I8:
691 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
692 case Mips::ATOMIC_LOAD_XOR_I16:
693 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
694 case Mips::ATOMIC_LOAD_XOR_I32:
695 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
697 case Mips::ATOMIC_LOAD_NAND_I8:
698 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
699 case Mips::ATOMIC_LOAD_NAND_I16:
700 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
701 case Mips::ATOMIC_LOAD_NAND_I32:
702 return EmitAtomicBinary(MI, BB, 4, 0, true);
704 case Mips::ATOMIC_LOAD_SUB_I8:
705 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
706 case Mips::ATOMIC_LOAD_SUB_I16:
707 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
708 case Mips::ATOMIC_LOAD_SUB_I32:
709 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
711 case Mips::ATOMIC_SWAP_I8:
712 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
713 case Mips::ATOMIC_SWAP_I16:
714 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
715 case Mips::ATOMIC_SWAP_I32:
716 return EmitAtomicBinary(MI, BB, 4, 0);
718 case Mips::ATOMIC_CMP_SWAP_I8:
719 return EmitAtomicCmpSwapPartword(MI, BB, 1);
720 case Mips::ATOMIC_CMP_SWAP_I16:
721 return EmitAtomicCmpSwapPartword(MI, BB, 2);
722 case Mips::ATOMIC_CMP_SWAP_I32:
723 return EmitAtomicCmpSwap(MI, BB, 4);
727 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
728 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
730 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
731 unsigned Size, unsigned BinOpcode,
733 assert(Size == 4 && "Unsupported size for EmitAtomicBinary.");
735 MachineFunction *MF = BB->getParent();
736 MachineRegisterInfo &RegInfo = MF->getRegInfo();
737 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
738 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
739 DebugLoc dl = MI->getDebugLoc();
741 unsigned OldVal = MI->getOperand(0).getReg();
742 unsigned Ptr = MI->getOperand(1).getReg();
743 unsigned Incr = MI->getOperand(2).getReg();
745 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
746 unsigned AndRes = RegInfo.createVirtualRegister(RC);
747 unsigned Success = RegInfo.createVirtualRegister(RC);
749 // insert new blocks after the current block
750 const BasicBlock *LLVM_BB = BB->getBasicBlock();
751 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
752 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
753 MachineFunction::iterator It = BB;
755 MF->insert(It, loopMBB);
756 MF->insert(It, exitMBB);
758 // Transfer the remainder of BB and its successor edges to exitMBB.
759 exitMBB->splice(exitMBB->begin(), BB,
760 llvm::next(MachineBasicBlock::iterator(MI)),
762 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
766 // fallthrough --> loopMBB
767 BB->addSuccessor(loopMBB);
768 loopMBB->addSuccessor(loopMBB);
769 loopMBB->addSuccessor(exitMBB);
773 // <binop> storeval, oldval, incr
774 // sc success, storeval, 0(ptr)
775 // beq success, $0, loopMBB
777 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(Ptr).addImm(0);
779 // and andres, oldval, incr
780 // nor storeval, $0, andres
781 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr);
782 BuildMI(BB, dl, TII->get(Mips::NOR), StoreVal)
783 .addReg(Mips::ZERO).addReg(AndRes);
784 } else if (BinOpcode) {
785 // <binop> storeval, oldval, incr
786 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
790 BuildMI(BB, dl, TII->get(Mips::SC), Success)
791 .addReg(StoreVal).addReg(Ptr).addImm(0);
792 BuildMI(BB, dl, TII->get(Mips::BEQ))
793 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
795 MI->eraseFromParent(); // The instruction is gone now.
801 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
802 MachineBasicBlock *BB,
803 unsigned Size, unsigned BinOpcode,
805 assert((Size == 1 || Size == 2) &&
806 "Unsupported size for EmitAtomicBinaryPartial.");
808 MachineFunction *MF = BB->getParent();
809 MachineRegisterInfo &RegInfo = MF->getRegInfo();
810 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
811 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
812 DebugLoc dl = MI->getDebugLoc();
814 unsigned Dest = MI->getOperand(0).getReg();
815 unsigned Ptr = MI->getOperand(1).getReg();
816 unsigned Incr = MI->getOperand(2).getReg();
818 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
819 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
820 unsigned Mask = RegInfo.createVirtualRegister(RC);
821 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
822 unsigned NewVal = RegInfo.createVirtualRegister(RC);
823 unsigned OldVal = RegInfo.createVirtualRegister(RC);
824 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
825 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
826 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
827 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
828 unsigned AndRes = RegInfo.createVirtualRegister(RC);
829 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
830 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
831 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
832 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
833 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
834 unsigned SllRes = RegInfo.createVirtualRegister(RC);
835 unsigned Success = RegInfo.createVirtualRegister(RC);
837 // insert new blocks after the current block
838 const BasicBlock *LLVM_BB = BB->getBasicBlock();
839 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
840 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
841 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
842 MachineFunction::iterator It = BB;
844 MF->insert(It, loopMBB);
845 MF->insert(It, sinkMBB);
846 MF->insert(It, exitMBB);
848 // Transfer the remainder of BB and its successor edges to exitMBB.
849 exitMBB->splice(exitMBB->begin(), BB,
850 llvm::next(MachineBasicBlock::iterator(MI)),
852 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
854 BB->addSuccessor(loopMBB);
855 loopMBB->addSuccessor(loopMBB);
856 loopMBB->addSuccessor(sinkMBB);
857 sinkMBB->addSuccessor(exitMBB);
860 // addiu masklsb2,$0,-4 # 0xfffffffc
861 // and alignedaddr,ptr,masklsb2
862 // andi ptrlsb2,ptr,3
863 // sll shiftamt,ptrlsb2,3
864 // ori maskupper,$0,255 # 0xff
865 // sll mask,maskupper,shiftamt
867 // sll incr2,incr,shiftamt
869 int64_t MaskImm = (Size == 1) ? 255 : 65535;
870 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
871 .addReg(Mips::ZERO).addImm(-4);
872 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
873 .addReg(Ptr).addReg(MaskLSB2);
874 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
875 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
876 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
877 .addReg(Mips::ZERO).addImm(MaskImm);
878 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
879 .addReg(ShiftAmt).addReg(MaskUpper);
880 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
881 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
886 // ll oldval,0(alignedaddr)
887 // binop binopres,oldval,incr2
888 // and newval,binopres,mask
889 // and maskedoldval0,oldval,mask2
890 // or storeval,maskedoldval0,newval
891 // sc success,storeval,0(alignedaddr)
892 // beq success,$0,loopMBB
896 // ll oldval,0(alignedaddr)
897 // and newval,incr2,mask
898 // and maskedoldval0,oldval,mask2
899 // or storeval,maskedoldval0,newval
900 // sc success,storeval,0(alignedaddr)
901 // beq success,$0,loopMBB
904 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
906 // and andres, oldval, incr2
907 // nor binopres, $0, andres
908 // and newval, binopres, mask
909 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
910 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
911 .addReg(Mips::ZERO).addReg(AndRes);
912 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
913 } else if (BinOpcode) {
914 // <binop> binopres, oldval, incr2
915 // and newval, binopres, mask
916 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
917 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
918 } else {// atomic.swap
919 // and newval, incr2, mask
920 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
923 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
924 .addReg(OldVal).addReg(Mask2);
925 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
926 .addReg(MaskedOldVal0).addReg(NewVal);
927 BuildMI(BB, dl, TII->get(Mips::SC), Success)
928 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
929 BuildMI(BB, dl, TII->get(Mips::BEQ))
930 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
933 // and maskedoldval1,oldval,mask
934 // srl srlres,maskedoldval1,shiftamt
935 // sll sllres,srlres,24
936 // sra dest,sllres,24
938 int64_t ShiftImm = (Size == 1) ? 24 : 16;
940 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
941 .addReg(OldVal).addReg(Mask);
942 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
943 .addReg(ShiftAmt).addReg(MaskedOldVal1);
944 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
945 .addReg(SrlRes).addImm(ShiftImm);
946 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
947 .addReg(SllRes).addImm(ShiftImm);
949 MI->eraseFromParent(); // The instruction is gone now.
955 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
956 MachineBasicBlock *BB,
957 unsigned Size) const {
958 assert(Size == 4 && "Unsupported size for EmitAtomicCmpSwap.");
960 MachineFunction *MF = BB->getParent();
961 MachineRegisterInfo &RegInfo = MF->getRegInfo();
962 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
963 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
964 DebugLoc dl = MI->getDebugLoc();
966 unsigned Dest = MI->getOperand(0).getReg();
967 unsigned Ptr = MI->getOperand(1).getReg();
968 unsigned OldVal = MI->getOperand(2).getReg();
969 unsigned NewVal = MI->getOperand(3).getReg();
971 unsigned Success = RegInfo.createVirtualRegister(RC);
973 // insert new blocks after the current block
974 const BasicBlock *LLVM_BB = BB->getBasicBlock();
975 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
976 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
977 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
978 MachineFunction::iterator It = BB;
980 MF->insert(It, loop1MBB);
981 MF->insert(It, loop2MBB);
982 MF->insert(It, exitMBB);
984 // Transfer the remainder of BB and its successor edges to exitMBB.
985 exitMBB->splice(exitMBB->begin(), BB,
986 llvm::next(MachineBasicBlock::iterator(MI)),
988 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
992 // fallthrough --> loop1MBB
993 BB->addSuccessor(loop1MBB);
994 loop1MBB->addSuccessor(exitMBB);
995 loop1MBB->addSuccessor(loop2MBB);
996 loop2MBB->addSuccessor(loop1MBB);
997 loop2MBB->addSuccessor(exitMBB);
1001 // bne dest, oldval, exitMBB
1003 BuildMI(BB, dl, TII->get(Mips::LL), Dest).addReg(Ptr).addImm(0);
1004 BuildMI(BB, dl, TII->get(Mips::BNE))
1005 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1008 // sc success, newval, 0(ptr)
1009 // beq success, $0, loop1MBB
1011 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1012 .addReg(NewVal).addReg(Ptr).addImm(0);
1013 BuildMI(BB, dl, TII->get(Mips::BEQ))
1014 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1016 MI->eraseFromParent(); // The instruction is gone now.
1022 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1023 MachineBasicBlock *BB,
1024 unsigned Size) const {
1025 assert((Size == 1 || Size == 2) &&
1026 "Unsupported size for EmitAtomicCmpSwapPartial.");
1028 MachineFunction *MF = BB->getParent();
1029 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1030 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1031 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1032 DebugLoc dl = MI->getDebugLoc();
1034 unsigned Dest = MI->getOperand(0).getReg();
1035 unsigned Ptr = MI->getOperand(1).getReg();
1036 unsigned CmpVal = MI->getOperand(2).getReg();
1037 unsigned NewVal = MI->getOperand(3).getReg();
1039 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1040 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1041 unsigned Mask = RegInfo.createVirtualRegister(RC);
1042 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1043 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1044 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1045 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1046 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1047 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1048 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1049 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1050 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1051 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1052 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1053 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1054 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1055 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1056 unsigned Success = RegInfo.createVirtualRegister(RC);
1058 // insert new blocks after the current block
1059 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1060 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1061 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1062 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1063 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1064 MachineFunction::iterator It = BB;
1066 MF->insert(It, loop1MBB);
1067 MF->insert(It, loop2MBB);
1068 MF->insert(It, sinkMBB);
1069 MF->insert(It, exitMBB);
1071 // Transfer the remainder of BB and its successor edges to exitMBB.
1072 exitMBB->splice(exitMBB->begin(), BB,
1073 llvm::next(MachineBasicBlock::iterator(MI)),
1075 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1077 BB->addSuccessor(loop1MBB);
1078 loop1MBB->addSuccessor(sinkMBB);
1079 loop1MBB->addSuccessor(loop2MBB);
1080 loop2MBB->addSuccessor(loop1MBB);
1081 loop2MBB->addSuccessor(sinkMBB);
1082 sinkMBB->addSuccessor(exitMBB);
1084 // FIXME: computation of newval2 can be moved to loop2MBB.
1086 // addiu masklsb2,$0,-4 # 0xfffffffc
1087 // and alignedaddr,ptr,masklsb2
1088 // andi ptrlsb2,ptr,3
1089 // sll shiftamt,ptrlsb2,3
1090 // ori maskupper,$0,255 # 0xff
1091 // sll mask,maskupper,shiftamt
1092 // nor mask2,$0,mask
1093 // andi maskedcmpval,cmpval,255
1094 // sll shiftedcmpval,maskedcmpval,shiftamt
1095 // andi maskednewval,newval,255
1096 // sll shiftednewval,maskednewval,shiftamt
1097 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1098 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1099 .addReg(Mips::ZERO).addImm(-4);
1100 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1101 .addReg(Ptr).addReg(MaskLSB2);
1102 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1103 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1104 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1105 .addReg(Mips::ZERO).addImm(MaskImm);
1106 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1107 .addReg(ShiftAmt).addReg(MaskUpper);
1108 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1109 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1110 .addReg(CmpVal).addImm(MaskImm);
1111 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1112 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1113 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1114 .addReg(NewVal).addImm(MaskImm);
1115 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1116 .addReg(ShiftAmt).addReg(MaskedNewVal);
1119 // ll oldval,0(alginedaddr)
1120 // and maskedoldval0,oldval,mask
1121 // bne maskedoldval0,shiftedcmpval,sinkMBB
1123 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1124 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1125 .addReg(OldVal).addReg(Mask);
1126 BuildMI(BB, dl, TII->get(Mips::BNE))
1127 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1130 // and maskedoldval1,oldval,mask2
1131 // or storeval,maskedoldval1,shiftednewval
1132 // sc success,storeval,0(alignedaddr)
1133 // beq success,$0,loop1MBB
1135 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1136 .addReg(OldVal).addReg(Mask2);
1137 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1138 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1139 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1140 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1141 BuildMI(BB, dl, TII->get(Mips::BEQ))
1142 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1145 // srl srlres,maskedoldval0,shiftamt
1146 // sll sllres,srlres,24
1147 // sra dest,sllres,24
1149 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1151 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1152 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1153 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1154 .addReg(SrlRes).addImm(ShiftImm);
1155 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1156 .addReg(SllRes).addImm(ShiftImm);
1158 MI->eraseFromParent(); // The instruction is gone now.
1163 //===----------------------------------------------------------------------===//
1164 // Misc Lower Operation implementation
1165 //===----------------------------------------------------------------------===//
1166 SDValue MipsTargetLowering::
1167 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1169 MachineFunction &MF = DAG.getMachineFunction();
1170 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1172 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1173 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1174 "Cannot lower if the alignment of the allocated space is larger than \
1175 that of the stack.");
1177 SDValue Chain = Op.getOperand(0);
1178 SDValue Size = Op.getOperand(1);
1179 DebugLoc dl = Op.getDebugLoc();
1181 // Get a reference from Mips stack pointer
1182 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
1184 // Subtract the dynamic size from the actual stack size to
1185 // obtain the new stack size.
1186 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
1188 // The Sub result contains the new stack start address, so it
1189 // must be placed in the stack pointer register.
1190 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
1193 // This node always has two return values: a new stack pointer
1194 // value and a chain
1195 SDVTList VTLs = DAG.getVTList(MVT::i32, MVT::Other);
1196 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1197 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1199 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1202 SDValue MipsTargetLowering::
1203 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1205 // The first operand is the chain, the second is the condition, the third is
1206 // the block to branch to if the condition is true.
1207 SDValue Chain = Op.getOperand(0);
1208 SDValue Dest = Op.getOperand(2);
1209 DebugLoc dl = Op.getDebugLoc();
1211 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1213 // Return if flag is not set by a floating point comparison.
1214 if (CondRes.getOpcode() != MipsISD::FPCmp)
1217 SDValue CCNode = CondRes.getOperand(2);
1219 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1220 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1222 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1226 SDValue MipsTargetLowering::
1227 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1229 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1231 // Return if flag is not set by a floating point comparison.
1232 if (Cond.getOpcode() != MipsISD::FPCmp)
1235 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1239 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1240 SelectionDAG &DAG) const {
1241 // FIXME there isn't actually debug info here
1242 DebugLoc dl = Op.getDebugLoc();
1243 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1245 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1246 SDVTList VTs = DAG.getVTList(MVT::i32);
1248 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1250 // %gp_rel relocation
1251 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1252 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1254 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1255 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1256 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1258 // %hi/%lo relocation
1259 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1261 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1263 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1264 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1265 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1268 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1270 GA = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, GA);
1271 SDValue ResNode = DAG.getLoad(MVT::i32, dl,
1272 DAG.getEntryNode(), GA, MachinePointerInfo(),
1274 // On functions and global targets not internal linked only
1275 // a load from got/GP is necessary for PIC to work.
1276 if (!GV->hasInternalLinkage() &&
1277 (!GV->hasLocalLinkage() || isa<Function>(GV)))
1279 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1281 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1282 return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
1285 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1286 SelectionDAG &DAG) const {
1287 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1288 // FIXME there isn't actually debug info here
1289 DebugLoc dl = Op.getDebugLoc();
1291 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1292 // %hi/%lo relocation
1293 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1295 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1297 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1298 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1299 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1302 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1304 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1305 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1307 SDValue Load = DAG.getLoad(MVT::i32, dl,
1308 DAG.getEntryNode(), BAGOTOffset,
1309 MachinePointerInfo(), false, false, 0);
1310 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1311 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1314 SDValue MipsTargetLowering::
1315 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1317 // If the relocation model is PIC, use the General Dynamic TLS Model,
1318 // otherwise use the Initial Exec or Local Exec TLS Model.
1319 // TODO: implement Local Dynamic TLS model
1321 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1322 DebugLoc dl = GA->getDebugLoc();
1323 const GlobalValue *GV = GA->getGlobal();
1324 EVT PtrVT = getPointerTy();
1326 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1327 // General Dynamic TLS Model
1328 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1329 0, MipsII::MO_TLSGD);
1330 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1331 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1332 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1336 Entry.Node = Argument;
1337 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1338 Args.push_back(Entry);
1339 std::pair<SDValue, SDValue> CallResult =
1340 LowerCallTo(DAG.getEntryNode(),
1341 (Type *) Type::getInt32Ty(*DAG.getContext()),
1342 false, false, false, false, 0, CallingConv::C, false, true,
1343 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1346 return CallResult.first;
1350 if (GV->isDeclaration()) {
1351 // Initial Exec TLS Model
1352 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1353 MipsII::MO_GOTTPREL);
1354 Offset = DAG.getLoad(MVT::i32, dl,
1355 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1358 // Local Exec TLS Model
1359 SDVTList VTs = DAG.getVTList(MVT::i32);
1360 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1361 MipsII::MO_TPREL_HI);
1362 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1363 MipsII::MO_TPREL_LO);
1364 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1365 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1366 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1369 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1370 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1373 SDValue MipsTargetLowering::
1374 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1378 // FIXME there isn't actually debug info here
1379 DebugLoc dl = Op.getDebugLoc();
1380 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1381 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1383 EVT PtrVT = Op.getValueType();
1384 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1386 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1389 SDValue Ops[] = { JTI };
1390 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1391 } else {// Emit Load from Global Pointer
1392 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1393 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1394 MachinePointerInfo(),
1398 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1400 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1401 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1406 SDValue MipsTargetLowering::
1407 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1410 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1411 const Constant *C = N->getConstVal();
1412 // FIXME there isn't actually debug info here
1413 DebugLoc dl = Op.getDebugLoc();
1415 // gp_rel relocation
1416 // FIXME: we should reference the constant pool using small data sections,
1417 // but the asm printer currently doesn't support this feature without
1418 // hacking it. This feature should come soon so we can uncomment the
1420 //if (IsInSmallSection(C->getType())) {
1421 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1422 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1423 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1425 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1426 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1427 N->getOffset(), MipsII::MO_ABS_HI);
1428 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1429 N->getOffset(), MipsII::MO_ABS_LO);
1430 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1431 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1432 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1434 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1435 N->getOffset(), MipsII::MO_GOT);
1436 CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1437 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1438 CP, MachinePointerInfo::getConstantPool(),
1440 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1441 N->getOffset(), MipsII::MO_ABS_LO);
1442 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1443 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1449 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1450 MachineFunction &MF = DAG.getMachineFunction();
1451 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1453 DebugLoc dl = Op.getDebugLoc();
1454 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1457 // vastart just stores the address of the VarArgsFrameIndex slot into the
1458 // memory location argument.
1459 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1460 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1461 MachinePointerInfo(SV),
1465 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1466 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1467 DebugLoc dl = Op.getDebugLoc();
1468 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1469 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1470 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1471 DAG.getConstant(0x7fffffff, MVT::i32));
1472 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1473 DAG.getConstant(0x80000000, MVT::i32));
1474 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1475 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1478 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1480 // Use ext/ins instructions if target architecture is Mips32r2.
1481 // Eliminate redundant mfc1 and mtc1 instructions.
1482 unsigned LoIdx = 0, HiIdx = 1;
1485 std::swap(LoIdx, HiIdx);
1487 DebugLoc dl = Op.getDebugLoc();
1488 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1490 DAG.getConstant(LoIdx, MVT::i32));
1491 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1492 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1493 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1494 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1495 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1496 DAG.getConstant(0x7fffffff, MVT::i32));
1497 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1498 DAG.getConstant(0x80000000, MVT::i32));
1499 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1502 std::swap(Word0, Word1);
1504 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1507 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1509 EVT Ty = Op.getValueType();
1511 assert(Ty == MVT::f32 || Ty == MVT::f64);
1514 return LowerFCOPYSIGN32(Op, DAG);
1516 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1519 SDValue MipsTargetLowering::
1520 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1522 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1523 "Frame address can only be determined for current frame.");
1525 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1526 MFI->setFrameAddressIsTaken(true);
1527 EVT VT = Op.getValueType();
1528 DebugLoc dl = Op.getDebugLoc();
1529 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::FP, VT);
1533 // TODO: set SType according to the desired memory barrier behavior.
1534 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1535 SelectionDAG& DAG) const {
1537 DebugLoc dl = Op.getDebugLoc();
1538 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1539 DAG.getConstant(SType, MVT::i32));
1542 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1543 SelectionDAG& DAG) const {
1544 // FIXME: Need pseudo-fence for 'singlethread' fences
1545 // FIXME: Set SType for weaker fences where supported/appropriate.
1547 DebugLoc dl = Op.getDebugLoc();
1548 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1549 DAG.getConstant(SType, MVT::i32));
1552 //===----------------------------------------------------------------------===//
1553 // Calling Convention Implementation
1554 //===----------------------------------------------------------------------===//
1556 #include "MipsGenCallingConv.inc"
1558 //===----------------------------------------------------------------------===//
1559 // TODO: Implement a generic logic using tblgen that can support this.
1560 // Mips O32 ABI rules:
1562 // i32 - Passed in A0, A1, A2, A3 and stack
1563 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1564 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1565 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1566 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1567 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1570 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1571 //===----------------------------------------------------------------------===//
1573 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1574 MVT LocVT, CCValAssign::LocInfo LocInfo,
1575 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1577 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1579 static const unsigned IntRegs[] = {
1580 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1582 static const unsigned F32Regs[] = {
1583 Mips::F12, Mips::F14
1585 static const unsigned F64Regs[] = {
1590 if (ArgFlags.isByVal()) {
1591 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1592 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1593 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1594 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1595 r < std::min(IntRegsSize, NextReg); ++r)
1596 State.AllocateReg(IntRegs[r]);
1600 // Promote i8 and i16
1601 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1603 if (ArgFlags.isSExt())
1604 LocInfo = CCValAssign::SExt;
1605 else if (ArgFlags.isZExt())
1606 LocInfo = CCValAssign::ZExt;
1608 LocInfo = CCValAssign::AExt;
1613 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1614 // is true: function is vararg, argument is 3rd or higher, there is previous
1615 // argument which is not f32 or f64.
1616 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1617 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1618 unsigned OrigAlign = ArgFlags.getOrigAlign();
1619 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1621 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1622 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1623 // If this is the first part of an i64 arg,
1624 // the allocated register must be either A0 or A2.
1625 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1626 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1628 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1629 // Allocate int register and shadow next int register. If first
1630 // available register is Mips::A1 or Mips::A3, shadow it too.
1631 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1632 if (Reg == Mips::A1 || Reg == Mips::A3)
1633 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1634 State.AllocateReg(IntRegs, IntRegsSize);
1636 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1637 // we are guaranteed to find an available float register
1638 if (ValVT == MVT::f32) {
1639 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1640 // Shadow int register
1641 State.AllocateReg(IntRegs, IntRegsSize);
1643 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1644 // Shadow int registers
1645 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1646 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1647 State.AllocateReg(IntRegs, IntRegsSize);
1648 State.AllocateReg(IntRegs, IntRegsSize);
1651 llvm_unreachable("Cannot handle this ValVT.");
1653 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1654 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1657 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1659 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1661 return false; // CC must always match
1664 //===----------------------------------------------------------------------===//
1665 // Call Calling Convention Implementation
1666 //===----------------------------------------------------------------------===//
1668 static const unsigned O32IntRegsSize = 4;
1670 static const unsigned O32IntRegs[] = {
1671 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1674 // Write ByVal Arg to arg registers and stack.
1676 WriteByValArg(SDValue& Chain, DebugLoc dl,
1677 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1678 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1679 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1680 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1682 unsigned FirstWord = VA.getLocMemOffset() / 4;
1683 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
1684 unsigned LastWord = FirstWord + NumWords;
1687 // copy the first 4 words of byval arg to registers A0 - A3
1688 for (CurWord = FirstWord; CurWord < std::min(LastWord, O32IntRegsSize);
1690 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1691 DAG.getConstant((CurWord - FirstWord) * 4,
1693 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1694 MachinePointerInfo(),
1696 MemOpChains.push_back(LoadVal.getValue(1));
1697 unsigned DstReg = O32IntRegs[CurWord];
1698 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1701 // copy remaining part of byval arg to stack.
1702 if (CurWord < LastWord) {
1703 unsigned SizeInBytes = (LastWord - CurWord) * 4;
1704 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1705 DAG.getConstant((CurWord - FirstWord) * 4,
1707 LastFI = MFI->CreateFixedObject(SizeInBytes, CurWord * 4, true);
1708 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1709 Chain = DAG.getMemcpy(Chain, dl, Dst, Src,
1710 DAG.getConstant(SizeInBytes, MVT::i32),
1712 /*isVolatile=*/false, /*AlwaysInline=*/false,
1713 MachinePointerInfo(0), MachinePointerInfo(0));
1714 MemOpChains.push_back(Chain);
1718 /// LowerCall - functions arguments are copied from virtual regs to
1719 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1720 /// TODO: isTailCall.
1722 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1723 CallingConv::ID CallConv, bool isVarArg,
1725 const SmallVectorImpl<ISD::OutputArg> &Outs,
1726 const SmallVectorImpl<SDValue> &OutVals,
1727 const SmallVectorImpl<ISD::InputArg> &Ins,
1728 DebugLoc dl, SelectionDAG &DAG,
1729 SmallVectorImpl<SDValue> &InVals) const {
1730 // MIPs target does not yet support tail call optimization.
1733 MachineFunction &MF = DAG.getMachineFunction();
1734 MachineFrameInfo *MFI = MF.getFrameInfo();
1735 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1736 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1737 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1739 // Analyze operands of the call, assigning locations to each operand.
1740 SmallVector<CCValAssign, 16> ArgLocs;
1741 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1742 getTargetMachine(), ArgLocs, *DAG.getContext());
1744 if (Subtarget->isABI_O32())
1745 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1747 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1749 // Get a count of how many bytes are to be pushed on the stack.
1750 unsigned NextStackOffset = CCInfo.getNextStackOffset();
1752 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NextStackOffset,
1755 // If this is the first call, create a stack frame object that points to
1756 // a location to which .cprestore saves $gp.
1757 if (IsPIC && !MipsFI->getGPFI())
1758 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1760 // Get the frame index of the stack frame object that points to the location
1761 // of dynamically allocated area on the stack.
1762 int DynAllocFI = MipsFI->getDynAllocFI();
1764 // Update size of the maximum argument space.
1765 // For O32, a minimum of four words (16 bytes) of argument space is
1767 if (Subtarget->isABI_O32())
1768 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1770 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1772 if (MaxCallFrameSize < NextStackOffset) {
1773 MipsFI->setMaxCallFrameSize(NextStackOffset);
1775 // Set the offsets relative to $sp of the $gp restore slot and dynamically
1776 // allocated stack space. These offsets must be aligned to a boundary
1777 // determined by the stack alignment of the ABI.
1778 unsigned StackAlignment = TFL->getStackAlignment();
1779 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
1780 StackAlignment * StackAlignment;
1783 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
1785 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
1788 // With EABI is it possible to have 16 args on registers.
1789 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1790 SmallVector<SDValue, 8> MemOpChains;
1792 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
1794 // Walk the register/memloc assignments, inserting copies/loads.
1795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796 SDValue Arg = OutVals[i];
1797 CCValAssign &VA = ArgLocs[i];
1799 // Promote the value if needed.
1800 switch (VA.getLocInfo()) {
1801 default: llvm_unreachable("Unknown loc info!");
1802 case CCValAssign::Full:
1803 if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1804 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1805 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1806 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1807 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1808 Arg, DAG.getConstant(0, MVT::i32));
1809 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1810 Arg, DAG.getConstant(1, MVT::i32));
1811 if (!Subtarget->isLittle())
1813 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1814 RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1819 case CCValAssign::SExt:
1820 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1822 case CCValAssign::ZExt:
1823 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1825 case CCValAssign::AExt:
1826 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1830 // Arguments that can be passed on register must be kept at
1831 // RegsToPass vector
1832 if (VA.isRegLoc()) {
1833 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1837 // Register can't get to this point...
1838 assert(VA.isMemLoc());
1841 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1842 if (Flags.isByVal()) {
1843 assert(Subtarget->isABI_O32() &&
1844 "No support for ByVal args by ABIs other than O32 yet.");
1845 assert(Flags.getByValSize() &&
1846 "ByVal args of size 0 should have been ignored by front-end.");
1847 WriteByValArg(Chain, dl, RegsToPass, MemOpChains, LastFI, MFI, DAG, Arg,
1848 VA, Flags, getPointerTy());
1852 // Create the frame index object for this incoming parameter
1853 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1854 VA.getLocMemOffset(), true);
1855 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
1857 // emit ISD::STORE whichs stores the
1858 // parameter value to a stack Location
1859 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1860 MachinePointerInfo(),
1864 // Extend range of indices of frame objects for outgoing arguments that were
1865 // created during this function call. Skip this step if no such objects were
1868 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
1870 // Transform all store nodes into one single node because all store
1871 // nodes are independent of each other.
1872 if (!MemOpChains.empty())
1873 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1874 &MemOpChains[0], MemOpChains.size());
1876 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1877 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1878 // node so that legalize doesn't hack it.
1879 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1880 bool LoadSymAddr = false;
1883 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1884 if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
1885 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1886 getPointerTy(), 0,MipsII:: MO_GOT);
1887 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
1888 0, MipsII::MO_ABS_LO);
1890 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1891 getPointerTy(), 0, OpFlag);
1896 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1897 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1898 getPointerTy(), OpFlag);
1904 // Create nodes that load address of callee and copy it to T9
1907 // Load callee address
1908 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
1909 SDValue LoadValue = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), Callee,
1910 MachinePointerInfo::getGOT(),
1913 // Use GOT+LO if callee has internal linkage.
1914 if (CalleeLo.getNode()) {
1915 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
1916 Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
1922 Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
1923 InFlag = Chain.getValue(1);
1924 Callee = DAG.getRegister(Mips::T9, MVT::i32);
1927 // Build a sequence of copy-to-reg nodes chained together with token
1928 // chain and flag operands which copy the outgoing args into registers.
1929 // The InFlag in necessary since all emitted instructions must be
1931 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1932 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1933 RegsToPass[i].second, InFlag);
1934 InFlag = Chain.getValue(1);
1937 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1938 // = Chain, Callee, Reg#1, Reg#2, ...
1940 // Returns a chain & a flag for retval copy to use.
1941 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1942 SmallVector<SDValue, 8> Ops;
1943 Ops.push_back(Chain);
1944 Ops.push_back(Callee);
1946 // Add argument registers to the end of the list so that they are
1947 // known live into the call.
1948 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1949 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1950 RegsToPass[i].second.getValueType()));
1952 if (InFlag.getNode())
1953 Ops.push_back(InFlag);
1955 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1956 InFlag = Chain.getValue(1);
1958 // Create the CALLSEQ_END node.
1959 Chain = DAG.getCALLSEQ_END(Chain,
1960 DAG.getIntPtrConstant(NextStackOffset, true),
1961 DAG.getIntPtrConstant(0, true), InFlag);
1962 InFlag = Chain.getValue(1);
1964 // Handle result values, copying them out of physregs into vregs that we
1966 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1967 Ins, dl, DAG, InVals);
1970 /// LowerCallResult - Lower the result values of a call into the
1971 /// appropriate copies out of appropriate physical registers.
1973 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1974 CallingConv::ID CallConv, bool isVarArg,
1975 const SmallVectorImpl<ISD::InputArg> &Ins,
1976 DebugLoc dl, SelectionDAG &DAG,
1977 SmallVectorImpl<SDValue> &InVals) const {
1978 // Assign locations to each value returned by this call.
1979 SmallVector<CCValAssign, 16> RVLocs;
1980 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1981 getTargetMachine(), RVLocs, *DAG.getContext());
1983 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1985 // Copy all of the result registers out of their specified physreg.
1986 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1987 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1988 RVLocs[i].getValVT(), InFlag).getValue(1);
1989 InFlag = Chain.getValue(2);
1990 InVals.push_back(Chain.getValue(0));
1996 //===----------------------------------------------------------------------===//
1997 // Formal Arguments Calling Convention Implementation
1998 //===----------------------------------------------------------------------===//
1999 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2000 std::vector<SDValue>& OutChains,
2001 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2002 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2003 unsigned LocMem = VA.getLocMemOffset();
2004 unsigned FirstWord = LocMem / 4;
2006 // copy register A0 - A3 to frame object
2007 for (unsigned i = 0; i < NumWords; ++i) {
2008 unsigned CurWord = FirstWord + i;
2009 if (CurWord >= O32IntRegsSize)
2012 unsigned SrcReg = O32IntRegs[CurWord];
2013 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2014 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2015 DAG.getConstant(i * 4, MVT::i32));
2016 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2017 StorePtr, MachinePointerInfo(), false,
2019 OutChains.push_back(Store);
2023 /// LowerFormalArguments - transform physical registers into virtual registers
2024 /// and generate load operations for arguments places on the stack.
2026 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2027 CallingConv::ID CallConv,
2029 const SmallVectorImpl<ISD::InputArg>
2031 DebugLoc dl, SelectionDAG &DAG,
2032 SmallVectorImpl<SDValue> &InVals)
2034 MachineFunction &MF = DAG.getMachineFunction();
2035 MachineFrameInfo *MFI = MF.getFrameInfo();
2036 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2038 MipsFI->setVarArgsFrameIndex(0);
2040 // Used with vargs to acumulate store chains.
2041 std::vector<SDValue> OutChains;
2043 // Assign locations to all of the incoming arguments.
2044 SmallVector<CCValAssign, 16> ArgLocs;
2045 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2046 getTargetMachine(), ArgLocs, *DAG.getContext());
2048 if (Subtarget->isABI_O32())
2049 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2051 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2053 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2055 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2056 CCValAssign &VA = ArgLocs[i];
2058 // Arguments stored on registers
2059 if (VA.isRegLoc()) {
2060 EVT RegVT = VA.getLocVT();
2061 unsigned ArgReg = VA.getLocReg();
2062 TargetRegisterClass *RC = 0;
2064 if (RegVT == MVT::i32)
2065 RC = Mips::CPURegsRegisterClass;
2066 else if (RegVT == MVT::f32)
2067 RC = Mips::FGR32RegisterClass;
2068 else if (RegVT == MVT::f64) {
2069 if (!Subtarget->isSingleFloat())
2070 RC = Mips::AFGR64RegisterClass;
2072 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2074 // Transform the arguments stored on
2075 // physical registers into virtual ones
2076 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2077 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2079 // If this is an 8 or 16-bit value, it has been passed promoted
2080 // to 32 bits. Insert an assert[sz]ext to capture this, then
2081 // truncate to the right size.
2082 if (VA.getLocInfo() != CCValAssign::Full) {
2083 unsigned Opcode = 0;
2084 if (VA.getLocInfo() == CCValAssign::SExt)
2085 Opcode = ISD::AssertSext;
2086 else if (VA.getLocInfo() == CCValAssign::ZExt)
2087 Opcode = ISD::AssertZext;
2089 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2090 DAG.getValueType(VA.getValVT()));
2091 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2094 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
2095 if (Subtarget->isABI_O32()) {
2096 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
2097 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
2098 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
2099 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2100 VA.getLocReg()+1, RC);
2101 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2102 if (!Subtarget->isLittle())
2103 std::swap(ArgValue, ArgValue2);
2104 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2105 ArgValue, ArgValue2);
2109 InVals.push_back(ArgValue);
2110 } else { // VA.isRegLoc()
2113 assert(VA.isMemLoc());
2115 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2117 if (Flags.isByVal()) {
2118 assert(Subtarget->isABI_O32() &&
2119 "No support for ByVal args by ABIs other than O32 yet.");
2120 assert(Flags.getByValSize() &&
2121 "ByVal args of size 0 should have been ignored by front-end.");
2122 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2123 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2125 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2126 InVals.push_back(FIN);
2127 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2132 // The stack pointer offset is relative to the caller stack frame.
2133 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2134 VA.getLocMemOffset(), true);
2136 // Create load nodes to retrieve arguments from the stack
2137 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2138 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2139 MachinePointerInfo::getFixedStack(LastFI),
2144 // The mips ABIs for returning structs by value requires that we copy
2145 // the sret argument into $v0 for the return. Save the argument into
2146 // a virtual register so that we can access it from the return points.
2147 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2148 unsigned Reg = MipsFI->getSRetReturnReg();
2150 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2151 MipsFI->setSRetReturnReg(Reg);
2153 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2154 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2157 if (isVarArg && Subtarget->isABI_O32()) {
2158 // Record the frame index of the first variable argument
2159 // which is a value necessary to VASTART.
2160 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2161 assert(NextStackOffset % 4 == 0 &&
2162 "NextStackOffset must be aligned to 4-byte boundaries.");
2163 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2164 MipsFI->setVarArgsFrameIndex(LastFI);
2166 // If NextStackOffset is smaller than o32's 16-byte reserved argument area,
2167 // copy the integer registers that have not been used for argument passing
2168 // to the caller's stack frame.
2169 for (; NextStackOffset < 16; NextStackOffset += 4) {
2170 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
2171 unsigned Idx = NextStackOffset / 4;
2172 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
2173 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
2174 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2175 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2176 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2177 MachinePointerInfo(),
2182 MipsFI->setLastInArgFI(LastFI);
2184 // All stores are grouped in one node to allow the matching between
2185 // the size of Ins and InVals. This only happens when on varg functions
2186 if (!OutChains.empty()) {
2187 OutChains.push_back(Chain);
2188 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2189 &OutChains[0], OutChains.size());
2195 //===----------------------------------------------------------------------===//
2196 // Return Value Calling Convention Implementation
2197 //===----------------------------------------------------------------------===//
2200 MipsTargetLowering::LowerReturn(SDValue Chain,
2201 CallingConv::ID CallConv, bool isVarArg,
2202 const SmallVectorImpl<ISD::OutputArg> &Outs,
2203 const SmallVectorImpl<SDValue> &OutVals,
2204 DebugLoc dl, SelectionDAG &DAG) const {
2206 // CCValAssign - represent the assignment of
2207 // the return value to a location
2208 SmallVector<CCValAssign, 16> RVLocs;
2210 // CCState - Info about the registers and stack slot.
2211 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2212 getTargetMachine(), RVLocs, *DAG.getContext());
2214 // Analize return values.
2215 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2217 // If this is the first return lowered for this function, add
2218 // the regs to the liveout set for the function.
2219 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2220 for (unsigned i = 0; i != RVLocs.size(); ++i)
2221 if (RVLocs[i].isRegLoc())
2222 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2227 // Copy the result values into the output registers.
2228 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2229 CCValAssign &VA = RVLocs[i];
2230 assert(VA.isRegLoc() && "Can only return in registers!");
2232 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2235 // guarantee that all emitted copies are
2236 // stuck together, avoiding something bad
2237 Flag = Chain.getValue(1);
2240 // The mips ABIs for returning structs by value requires that we copy
2241 // the sret argument into $v0 for the return. We saved the argument into
2242 // a virtual register in the entry block, so now we copy the value out
2244 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2245 MachineFunction &MF = DAG.getMachineFunction();
2246 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2247 unsigned Reg = MipsFI->getSRetReturnReg();
2250 llvm_unreachable("sret virtual register not created in the entry block");
2251 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2253 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2254 Flag = Chain.getValue(1);
2257 // Return on Mips is always a "jr $ra"
2259 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2260 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2262 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2263 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2266 //===----------------------------------------------------------------------===//
2267 // Mips Inline Assembly Support
2268 //===----------------------------------------------------------------------===//
2270 /// getConstraintType - Given a constraint letter, return the type of
2271 /// constraint it is for this target.
2272 MipsTargetLowering::ConstraintType MipsTargetLowering::
2273 getConstraintType(const std::string &Constraint) const
2275 // Mips specific constrainy
2276 // GCC config/mips/constraints.md
2278 // 'd' : An address register. Equivalent to r
2279 // unless generating MIPS16 code.
2280 // 'y' : Equivalent to r; retained for
2281 // backwards compatibility.
2282 // 'f' : Floating Point registers.
2283 if (Constraint.size() == 1) {
2284 switch (Constraint[0]) {
2289 return C_RegisterClass;
2293 return TargetLowering::getConstraintType(Constraint);
2296 /// Examine constraint type and operand type and determine a weight value.
2297 /// This object must already have been set up with the operand type
2298 /// and the current alternative constraint selected.
2299 TargetLowering::ConstraintWeight
2300 MipsTargetLowering::getSingleConstraintMatchWeight(
2301 AsmOperandInfo &info, const char *constraint) const {
2302 ConstraintWeight weight = CW_Invalid;
2303 Value *CallOperandVal = info.CallOperandVal;
2304 // If we don't have a value, we can't do a match,
2305 // but allow it at the lowest weight.
2306 if (CallOperandVal == NULL)
2308 Type *type = CallOperandVal->getType();
2309 // Look at the constraint type.
2310 switch (*constraint) {
2312 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2316 if (type->isIntegerTy())
2317 weight = CW_Register;
2320 if (type->isFloatTy())
2321 weight = CW_Register;
2327 /// Given a register class constraint, like 'r', if this corresponds directly
2328 /// to an LLVM register class, return a register of 0 and the register class
2330 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2331 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2333 if (Constraint.size() == 1) {
2334 switch (Constraint[0]) {
2335 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2336 case 'y': // Same as 'r'. Exists for compatibility.
2338 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2341 return std::make_pair(0U, Mips::FGR32RegisterClass);
2343 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2344 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2348 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2352 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2353 // The Mips target isn't yet aware of offsets.
2357 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2358 if (VT != MVT::f32 && VT != MVT::f64)
2360 if (Imm.isNegZero())
2362 return Imm.isZero();