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 "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
37 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
39 case MipsISD::JmpLink : return "MipsISD::JmpLink";
40 case MipsISD::Hi : return "MipsISD::Hi";
41 case MipsISD::Lo : return "MipsISD::Lo";
42 case MipsISD::GPRel : return "MipsISD::GPRel";
43 case MipsISD::Ret : return "MipsISD::Ret";
44 case MipsISD::SelectCC : return "MipsISD::SelectCC";
45 case MipsISD::FPSelectCC : return "MipsISD::FPSelectCC";
46 case MipsISD::FPBrcond : return "MipsISD::FPBrcond";
47 case MipsISD::FPCmp : return "MipsISD::FPCmp";
48 case MipsISD::FPRound : return "MipsISD::FPRound";
49 case MipsISD::MAdd : return "MipsISD::MAdd";
50 case MipsISD::MAddu : return "MipsISD::MAddu";
51 case MipsISD::MSub : return "MipsISD::MSub";
52 case MipsISD::MSubu : return "MipsISD::MSubu";
53 default : return NULL;
58 MipsTargetLowering(MipsTargetMachine &TM)
59 : TargetLowering(TM, new MipsTargetObjectFile()) {
60 Subtarget = &TM.getSubtarget<MipsSubtarget>();
62 // Mips does not have i1 type, so use i32 for
63 // setcc operations results (slt, sgt, ...).
64 setBooleanContents(ZeroOrOneBooleanContent);
66 // Set up the register classes
67 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
68 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
70 // When dealing with single precision only, use libcalls
71 if (!Subtarget->isSingleFloat())
72 if (!Subtarget->isFP64bit())
73 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
75 // Load extented operations for i1 types must be promoted
76 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
77 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
78 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
80 // MIPS doesn't have extending float->double load/store
81 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
82 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84 // Used by legalize types to correctly generate the setcc result.
85 // Without this, every float setcc comes with a AND/OR with the result,
86 // we don't want this, since the fpcmp result goes to a flag register,
87 // which is used implicitly by brcond and select operations.
88 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
90 // Mips Custom Operations
91 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
92 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
93 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
94 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
95 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
96 setOperationAction(ISD::SELECT, MVT::f32, Custom);
97 setOperationAction(ISD::SELECT, MVT::f64, Custom);
98 setOperationAction(ISD::SELECT, MVT::i32, Custom);
99 setOperationAction(ISD::SETCC, MVT::f32, Custom);
100 setOperationAction(ISD::SETCC, MVT::f64, Custom);
101 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
102 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
103 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
104 setOperationAction(ISD::VASTART, MVT::Other, Custom);
107 // We custom lower AND/OR to handle the case where the DAG contain 'ands/ors'
108 // with operands comming from setcc fp comparions. This is necessary since
109 // the result from these setcc are in a flag registers (FCR31).
110 setOperationAction(ISD::AND, MVT::i32, Custom);
111 setOperationAction(ISD::OR, MVT::i32, Custom);
113 // Operations not directly supported by Mips.
114 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
115 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
116 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
117 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
118 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
120 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
121 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
122 setOperationAction(ISD::ROTL, MVT::i32, Expand);
124 if (!Subtarget->isMips32r2())
125 setOperationAction(ISD::ROTR, MVT::i32, Expand);
127 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
128 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
129 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
130 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
131 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
132 setOperationAction(ISD::FSIN, MVT::f32, Expand);
133 setOperationAction(ISD::FSIN, MVT::f64, Expand);
134 setOperationAction(ISD::FCOS, MVT::f32, Expand);
135 setOperationAction(ISD::FCOS, MVT::f64, Expand);
136 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
137 setOperationAction(ISD::FPOW, MVT::f32, Expand);
138 setOperationAction(ISD::FLOG, MVT::f32, Expand);
139 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
140 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
141 setOperationAction(ISD::FEXP, MVT::f32, Expand);
143 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
145 // Use the default for now
146 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
147 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
148 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
150 if (Subtarget->isSingleFloat())
151 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
153 if (!Subtarget->hasSEInReg()) {
154 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
155 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
158 if (!Subtarget->hasBitCount())
159 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
161 if (!Subtarget->hasSwap())
162 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
164 setTargetDAGCombine(ISD::ADDE);
165 setTargetDAGCombine(ISD::SUBE);
167 setStackPointerRegisterToSaveRestore(Mips::SP);
168 computeRegisterProperties();
171 MVT::SimpleValueType MipsTargetLowering::getSetCCResultType(EVT VT) const {
175 /// getFunctionAlignment - Return the Log2 alignment of this function.
176 unsigned MipsTargetLowering::getFunctionAlignment(const Function *) const {
181 // Transforms a subgraph in CurDAG if the following pattern is found:
182 // (addc multLo, Lo0), (adde multHi, Hi0),
184 // multHi/Lo: product of multiplication
185 // Lo0: initial value of Lo register
186 // Hi0: initial value of Hi register
187 // Return true if mattern matching was successful.
188 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
189 // ADDENode's second operand must be a flag output of an ADDC node in order
190 // for the matching to be successful.
191 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
193 if (ADDCNode->getOpcode() != ISD::ADDC)
196 SDValue MultHi = ADDENode->getOperand(0);
197 SDValue MultLo = ADDCNode->getOperand(0);
198 SDNode* MultNode = MultHi.getNode();
199 unsigned MultOpc = MultHi.getOpcode();
201 // MultHi and MultLo must be generated by the same node,
202 if (MultLo.getNode() != MultNode)
205 // and it must be a multiplication.
206 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
209 // MultLo amd MultHi must be the first and second output of MultNode
211 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
214 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
215 // of the values of MultNode, in which case MultNode will be removed in later
217 // If there exist users other than ADDENode or ADDCNode, this function returns
218 // here, which will result in MultNode being mapped to a single MULT
219 // instruction node rather than a pair of MULT and MADD instructions being
221 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
224 SDValue Chain = CurDAG->getEntryNode();
225 DebugLoc dl = ADDENode->getDebugLoc();
227 // create MipsMAdd(u) node
228 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
230 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
232 MultNode->getOperand(0),// Factor 0
233 MultNode->getOperand(1),// Factor 1
234 ADDCNode->getOperand(1),// Lo0
235 ADDENode->getOperand(1));// Hi0
237 // create CopyFromReg nodes
238 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
240 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
242 CopyFromLo.getValue(2));
244 // replace uses of adde and addc here
245 if (!SDValue(ADDCNode, 0).use_empty())
246 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
248 if (!SDValue(ADDENode, 0).use_empty())
249 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
255 // Transforms a subgraph in CurDAG if the following pattern is found:
256 // (addc Lo0, multLo), (sube Hi0, multHi),
258 // multHi/Lo: product of multiplication
259 // Lo0: initial value of Lo register
260 // Hi0: initial value of Hi register
261 // Return true if mattern matching was successful.
262 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
263 // SUBENode's second operand must be a flag output of an SUBC node in order
264 // for the matching to be successful.
265 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
267 if (SUBCNode->getOpcode() != ISD::SUBC)
270 SDValue MultHi = SUBENode->getOperand(1);
271 SDValue MultLo = SUBCNode->getOperand(1);
272 SDNode* MultNode = MultHi.getNode();
273 unsigned MultOpc = MultHi.getOpcode();
275 // MultHi and MultLo must be generated by the same node,
276 if (MultLo.getNode() != MultNode)
279 // and it must be a multiplication.
280 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
283 // MultLo amd MultHi must be the first and second output of MultNode
285 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
288 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
289 // of the values of MultNode, in which case MultNode will be removed in later
291 // If there exist users other than SUBENode or SUBCNode, this function returns
292 // here, which will result in MultNode being mapped to a single MULT
293 // instruction node rather than a pair of MULT and MSUB instructions being
295 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
298 SDValue Chain = CurDAG->getEntryNode();
299 DebugLoc dl = SUBENode->getDebugLoc();
301 // create MipsSub(u) node
302 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
304 SDValue MSub = CurDAG->getNode(MultOpc, dl,
306 MultNode->getOperand(0),// Factor 0
307 MultNode->getOperand(1),// Factor 1
308 SUBCNode->getOperand(0),// Lo0
309 SUBENode->getOperand(0));// Hi0
311 // create CopyFromReg nodes
312 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
314 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
316 CopyFromLo.getValue(2));
318 // replace uses of sube and subc here
319 if (!SDValue(SUBCNode, 0).use_empty())
320 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
322 if (!SDValue(SUBENode, 0).use_empty())
323 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
328 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
329 TargetLowering::DAGCombinerInfo &DCI,
330 const MipsSubtarget* Subtarget) {
331 if (DCI.isBeforeLegalize())
334 if (Subtarget->isMips32() && SelectMadd(N, &DAG))
335 return SDValue(N, 0);
340 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
341 TargetLowering::DAGCombinerInfo &DCI,
342 const MipsSubtarget* Subtarget) {
343 if (DCI.isBeforeLegalize())
346 if (Subtarget->isMips32() && SelectMsub(N, &DAG))
347 return SDValue(N, 0);
352 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
354 SelectionDAG &DAG = DCI.DAG;
355 unsigned opc = N->getOpcode();
360 return PerformADDECombine(N, DAG, DCI, Subtarget);
362 return PerformSUBECombine(N, DAG, DCI, Subtarget);
368 SDValue MipsTargetLowering::
369 LowerOperation(SDValue Op, SelectionDAG &DAG) const
371 switch (Op.getOpcode())
373 case ISD::AND: return LowerANDOR(Op, DAG);
374 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
375 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
376 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
377 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
378 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
379 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
380 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
381 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
382 case ISD::OR: return LowerANDOR(Op, DAG);
383 case ISD::SELECT: return LowerSELECT(Op, DAG);
384 case ISD::SETCC: return LowerSETCC(Op, DAG);
385 case ISD::VASTART: return LowerVASTART(Op, DAG);
390 //===----------------------------------------------------------------------===//
391 // Lower helper functions
392 //===----------------------------------------------------------------------===//
394 // AddLiveIn - This helper function adds the specified physical register to the
395 // MachineFunction as a live in value. It also creates a corresponding
396 // virtual register for it.
398 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
400 assert(RC->contains(PReg) && "Not the correct regclass!");
401 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
402 MF.getRegInfo().addLiveIn(PReg, VReg);
406 // Get fp branch code (not opcode) from condition code.
407 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
408 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
409 return Mips::BRANCH_T;
411 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
412 return Mips::BRANCH_F;
414 return Mips::BRANCH_INVALID;
417 static unsigned FPBranchCodeToOpc(Mips::FPBranchCode BC) {
420 llvm_unreachable("Unknown branch code");
421 case Mips::BRANCH_T : return Mips::BC1T;
422 case Mips::BRANCH_F : return Mips::BC1F;
423 case Mips::BRANCH_TL : return Mips::BC1TL;
424 case Mips::BRANCH_FL : return Mips::BC1FL;
428 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
430 default: llvm_unreachable("Unknown fp condition code!");
432 case ISD::SETOEQ: return Mips::FCOND_EQ;
433 case ISD::SETUNE: return Mips::FCOND_OGL;
435 case ISD::SETOLT: return Mips::FCOND_OLT;
437 case ISD::SETOGT: return Mips::FCOND_OGT;
439 case ISD::SETOLE: return Mips::FCOND_OLE;
441 case ISD::SETOGE: return Mips::FCOND_OGE;
442 case ISD::SETULT: return Mips::FCOND_ULT;
443 case ISD::SETULE: return Mips::FCOND_ULE;
444 case ISD::SETUGT: return Mips::FCOND_UGT;
445 case ISD::SETUGE: return Mips::FCOND_UGE;
446 case ISD::SETUO: return Mips::FCOND_UN;
447 case ISD::SETO: return Mips::FCOND_OR;
449 case ISD::SETONE: return Mips::FCOND_NEQ;
450 case ISD::SETUEQ: return Mips::FCOND_UEQ;
455 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
456 MachineBasicBlock *BB) const {
457 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
458 bool isFPCmp = false;
459 DebugLoc dl = MI->getDebugLoc();
461 switch (MI->getOpcode()) {
462 default: assert(false && "Unexpected instr type to insert");
463 case Mips::Select_FCC:
464 case Mips::Select_FCC_S32:
465 case Mips::Select_FCC_D32:
466 isFPCmp = true; // FALL THROUGH
467 case Mips::Select_CC:
468 case Mips::Select_CC_S32:
469 case Mips::Select_CC_D32: {
470 // To "insert" a SELECT_CC instruction, we actually have to insert the
471 // diamond control-flow pattern. The incoming instruction knows the
472 // destination vreg to set, the condition code register to branch on, the
473 // true/false values to select between, and a branch opcode to use.
474 const BasicBlock *LLVM_BB = BB->getBasicBlock();
475 MachineFunction::iterator It = BB;
482 // bNE r1, r0, copy1MBB
483 // fallthrough --> copy0MBB
484 MachineBasicBlock *thisMBB = BB;
485 MachineFunction *F = BB->getParent();
486 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
487 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
488 F->insert(It, copy0MBB);
489 F->insert(It, sinkMBB);
491 // Transfer the remainder of BB and its successor edges to sinkMBB.
492 sinkMBB->splice(sinkMBB->begin(), BB,
493 llvm::next(MachineBasicBlock::iterator(MI)),
495 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
497 // Next, add the true and fallthrough blocks as its successors.
498 BB->addSuccessor(copy0MBB);
499 BB->addSuccessor(sinkMBB);
501 // Emit the right instruction according to the type of the operands compared
503 // Find the condiction code present in the setcc operation.
504 Mips::CondCode CC = (Mips::CondCode)MI->getOperand(4).getImm();
505 // Get the branch opcode from the branch code.
506 unsigned Opc = FPBranchCodeToOpc(GetFPBranchCodeFromCond(CC));
507 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
509 BuildMI(BB, dl, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
510 .addReg(Mips::ZERO).addMBB(sinkMBB);
514 // # fallthrough to sinkMBB
517 // Update machine-CFG edges
518 BB->addSuccessor(sinkMBB);
521 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
524 BuildMI(*BB, BB->begin(), dl,
525 TII->get(Mips::PHI), MI->getOperand(0).getReg())
526 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
527 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
529 MI->eraseFromParent(); // The pseudo instruction is gone now.
535 //===----------------------------------------------------------------------===//
536 // Misc Lower Operation implementation
537 //===----------------------------------------------------------------------===//
539 SDValue MipsTargetLowering::
540 LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) const
542 if (!Subtarget->isMips1())
545 MachineFunction &MF = DAG.getMachineFunction();
546 unsigned CCReg = AddLiveIn(MF, Mips::FCR31, Mips::CCRRegisterClass);
548 SDValue Chain = DAG.getEntryNode();
549 DebugLoc dl = Op.getDebugLoc();
550 SDValue Src = Op.getOperand(0);
552 // Set the condition register
553 SDValue CondReg = DAG.getCopyFromReg(Chain, dl, CCReg, MVT::i32);
554 CondReg = DAG.getCopyToReg(Chain, dl, Mips::AT, CondReg);
555 CondReg = DAG.getCopyFromReg(CondReg, dl, Mips::AT, MVT::i32);
557 SDValue Cst = DAG.getConstant(3, MVT::i32);
558 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, CondReg, Cst);
559 Cst = DAG.getConstant(2, MVT::i32);
560 SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i32, Or, Cst);
562 SDValue InFlag(0, 0);
563 CondReg = DAG.getCopyToReg(Chain, dl, Mips::FCR31, Xor, InFlag);
565 // Emit the round instruction and bit convert to integer
566 SDValue Trunc = DAG.getNode(MipsISD::FPRound, dl, MVT::f32,
567 Src, CondReg.getValue(1));
568 SDValue BitCvt = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Trunc);
572 SDValue MipsTargetLowering::
573 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
575 SDValue Chain = Op.getOperand(0);
576 SDValue Size = Op.getOperand(1);
577 DebugLoc dl = Op.getDebugLoc();
579 // Get a reference from Mips stack pointer
580 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
582 // Subtract the dynamic size from the actual stack size to
583 // obtain the new stack size.
584 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
586 // The Sub result contains the new stack start address, so it
587 // must be placed in the stack pointer register.
588 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub);
590 // This node always has two return values: a new stack pointer
592 SDValue Ops[2] = { Sub, Chain };
593 return DAG.getMergeValues(Ops, 2, dl);
596 SDValue MipsTargetLowering::
597 LowerANDOR(SDValue Op, SelectionDAG &DAG) const
599 SDValue LHS = Op.getOperand(0);
600 SDValue RHS = Op.getOperand(1);
601 DebugLoc dl = Op.getDebugLoc();
603 if (LHS.getOpcode() != MipsISD::FPCmp || RHS.getOpcode() != MipsISD::FPCmp)
606 SDValue True = DAG.getConstant(1, MVT::i32);
607 SDValue False = DAG.getConstant(0, MVT::i32);
609 SDValue LSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
610 LHS, True, False, LHS.getOperand(2));
611 SDValue RSEL = DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
612 RHS, True, False, RHS.getOperand(2));
614 return DAG.getNode(Op.getOpcode(), dl, MVT::i32, LSEL, RSEL);
617 SDValue MipsTargetLowering::
618 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
620 // The first operand is the chain, the second is the condition, the third is
621 // the block to branch to if the condition is true.
622 SDValue Chain = Op.getOperand(0);
623 SDValue Dest = Op.getOperand(2);
624 DebugLoc dl = Op.getDebugLoc();
626 if (Op.getOperand(1).getOpcode() != MipsISD::FPCmp)
629 SDValue CondRes = Op.getOperand(1);
630 SDValue CCNode = CondRes.getOperand(2);
632 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
633 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
635 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
639 SDValue MipsTargetLowering::
640 LowerSETCC(SDValue Op, SelectionDAG &DAG) const
642 // The operands to this are the left and right operands to compare (ops #0,
643 // and #1) and the condition code to compare them with (op #2) as a
645 SDValue LHS = Op.getOperand(0);
646 SDValue RHS = Op.getOperand(1);
647 DebugLoc dl = Op.getDebugLoc();
649 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
651 return DAG.getNode(MipsISD::FPCmp, dl, Op.getValueType(), LHS, RHS,
652 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
655 SDValue MipsTargetLowering::
656 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
658 SDValue Cond = Op.getOperand(0);
659 SDValue True = Op.getOperand(1);
660 SDValue False = Op.getOperand(2);
661 DebugLoc dl = Op.getDebugLoc();
663 // if the incomming condition comes from a integer compare, the select
664 // operation must be SelectCC or a conditional move if the subtarget
666 if (Cond.getOpcode() != MipsISD::FPCmp) {
667 if (Subtarget->hasCondMov() && !True.getValueType().isFloatingPoint())
669 return DAG.getNode(MipsISD::SelectCC, dl, True.getValueType(),
673 // if the incomming condition comes from fpcmp, the select
674 // operation must use FPSelectCC.
675 SDValue CCNode = Cond.getOperand(2);
676 return DAG.getNode(MipsISD::FPSelectCC, dl, True.getValueType(),
677 Cond, True, False, CCNode);
680 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
681 SelectionDAG &DAG) const {
682 // FIXME there isn't actually debug info here
683 DebugLoc dl = Op.getDebugLoc();
684 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
686 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
687 SDVTList VTs = DAG.getVTList(MVT::i32);
689 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
691 // %gp_rel relocation
692 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
693 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
695 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
696 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
697 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
699 // %hi/%lo relocation
700 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
701 MipsII::MO_ABS_HILO);
702 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GA, 1);
703 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
704 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
707 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
709 SDValue ResNode = DAG.getLoad(MVT::i32, dl,
710 DAG.getEntryNode(), GA, MachinePointerInfo(),
712 // On functions and global targets not internal linked only
713 // a load from got/GP is necessary for PIC to work.
714 if (!GV->hasLocalLinkage() || isa<Function>(GV))
716 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GA);
717 return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
720 llvm_unreachable("Dont know how to handle GlobalAddress");
724 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
725 SelectionDAG &DAG) const {
726 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
727 assert(false && "implement LowerBlockAddress for -static");
728 return SDValue(0, 0);
731 // FIXME there isn't actually debug info here
732 DebugLoc dl = Op.getDebugLoc();
733 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
734 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
736 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
737 MipsII::MO_ABS_HILO);
738 SDValue Load = DAG.getLoad(MVT::i32, dl,
739 DAG.getEntryNode(), BAGOTOffset,
740 MachinePointerInfo(), false, false, 0);
741 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
742 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
746 SDValue MipsTargetLowering::
747 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
749 llvm_unreachable("TLS not implemented for MIPS.");
750 return SDValue(); // Not reached
753 SDValue MipsTargetLowering::
754 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
758 // FIXME there isn't actually debug info here
759 DebugLoc dl = Op.getDebugLoc();
760 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
761 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HILO;
763 EVT PtrVT = Op.getValueType();
764 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
766 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
769 SDValue Ops[] = { JTI };
770 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
771 } else // Emit Load from Global Pointer
772 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
773 MachinePointerInfo(),
776 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTI);
777 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
782 SDValue MipsTargetLowering::
783 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
786 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
787 const Constant *C = N->getConstVal();
788 // FIXME there isn't actually debug info here
789 DebugLoc dl = Op.getDebugLoc();
792 // FIXME: we should reference the constant pool using small data sections,
793 // but the asm printer currently doens't support this feature without
794 // hacking it. This feature should come soon so we can uncomment the
796 //if (IsInSmallSection(C->getType())) {
797 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
798 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
799 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
801 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
802 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
803 N->getOffset(), MipsII::MO_ABS_HILO);
804 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CP);
805 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
806 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
808 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
809 N->getOffset(), MipsII::MO_GOT);
810 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
811 CP, MachinePointerInfo::getConstantPool(),
813 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CP);
814 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
820 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
821 MachineFunction &MF = DAG.getMachineFunction();
822 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
824 DebugLoc dl = Op.getDebugLoc();
825 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
828 // vastart just stores the address of the VarArgsFrameIndex slot into the
829 // memory location argument.
830 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
831 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
832 MachinePointerInfo(SV),
836 //===----------------------------------------------------------------------===//
837 // Calling Convention Implementation
838 //===----------------------------------------------------------------------===//
840 #include "MipsGenCallingConv.inc"
842 //===----------------------------------------------------------------------===//
843 // TODO: Implement a generic logic using tblgen that can support this.
844 // Mips O32 ABI rules:
846 // i32 - Passed in A0, A1, A2, A3 and stack
847 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
848 // an argument. Otherwise, passed in A1, A2, A3 and stack.
849 // f64 - Only passed in two aliased f32 registers if no int reg has been used
850 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
851 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
853 //===----------------------------------------------------------------------===//
855 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
856 MVT LocVT, CCValAssign::LocInfo LocInfo,
857 ISD::ArgFlagsTy ArgFlags, CCState &State) {
859 static const unsigned IntRegsSize=4, FloatRegsSize=2;
861 static const unsigned IntRegs[] = {
862 Mips::A0, Mips::A1, Mips::A2, Mips::A3
864 static const unsigned F32Regs[] = {
867 static const unsigned F64Regs[] = {
872 static bool IntRegUsed = false;
874 // This must be the first arg of the call if no regs have been allocated.
875 // Initialize IntRegUsed in that case.
876 if (IntRegs[State.getFirstUnallocated(IntRegs, IntRegsSize)] == Mips::A0 &&
877 F32Regs[State.getFirstUnallocated(F32Regs, FloatRegsSize)] == Mips::F12 &&
878 F64Regs[State.getFirstUnallocated(F64Regs, FloatRegsSize)] == Mips::D6)
881 // Promote i8 and i16
882 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
884 if (ArgFlags.isSExt())
885 LocInfo = CCValAssign::SExt;
886 else if (ArgFlags.isZExt())
887 LocInfo = CCValAssign::ZExt;
889 LocInfo = CCValAssign::AExt;
892 if (ValVT == MVT::i32) {
893 Reg = State.AllocateReg(IntRegs, IntRegsSize);
895 } else if (ValVT == MVT::f32) {
896 // An int reg has to be marked allocated regardless of whether or not
897 // IntRegUsed is true.
898 Reg = State.AllocateReg(IntRegs, IntRegsSize);
901 if (Reg) // Int reg is available
904 unsigned FReg = State.AllocateReg(F32Regs, FloatRegsSize);
905 if (FReg) // F32 reg is available
907 else if (Reg) // No F32 regs are available, but an int reg is available.
910 } else if (ValVT == MVT::f64) {
911 // Int regs have to be marked allocated regardless of whether or not
912 // IntRegUsed is true.
913 Reg = State.AllocateReg(IntRegs, IntRegsSize);
915 Reg = State.AllocateReg(IntRegs, IntRegsSize);
916 else if (Reg == Mips::A3)
918 State.AllocateReg(IntRegs, IntRegsSize);
920 // At this point, Reg is A0, A2 or 0, and all the unavailable integer regs
921 // are marked as allocated.
923 if (Reg)// if int reg is available
926 unsigned FReg = State.AllocateReg(F64Regs, FloatRegsSize);
927 if (FReg) // F64 reg is available.
929 else if (Reg) // No F64 regs are available, but an int reg is available.
933 assert(false && "cannot handle this ValVT");
936 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
937 unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
938 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
940 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
942 return false; // CC must always match
945 static bool CC_MipsO32_VarArgs(unsigned ValNo, MVT ValVT,
946 MVT LocVT, CCValAssign::LocInfo LocInfo,
947 ISD::ArgFlagsTy ArgFlags, CCState &State) {
949 static const unsigned IntRegsSize=4;
951 static const unsigned IntRegs[] = {
952 Mips::A0, Mips::A1, Mips::A2, Mips::A3
955 // Promote i8 and i16
956 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
958 if (ArgFlags.isSExt())
959 LocInfo = CCValAssign::SExt;
960 else if (ArgFlags.isZExt())
961 LocInfo = CCValAssign::ZExt;
963 LocInfo = CCValAssign::AExt;
966 if (ValVT == MVT::i32 || ValVT == MVT::f32) {
967 if (unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize)) {
968 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
971 unsigned Off = State.AllocateStack(4, 4);
972 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
976 unsigned UnallocIntReg = State.getFirstUnallocated(IntRegs, IntRegsSize);
977 if (ValVT == MVT::f64) {
978 if (IntRegs[UnallocIntReg] == (unsigned (Mips::A1))) {
979 // A1 can't be used anymore, because 64 bit arguments
980 // must be aligned when copied back to the caller stack
981 State.AllocateReg(IntRegs, IntRegsSize);
985 if (IntRegs[UnallocIntReg] == (unsigned (Mips::A0)) ||
986 IntRegs[UnallocIntReg] == (unsigned (Mips::A2))) {
987 unsigned Reg = State.AllocateReg(IntRegs, IntRegsSize);
988 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
989 // Shadow the next register so it can be used
990 // later to get the other 32bit part.
991 State.AllocateReg(IntRegs, IntRegsSize);
995 // Register is shadowed to preserve alignment, and the
996 // argument goes to a stack location.
997 if (UnallocIntReg != IntRegsSize)
998 State.AllocateReg(IntRegs, IntRegsSize);
1000 unsigned Off = State.AllocateStack(8, 8);
1001 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Off, LocVT, LocInfo));
1005 return true; // CC didn't match
1008 //===----------------------------------------------------------------------===//
1009 // Call Calling Convention Implementation
1010 //===----------------------------------------------------------------------===//
1012 /// LowerCall - functions arguments are copied from virtual regs to
1013 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1014 /// TODO: isTailCall.
1016 MipsTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1017 CallingConv::ID CallConv, bool isVarArg,
1019 const SmallVectorImpl<ISD::OutputArg> &Outs,
1020 const SmallVectorImpl<SDValue> &OutVals,
1021 const SmallVectorImpl<ISD::InputArg> &Ins,
1022 DebugLoc dl, SelectionDAG &DAG,
1023 SmallVectorImpl<SDValue> &InVals) const {
1024 // MIPs target does not yet support tail call optimization.
1027 MachineFunction &MF = DAG.getMachineFunction();
1028 MachineFrameInfo *MFI = MF.getFrameInfo();
1029 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1031 // Analyze operands of the call, assigning locations to each operand.
1032 SmallVector<CCValAssign, 16> ArgLocs;
1033 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1036 // To meet O32 ABI, Mips must always allocate 16 bytes on
1037 // the stack (even if less than 4 are used as arguments)
1038 if (Subtarget->isABI_O32()) {
1039 int VTsize = MVT(MVT::i32).getSizeInBits()/8;
1040 MFI->CreateFixedObject(VTsize, (VTsize*3), true);
1041 CCInfo.AnalyzeCallOperands(Outs,
1042 isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1044 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1046 // Get a count of how many bytes are to be pushed on the stack.
1047 unsigned NumBytes = CCInfo.getNextStackOffset();
1048 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1050 // With EABI is it possible to have 16 args on registers.
1051 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1052 SmallVector<SDValue, 8> MemOpChains;
1054 // First/LastArgStackLoc contains the first/last
1055 // "at stack" argument location.
1056 int LastArgStackLoc = 0;
1057 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1059 // Walk the register/memloc assignments, inserting copies/loads.
1060 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1061 SDValue Arg = OutVals[i];
1062 CCValAssign &VA = ArgLocs[i];
1064 // Promote the value if needed.
1065 switch (VA.getLocInfo()) {
1066 default: llvm_unreachable("Unknown loc info!");
1067 case CCValAssign::Full:
1068 if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1069 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1070 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1071 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1072 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1073 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1074 DAG.getConstant(0, getPointerTy()));
1075 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Arg,
1076 DAG.getConstant(1, getPointerTy()));
1077 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1078 RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1083 case CCValAssign::SExt:
1084 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1086 case CCValAssign::ZExt:
1087 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1089 case CCValAssign::AExt:
1090 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1094 // Arguments that can be passed on register must be kept at
1095 // RegsToPass vector
1096 if (VA.isRegLoc()) {
1097 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1101 // Register can't get to this point...
1102 assert(VA.isMemLoc());
1104 // Create the frame index object for this incoming parameter
1105 // This guarantees that when allocating Local Area the firsts
1106 // 16 bytes which are alwayes reserved won't be overwritten
1107 // if O32 ABI is used. For EABI the first address is zero.
1108 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
1109 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1110 LastArgStackLoc, true);
1112 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
1114 // emit ISD::STORE whichs stores the
1115 // parameter value to a stack Location
1116 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
1117 MachinePointerInfo(),
1121 // Transform all store nodes into one single node because all store
1122 // nodes are independent of each other.
1123 if (!MemOpChains.empty())
1124 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1125 &MemOpChains[0], MemOpChains.size());
1127 // Build a sequence of copy-to-reg nodes chained together with token
1128 // chain and flag operands which copy the outgoing args into registers.
1129 // The InFlag in necessary since all emited instructions must be
1132 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1133 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1134 RegsToPass[i].second, InFlag);
1135 InFlag = Chain.getValue(1);
1138 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1139 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1140 // node so that legalize doesn't hack it.
1141 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
1142 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1143 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
1144 getPointerTy(), 0, OpFlag);
1145 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1146 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
1147 getPointerTy(), OpFlag);
1149 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
1150 // = Chain, Callee, Reg#1, Reg#2, ...
1152 // Returns a chain & a flag for retval copy to use.
1153 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1154 SmallVector<SDValue, 8> Ops;
1155 Ops.push_back(Chain);
1156 Ops.push_back(Callee);
1158 // Add argument registers to the end of the list so that they are
1159 // known live into the call.
1160 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1161 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1162 RegsToPass[i].second.getValueType()));
1164 if (InFlag.getNode())
1165 Ops.push_back(InFlag);
1167 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
1168 InFlag = Chain.getValue(1);
1170 // Create a stack location to hold GP when PIC is used. This stack
1171 // location is used on function prologue to save GP and also after all
1172 // emited CALL's to restore GP.
1174 // Function can have an arbitrary number of calls, so
1175 // hold the LastArgStackLoc with the biggest offset.
1177 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1178 if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
1179 LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
1180 // Create the frame index only once. SPOffset here can be anything
1181 // (this will be fixed on processFunctionBeforeFrameFinalized)
1182 if (MipsFI->getGPStackOffset() == -1) {
1183 FI = MFI->CreateFixedObject(4, 0, true);
1184 MipsFI->setGPFI(FI);
1186 MipsFI->setGPStackOffset(LastArgStackLoc);
1190 FI = MipsFI->getGPFI();
1191 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1192 SDValue GPLoad = DAG.getLoad(MVT::i32, dl, Chain, FIN,
1193 MachinePointerInfo::getFixedStack(FI),
1195 Chain = GPLoad.getValue(1);
1196 Chain = DAG.getCopyToReg(Chain, dl, DAG.getRegister(Mips::GP, MVT::i32),
1197 GPLoad, SDValue(0,0));
1198 InFlag = Chain.getValue(1);
1201 // Create the CALLSEQ_END node.
1202 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1203 DAG.getIntPtrConstant(0, true), InFlag);
1204 InFlag = Chain.getValue(1);
1206 // Handle result values, copying them out of physregs into vregs that we
1208 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1209 Ins, dl, DAG, InVals);
1212 /// LowerCallResult - Lower the result values of a call into the
1213 /// appropriate copies out of appropriate physical registers.
1215 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1216 CallingConv::ID CallConv, bool isVarArg,
1217 const SmallVectorImpl<ISD::InputArg> &Ins,
1218 DebugLoc dl, SelectionDAG &DAG,
1219 SmallVectorImpl<SDValue> &InVals) const {
1221 // Assign locations to each value returned by this call.
1222 SmallVector<CCValAssign, 16> RVLocs;
1223 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1224 RVLocs, *DAG.getContext());
1226 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
1228 // Copy all of the result registers out of their specified physreg.
1229 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1230 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1231 RVLocs[i].getValVT(), InFlag).getValue(1);
1232 InFlag = Chain.getValue(2);
1233 InVals.push_back(Chain.getValue(0));
1239 //===----------------------------------------------------------------------===//
1240 // Formal Arguments Calling Convention Implementation
1241 //===----------------------------------------------------------------------===//
1243 /// LowerFormalArguments - transform physical registers into virtual registers
1244 /// and generate load operations for arguments places on the stack.
1246 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
1247 CallingConv::ID CallConv, bool isVarArg,
1248 const SmallVectorImpl<ISD::InputArg>
1250 DebugLoc dl, SelectionDAG &DAG,
1251 SmallVectorImpl<SDValue> &InVals)
1254 MachineFunction &MF = DAG.getMachineFunction();
1255 MachineFrameInfo *MFI = MF.getFrameInfo();
1256 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1258 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
1259 MipsFI->setVarArgsFrameIndex(0);
1261 // Used with vargs to acumulate store chains.
1262 std::vector<SDValue> OutChains;
1264 // Keep track of the last register used for arguments
1265 unsigned ArgRegEnd = 0;
1267 // Assign locations to all of the incoming arguments.
1268 SmallVector<CCValAssign, 16> ArgLocs;
1269 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1270 ArgLocs, *DAG.getContext());
1272 if (Subtarget->isABI_O32())
1273 CCInfo.AnalyzeFormalArguments(Ins,
1274 isVarArg ? CC_MipsO32_VarArgs : CC_MipsO32);
1276 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
1280 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
1282 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1283 CCValAssign &VA = ArgLocs[i];
1285 // Arguments stored on registers
1286 if (VA.isRegLoc()) {
1287 EVT RegVT = VA.getLocVT();
1288 ArgRegEnd = VA.getLocReg();
1289 TargetRegisterClass *RC = 0;
1291 if (RegVT == MVT::i32)
1292 RC = Mips::CPURegsRegisterClass;
1293 else if (RegVT == MVT::f32)
1294 RC = Mips::FGR32RegisterClass;
1295 else if (RegVT == MVT::f64) {
1296 if (!Subtarget->isSingleFloat())
1297 RC = Mips::AFGR64RegisterClass;
1299 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
1301 // Transform the arguments stored on
1302 // physical registers into virtual ones
1303 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1304 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1306 // If this is an 8 or 16-bit value, it has been passed promoted
1307 // to 32 bits. Insert an assert[sz]ext to capture this, then
1308 // truncate to the right size.
1309 if (VA.getLocInfo() != CCValAssign::Full) {
1310 unsigned Opcode = 0;
1311 if (VA.getLocInfo() == CCValAssign::SExt)
1312 Opcode = ISD::AssertSext;
1313 else if (VA.getLocInfo() == CCValAssign::ZExt)
1314 Opcode = ISD::AssertZext;
1316 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
1317 DAG.getValueType(VA.getValVT()));
1318 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1321 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
1322 if (Subtarget->isABI_O32()) {
1323 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
1324 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
1325 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
1326 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
1327 VA.getLocReg()+1, RC);
1328 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
1329 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, ArgValue2, ArgValue);
1330 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Pair);
1334 InVals.push_back(ArgValue);
1335 } else { // VA.isRegLoc()
1338 assert(VA.isMemLoc());
1340 // The last argument is not a register anymore
1343 // The stack pointer offset is relative to the caller stack frame.
1344 // Since the real stack size is unknown here, a negative SPOffset
1345 // is used so there's a way to adjust these offsets when the stack
1346 // size get known (on EliminateFrameIndex). A dummy SPOffset is
1347 // used instead of a direct negative address (which is recorded to
1348 // be used on emitPrologue) to avoid mis-calc of the first stack
1349 // offset on PEI::calculateFrameObjectOffsets.
1350 // Arguments are always 32-bit.
1351 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1352 int FI = MFI->CreateFixedObject(ArgSize, 0, true);
1353 MipsFI->recordLoadArgsFI(FI, -(ArgSize+
1354 (FirstStackArgLoc + VA.getLocMemOffset())));
1356 // Create load nodes to retrieve arguments from the stack
1357 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1358 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1359 MachinePointerInfo::getFixedStack(FI),
1364 // The mips ABIs for returning structs by value requires that we copy
1365 // the sret argument into $v0 for the return. Save the argument into
1366 // a virtual register so that we can access it from the return points.
1367 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1368 unsigned Reg = MipsFI->getSRetReturnReg();
1370 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
1371 MipsFI->setSRetReturnReg(Reg);
1373 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1374 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1377 // To meet ABI, when VARARGS are passed on registers, the registers
1378 // must have their values written to the caller stack frame. If the last
1379 // argument was placed in the stack, there's no need to save any register.
1380 if ((isVarArg) && (Subtarget->isABI_O32() && ArgRegEnd)) {
1381 if (StackPtr.getNode() == 0)
1382 StackPtr = DAG.getRegister(StackReg, getPointerTy());
1384 // The last register argument that must be saved is Mips::A3
1385 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
1386 unsigned StackLoc = ArgLocs.size()-1;
1388 for (++ArgRegEnd; ArgRegEnd <= Mips::A3; ++ArgRegEnd, ++StackLoc) {
1389 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegEnd, RC);
1390 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
1392 int FI = MFI->CreateFixedObject(4, 0, true);
1393 MipsFI->recordStoreVarArgsFI(FI, -(4+(StackLoc*4)));
1394 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
1395 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
1396 MachinePointerInfo(),
1399 // Record the frame index of the first variable argument
1400 // which is a value necessary to VASTART.
1401 if (!MipsFI->getVarArgsFrameIndex())
1402 MipsFI->setVarArgsFrameIndex(FI);
1406 // All stores are grouped in one node to allow the matching between
1407 // the size of Ins and InVals. This only happens when on varg functions
1408 if (!OutChains.empty()) {
1409 OutChains.push_back(Chain);
1410 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1411 &OutChains[0], OutChains.size());
1417 //===----------------------------------------------------------------------===//
1418 // Return Value Calling Convention Implementation
1419 //===----------------------------------------------------------------------===//
1422 MipsTargetLowering::LowerReturn(SDValue Chain,
1423 CallingConv::ID CallConv, bool isVarArg,
1424 const SmallVectorImpl<ISD::OutputArg> &Outs,
1425 const SmallVectorImpl<SDValue> &OutVals,
1426 DebugLoc dl, SelectionDAG &DAG) const {
1428 // CCValAssign - represent the assignment of
1429 // the return value to a location
1430 SmallVector<CCValAssign, 16> RVLocs;
1432 // CCState - Info about the registers and stack slot.
1433 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1434 RVLocs, *DAG.getContext());
1436 // Analize return values.
1437 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
1439 // If this is the first return lowered for this function, add
1440 // the regs to the liveout set for the function.
1441 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1442 for (unsigned i = 0; i != RVLocs.size(); ++i)
1443 if (RVLocs[i].isRegLoc())
1444 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1449 // Copy the result values into the output registers.
1450 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1451 CCValAssign &VA = RVLocs[i];
1452 assert(VA.isRegLoc() && "Can only return in registers!");
1454 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1457 // guarantee that all emitted copies are
1458 // stuck together, avoiding something bad
1459 Flag = Chain.getValue(1);
1462 // The mips ABIs for returning structs by value requires that we copy
1463 // the sret argument into $v0 for the return. We saved the argument into
1464 // a virtual register in the entry block, so now we copy the value out
1466 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1467 MachineFunction &MF = DAG.getMachineFunction();
1468 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1469 unsigned Reg = MipsFI->getSRetReturnReg();
1472 llvm_unreachable("sret virtual register not created in the entry block");
1473 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1475 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
1476 Flag = Chain.getValue(1);
1479 // Return on Mips is always a "jr $ra"
1481 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1482 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
1484 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
1485 Chain, DAG.getRegister(Mips::RA, MVT::i32));
1488 //===----------------------------------------------------------------------===//
1489 // Mips Inline Assembly Support
1490 //===----------------------------------------------------------------------===//
1492 /// getConstraintType - Given a constraint letter, return the type of
1493 /// constraint it is for this target.
1494 MipsTargetLowering::ConstraintType MipsTargetLowering::
1495 getConstraintType(const std::string &Constraint) const
1497 // Mips specific constrainy
1498 // GCC config/mips/constraints.md
1500 // 'd' : An address register. Equivalent to r
1501 // unless generating MIPS16 code.
1502 // 'y' : Equivalent to r; retained for
1503 // backwards compatibility.
1504 // 'f' : Floating Point registers.
1505 if (Constraint.size() == 1) {
1506 switch (Constraint[0]) {
1511 return C_RegisterClass;
1515 return TargetLowering::getConstraintType(Constraint);
1518 /// Examine constraint type and operand type and determine a weight value.
1519 /// This object must already have been set up with the operand type
1520 /// and the current alternative constraint selected.
1521 TargetLowering::ConstraintWeight
1522 MipsTargetLowering::getSingleConstraintMatchWeight(
1523 AsmOperandInfo &info, const char *constraint) const {
1524 ConstraintWeight weight = CW_Invalid;
1525 Value *CallOperandVal = info.CallOperandVal;
1526 // If we don't have a value, we can't do a match,
1527 // but allow it at the lowest weight.
1528 if (CallOperandVal == NULL)
1530 const Type *type = CallOperandVal->getType();
1531 // Look at the constraint type.
1532 switch (*constraint) {
1534 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1538 if (type->isIntegerTy())
1539 weight = CW_Register;
1542 if (type->isFloatTy())
1543 weight = CW_Register;
1549 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
1550 /// return a list of registers that can be used to satisfy the constraint.
1551 /// This should only be used for C_RegisterClass constraints.
1552 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
1553 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
1555 if (Constraint.size() == 1) {
1556 switch (Constraint[0]) {
1558 return std::make_pair(0U, Mips::CPURegsRegisterClass);
1561 return std::make_pair(0U, Mips::FGR32RegisterClass);
1563 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1564 return std::make_pair(0U, Mips::AFGR64RegisterClass);
1567 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1570 /// Given a register class constraint, like 'r', if this corresponds directly
1571 /// to an LLVM register class, return a register of 0 and the register class
1573 std::vector<unsigned> MipsTargetLowering::
1574 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1577 if (Constraint.size() != 1)
1578 return std::vector<unsigned>();
1580 switch (Constraint[0]) {
1583 // GCC Mips Constraint Letters
1586 return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1587 Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1588 Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1592 if (VT == MVT::f32) {
1593 if (Subtarget->isSingleFloat())
1594 return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1595 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1596 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1597 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1598 Mips::F30, Mips::F31, 0);
1600 return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1601 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1602 Mips::F28, Mips::F30, 0);
1606 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1607 return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1608 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1609 Mips::D14, Mips::D15, 0);
1611 return std::vector<unsigned>();
1615 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1616 // The Mips target isn't yet aware of offsets.
1620 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1621 if (VT != MVT::f32 && VT != MVT::f64)
1623 if (Imm.isNegZero())
1625 return Imm.isZero();