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"
17 #include "MipsISelLowering.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsTargetMachine.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"
39 const char *MipsTargetLowering::
40 getTargetNodeName(unsigned Opcode) const
44 case MipsISD::JmpLink : return "MipsISD::JmpLink";
45 case MipsISD::Hi : return "MipsISD::Hi";
46 case MipsISD::Lo : return "MipsISD::Lo";
47 case MipsISD::GPRel : return "MipsISD::GPRel";
48 case MipsISD::Ret : return "MipsISD::Ret";
49 case MipsISD::SelectCC : return "MipsISD::SelectCC";
50 case MipsISD::FPBrcond : return "MipsISD::FPBrcond";
51 case MipsISD::FPCmp : return "MipsISD::FPCmp";
52 default : return NULL;
57 MipsTargetLowering(MipsTargetMachine &TM): TargetLowering(TM)
59 Subtarget = &TM.getSubtarget<MipsSubtarget>();
61 // Mips does not have i1 type, so use i32 for
62 // setcc operations results (slt, sgt, ...).
63 setSetCCResultContents(ZeroOrOneSetCCResult);
65 // JumpTable targets must use GOT when using PIC_
66 setUsesGlobalOffsetTable(true);
68 // Set up the register classes
69 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
71 // When dealing with single precision only, use libcalls
72 if (!Subtarget->isSingleFloat()) {
73 addRegisterClass(MVT::f32, Mips::AFGR32RegisterClass);
74 if (!Subtarget->isFP64bit())
75 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
77 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
79 // Load extented operations for i1 types must be promoted
80 setLoadXAction(ISD::EXTLOAD, MVT::i1, Promote);
81 setLoadXAction(ISD::ZEXTLOAD, MVT::i1, Promote);
82 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
84 // Mips Custom Operations
85 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
86 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
87 setOperationAction(ISD::RET, MVT::Other, Custom);
88 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
89 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
90 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
92 setOperationAction(ISD::SETCC, MVT::f32, Custom);
93 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
95 // Operations not directly supported by Mips.
96 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
97 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
98 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
99 setOperationAction(ISD::SELECT, MVT::i32, Expand);
100 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
101 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
102 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
104 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
105 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
106 setOperationAction(ISD::ROTL, MVT::i32, Expand);
107 setOperationAction(ISD::ROTR, MVT::i32, Expand);
108 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
109 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
113 // We don't have line number support yet.
114 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
115 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
116 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
117 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
119 // Use the default for now
120 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
121 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
122 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
124 if (Subtarget->isSingleFloat())
125 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
127 if (!Subtarget->hasSEInReg()) {
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
132 setStackPointerRegisterToSaveRestore(Mips::SP);
133 computeRegisterProperties();
137 MVT MipsTargetLowering::getSetCCResultType(const SDValue &) const {
142 SDValue MipsTargetLowering::
143 LowerOperation(SDValue Op, SelectionDAG &DAG)
145 switch (Op.getOpcode())
147 case ISD::CALL: return LowerCALL(Op, DAG);
148 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
149 case ISD::RET: return LowerRET(Op, DAG);
150 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
151 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
152 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
153 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
154 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
155 case ISD::SETCC: return LowerSETCC(Op, DAG);
156 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
162 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
163 MachineBasicBlock *BB)
165 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
166 switch (MI->getOpcode()) {
167 default: assert(false && "Unexpected instr type to insert");
168 case Mips::Select_CC: {
169 // To "insert" a SELECT_CC instruction, we actually have to insert the
170 // diamond control-flow pattern. The incoming instruction knows the
171 // destination vreg to set, the condition code register to branch on, the
172 // true/false values to select between, and a branch opcode to use.
173 const BasicBlock *LLVM_BB = BB->getBasicBlock();
174 MachineFunction::iterator It = BB;
181 // bNE r1, r0, copy1MBB
182 // fallthrough --> copy0MBB
183 MachineBasicBlock *thisMBB = BB;
184 MachineFunction *F = BB->getParent();
185 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
186 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
187 BuildMI(BB, TII->get(Mips::BNE)).addReg(MI->getOperand(1).getReg())
188 .addReg(Mips::ZERO).addMBB(sinkMBB);
189 F->insert(It, copy0MBB);
190 F->insert(It, sinkMBB);
191 // Update machine-CFG edges by first adding all successors of the current
192 // block to the new block which will contain the Phi node for the select.
193 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
194 e = BB->succ_end(); i != e; ++i)
195 sinkMBB->addSuccessor(*i);
196 // Next, remove all successors of the current block, and add the true
197 // and fallthrough blocks as its successors.
198 while(!BB->succ_empty())
199 BB->removeSuccessor(BB->succ_begin());
200 BB->addSuccessor(copy0MBB);
201 BB->addSuccessor(sinkMBB);
205 // # fallthrough to sinkMBB
208 // Update machine-CFG edges
209 BB->addSuccessor(sinkMBB);
212 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
215 BuildMI(BB, TII->get(Mips::PHI), MI->getOperand(0).getReg())
216 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
217 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB);
219 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
225 //===----------------------------------------------------------------------===//
226 // Lower helper functions
227 //===----------------------------------------------------------------------===//
229 // AddLiveIn - This helper function adds the specified physical register to the
230 // MachineFunction as a live in value. It also creates a corresponding
231 // virtual register for it.
233 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
235 assert(RC->contains(PReg) && "Not the correct regclass!");
236 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
237 MF.getRegInfo().addLiveIn(PReg, VReg);
241 // A address must be loaded from a small section if its size is less than the
242 // small section size threshold. Data in this section must be addressed using
244 bool MipsTargetLowering::IsInSmallSection(unsigned Size) {
245 return (Size > 0 && (Size <= Subtarget->getSSectionThreshold()));
248 // Discover if this global address can be placed into small data/bss section.
249 bool MipsTargetLowering::IsGlobalInSmallSection(GlobalValue *GV)
251 const TargetData *TD = getTargetData();
252 const GlobalVariable *GVA = dyn_cast<GlobalVariable>(GV);
257 const Type *Ty = GV->getType()->getElementType();
258 unsigned Size = TD->getABITypeSize(Ty);
260 // if this is a internal constant string, there is a special
261 // section for it, but not in small data/bss.
262 if (GVA->hasInitializer() && GV->hasInternalLinkage()) {
263 Constant *C = GVA->getInitializer();
264 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
265 if (CVA && CVA->isCString())
269 return IsInSmallSection(Size);
272 // Get fp branch code (not opcode) from condition code.
273 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
274 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
275 return Mips::BRANCH_T;
277 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
278 return Mips::BRANCH_F;
280 return Mips::BRANCH_INVALID;
284 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
286 default: assert(0 && "Unknown fp condition code!");
288 case ISD::SETOEQ: return Mips::FCOND_EQ;
289 case ISD::SETUNE: return Mips::FCOND_OGL;
291 case ISD::SETOLT: return Mips::FCOND_OLT;
293 case ISD::SETOGT: return Mips::FCOND_OGT;
295 case ISD::SETOLE: return Mips::FCOND_OLE;
297 case ISD::SETOGE: return Mips::FCOND_OGE;
298 case ISD::SETULT: return Mips::FCOND_ULT;
299 case ISD::SETULE: return Mips::FCOND_ULE;
300 case ISD::SETUGT: return Mips::FCOND_UGT;
301 case ISD::SETUGE: return Mips::FCOND_UGE;
302 case ISD::SETUO: return Mips::FCOND_UN;
303 case ISD::SETO: return Mips::FCOND_OR;
305 case ISD::SETONE: return Mips::FCOND_NEQ;
306 case ISD::SETUEQ: return Mips::FCOND_UEQ;
310 //===----------------------------------------------------------------------===//
311 // Misc Lower Operation implementation
312 //===----------------------------------------------------------------------===//
313 SDValue MipsTargetLowering::
314 LowerBRCOND(SDValue Op, SelectionDAG &DAG)
316 // The first operand is the chain, the second is the condition, the third is
317 // the block to branch to if the condition is true.
318 SDValue Chain = Op.getOperand(0);
319 SDValue Dest = Op.getOperand(2);
322 if (Op.getOperand(1).getOpcode() == ISD::AND)
323 CondRes = Op.getOperand(1).getOperand(0);
324 else if (Op.getOperand(1).getOpcode() == MipsISD::FPCmp)
325 CondRes = Op.getOperand(1);
327 assert(0 && "Incoming condition flag unknown");
329 SDValue CCNode = CondRes.getOperand(2);
330 Mips::CondCode CC = (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getValue();
331 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
333 return DAG.getNode(MipsISD::FPBrcond, Op.getValueType(), Chain, BrCode,
337 SDValue MipsTargetLowering::
338 LowerSETCC(SDValue Op, SelectionDAG &DAG)
340 // The operands to this are the left and right operands to compare (ops #0,
341 // and #1) and the condition code to compare them with (op #2) as a
343 SDValue LHS = Op.getOperand(0);
344 SDValue RHS = Op.getOperand(1);
346 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
348 return DAG.getNode(MipsISD::FPCmp, Op.getValueType(), LHS, RHS,
349 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
352 SDValue MipsTargetLowering::
353 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
355 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
356 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
358 if (!Subtarget->hasABICall()) {
359 if (isa<Function>(GV)) return GA;
360 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
361 SDValue Ops[] = { GA };
363 if (IsGlobalInSmallSection(GV)) { // %gp_rel relocation
364 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, VTs, 1, Ops, 1);
365 SDValue GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, MVT::i32);
366 return DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
368 // %hi/%lo relocation
369 SDValue HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
370 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
371 return DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
373 } else { // Abicall relocations, TODO: make this cleaner.
374 SDValue ResNode = DAG.getLoad(MVT::i32, DAG.getEntryNode(), GA, NULL, 0);
375 // On functions and global targets not internal linked only
376 // a load from got/GP is necessary for PIC to work.
377 if (!GV->hasInternalLinkage() || isa<Function>(GV))
379 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, GA);
380 return DAG.getNode(ISD::ADD, MVT::i32, ResNode, Lo);
383 assert(0 && "Dont know how to handle GlobalAddress");
387 SDValue MipsTargetLowering::
388 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
390 assert(0 && "TLS not implemented for MIPS.");
391 return SDValue(); // Not reached
394 SDValue MipsTargetLowering::
395 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
397 SDValue LHS = Op.getOperand(0);
398 SDValue RHS = Op.getOperand(1);
399 SDValue True = Op.getOperand(2);
400 SDValue False = Op.getOperand(3);
401 SDValue CC = Op.getOperand(4);
403 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
404 SDValue Ops[] = { LHS, RHS, CC };
405 SDValue SetCCRes = DAG.getNode(ISD::SETCC, VTs, 1, Ops, 3);
407 return DAG.getNode(MipsISD::SelectCC, True.getValueType(),
408 SetCCRes, True, False);
411 SDValue MipsTargetLowering::
412 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
417 MVT PtrVT = Op.getValueType();
418 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
419 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
421 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
422 const MVT *VTs = DAG.getNodeValueTypes(MVT::i32);
423 SDValue Ops[] = { JTI };
424 HiPart = DAG.getNode(MipsISD::Hi, VTs, 1, Ops, 1);
425 } else // Emit Load from Global Pointer
426 HiPart = DAG.getLoad(MVT::i32, DAG.getEntryNode(), JTI, NULL, 0);
428 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, JTI);
429 ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
434 SDValue MipsTargetLowering::
435 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
438 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
439 Constant *C = N->getConstVal();
440 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
443 if (!Subtarget->hasABICall() &&
444 IsInSmallSection(getTargetData()->getABITypeSize(C->getType()))) {
445 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
446 SDValue GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, MVT::i32);
447 ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
448 } else { // %hi/%lo relocation
449 SDValue HiPart = DAG.getNode(MipsISD::Hi, MVT::i32, CP);
450 SDValue Lo = DAG.getNode(MipsISD::Lo, MVT::i32, CP);
451 ResNode = DAG.getNode(ISD::ADD, MVT::i32, HiPart, Lo);
457 //===----------------------------------------------------------------------===//
458 // Calling Convention Implementation
460 // The lower operations present on calling convention works on this order:
461 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
462 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
463 // LowerRET (virt regs --> phys regs)
464 // LowerCALL (phys regs --> virt regs)
466 //===----------------------------------------------------------------------===//
468 #include "MipsGenCallingConv.inc"
470 //===----------------------------------------------------------------------===//
471 // CALL Calling Convention Implementation
472 //===----------------------------------------------------------------------===//
474 /// Mips custom CALL implementation
475 SDValue MipsTargetLowering::
476 LowerCALL(SDValue Op, SelectionDAG &DAG)
478 unsigned CallingConv = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
480 // By now, only CallingConv::C implemented
481 switch (CallingConv) {
483 assert(0 && "Unsupported calling convention");
484 case CallingConv::Fast:
486 return LowerCCCCallTo(Op, DAG, CallingConv);
490 /// LowerCCCCallTo - functions arguments are copied from virtual
491 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
492 /// CALLSEQ_END are emitted.
493 /// TODO: isVarArg, isTailCall.
494 SDValue MipsTargetLowering::
495 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
497 MachineFunction &MF = DAG.getMachineFunction();
499 SDValue Chain = Op.getOperand(0);
500 SDValue Callee = Op.getOperand(4);
501 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
503 MachineFrameInfo *MFI = MF.getFrameInfo();
505 // Analyze operands of the call, assigning locations to each operand.
506 SmallVector<CCValAssign, 16> ArgLocs;
507 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
509 // To meet O32 ABI, Mips must always allocate 16 bytes on
510 // the stack (even if less than 4 are used as arguments)
511 if (Subtarget->isABI_O32()) {
512 int VTsize = MVT(MVT::i32).getSizeInBits()/8;
513 MFI->CreateFixedObject(VTsize, (VTsize*3));
516 CCInfo.AnalyzeCallOperands(Op.Val, CC_Mips);
518 // Get a count of how many bytes are to be pushed on the stack.
519 unsigned NumBytes = CCInfo.getNextStackOffset();
520 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
523 // With EABI is it possible to have 16 args on registers.
524 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
525 SmallVector<SDValue, 8> MemOpChains;
527 // First/LastArgStackLoc contains the first/last
528 // "at stack" argument location.
529 int LastArgStackLoc = 0;
530 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
532 // Walk the register/memloc assignments, inserting copies/loads.
533 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
534 CCValAssign &VA = ArgLocs[i];
536 // Arguments start after the 5 first operands of ISD::CALL
537 SDValue Arg = Op.getOperand(5+2*VA.getValNo());
539 // Promote the value if needed.
540 switch (VA.getLocInfo()) {
541 default: assert(0 && "Unknown loc info!");
542 case CCValAssign::Full: break;
543 case CCValAssign::SExt:
544 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
546 case CCValAssign::ZExt:
547 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
549 case CCValAssign::AExt:
550 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
554 // Arguments that can be passed on register must be kept at
557 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
561 // Register cant get to this point...
562 assert(VA.isMemLoc());
564 // Create the frame index object for this incoming parameter
565 // This guarantees that when allocating Local Area the firsts
566 // 16 bytes which are alwayes reserved won't be overwritten
567 // if O32 ABI is used. For EABI the first address is zero.
568 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
569 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
572 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
574 // emit ISD::STORE whichs stores the
575 // parameter value to a stack Location
576 MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
579 // Transform all store nodes into one single node because all store
580 // nodes are independent of each other.
581 if (!MemOpChains.empty())
582 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
583 &MemOpChains[0], MemOpChains.size());
585 // Build a sequence of copy-to-reg nodes chained together with token
586 // chain and flag operands which copy the outgoing args into registers.
587 // The InFlag in necessary since all emited instructions must be
590 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
591 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first,
592 RegsToPass[i].second, InFlag);
593 InFlag = Chain.getValue(1);
596 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
597 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
598 // node so that legalize doesn't hack it.
599 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
600 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
601 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
602 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
605 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
606 // = Chain, Callee, Reg#1, Reg#2, ...
608 // Returns a chain & a flag for retval copy to use.
609 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
610 SmallVector<SDValue, 8> Ops;
611 Ops.push_back(Chain);
612 Ops.push_back(Callee);
614 // Add argument registers to the end of the list so that they are
615 // known live into the call.
616 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
617 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
618 RegsToPass[i].second.getValueType()));
621 Ops.push_back(InFlag);
623 Chain = DAG.getNode(MipsISD::JmpLink, NodeTys, &Ops[0], Ops.size());
624 InFlag = Chain.getValue(1);
626 // Create the CALLSEQ_END node.
627 Chain = DAG.getCALLSEQ_END(Chain,
628 DAG.getConstant(NumBytes, getPointerTy()),
629 DAG.getConstant(0, getPointerTy()),
631 InFlag = Chain.getValue(1);
633 // Create a stack location to hold GP when PIC is used. This stack
634 // location is used on function prologue to save GP and also after all
635 // emited CALL's to restore GP.
636 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
637 // Function can have an arbitrary number of calls, so
638 // hold the LastArgStackLoc with the biggest offset.
640 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
641 if (LastArgStackLoc >= MipsFI->getGPStackOffset()) {
642 LastArgStackLoc = (!LastArgStackLoc) ? (16) : (LastArgStackLoc+4);
643 // Create the frame index only once. SPOffset here can be anything
644 // (this will be fixed on processFunctionBeforeFrameFinalized)
645 if (MipsFI->getGPStackOffset() == -1) {
646 FI = MFI->CreateFixedObject(4, 0);
649 MipsFI->setGPStackOffset(LastArgStackLoc);
653 FI = MipsFI->getGPFI();
654 SDValue FIN = DAG.getFrameIndex(FI,getPointerTy());
655 SDValue GPLoad = DAG.getLoad(MVT::i32, Chain, FIN, NULL, 0);
656 Chain = GPLoad.getValue(1);
657 Chain = DAG.getCopyToReg(Chain, DAG.getRegister(Mips::GP, MVT::i32),
658 GPLoad, SDValue(0,0));
659 InFlag = Chain.getValue(1);
662 // Handle result values, copying them out of physregs into vregs that we
664 return SDValue(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
667 /// LowerCallResult - Lower the result values of an ISD::CALL into the
668 /// appropriate copies out of appropriate physical registers. This assumes that
669 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
670 /// being lowered. Returns a SDNode with the same number of values as the
672 SDNode *MipsTargetLowering::
673 LowerCallResult(SDValue Chain, SDValue InFlag, SDNode *TheCall,
674 unsigned CallingConv, SelectionDAG &DAG) {
676 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
678 // Assign locations to each value returned by this call.
679 SmallVector<CCValAssign, 16> RVLocs;
680 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
682 CCInfo.AnalyzeCallResult(TheCall, RetCC_Mips);
683 SmallVector<SDValue, 8> ResultVals;
685 // Copy all of the result registers out of their specified physreg.
686 for (unsigned i = 0; i != RVLocs.size(); ++i) {
687 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
688 RVLocs[i].getValVT(), InFlag).getValue(1);
689 InFlag = Chain.getValue(2);
690 ResultVals.push_back(Chain.getValue(0));
693 ResultVals.push_back(Chain);
695 // Merge everything together with a MERGE_VALUES node.
696 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
697 ResultVals.size()).Val;
700 //===----------------------------------------------------------------------===//
701 // FORMAL_ARGUMENTS Calling Convention Implementation
702 //===----------------------------------------------------------------------===//
704 /// Mips custom FORMAL_ARGUMENTS implementation
705 SDValue MipsTargetLowering::
706 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
708 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
712 assert(0 && "Unsupported calling convention");
714 return LowerCCCArguments(Op, DAG);
718 /// LowerCCCArguments - transform physical registers into
719 /// virtual registers and generate load operations for
720 /// arguments places on the stack.
722 SDValue MipsTargetLowering::
723 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
725 SDValue Root = Op.getOperand(0);
726 MachineFunction &MF = DAG.getMachineFunction();
727 MachineFrameInfo *MFI = MF.getFrameInfo();
728 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
730 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
731 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
733 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
735 // GP must be live into PIC and non-PIC call target.
736 AddLiveIn(MF, Mips::GP, Mips::CPURegsRegisterClass);
738 // Assign locations to all of the incoming arguments.
739 SmallVector<CCValAssign, 16> ArgLocs;
740 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
742 CCInfo.AnalyzeFormalArguments(Op.Val, CC_Mips);
743 SmallVector<SDValue, 16> ArgValues;
746 unsigned FirstStackArgLoc = (Subtarget->isABI_EABI() ? 0 : 16);
748 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
750 CCValAssign &VA = ArgLocs[i];
752 // Arguments stored on registers
754 MVT RegVT = VA.getLocVT();
755 TargetRegisterClass *RC = 0;
757 if (RegVT == MVT::i32)
758 RC = Mips::CPURegsRegisterClass;
759 else if (RegVT == MVT::f32) {
760 if (Subtarget->isSingleFloat())
761 RC = Mips::FGR32RegisterClass;
763 RC = Mips::AFGR32RegisterClass;
764 } else if (RegVT == MVT::f64) {
765 if (!Subtarget->isSingleFloat())
766 RC = Mips::AFGR64RegisterClass;
768 assert(0 && "RegVT not supported by FORMAL_ARGUMENTS Lowering");
770 // Transform the arguments stored on
771 // physical registers into virtual ones
772 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
773 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
775 // If this is an 8 or 16-bit value, it is really passed promoted
776 // to 32 bits. Insert an assert[sz]ext to capture this, then
777 // truncate to the right size.
778 if (VA.getLocInfo() == CCValAssign::SExt)
779 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
780 DAG.getValueType(VA.getValVT()));
781 else if (VA.getLocInfo() == CCValAssign::ZExt)
782 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
783 DAG.getValueType(VA.getValVT()));
785 if (VA.getLocInfo() != CCValAssign::Full)
786 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
788 ArgValues.push_back(ArgValue);
790 // To meet ABI, when VARARGS are passed on registers, the registers
791 // must have their values written to the caller stack frame.
792 if ((isVarArg) && (Subtarget->isABI_O32())) {
793 if (StackPtr.Val == 0)
794 StackPtr = DAG.getRegister(StackReg, getPointerTy());
796 // The stack pointer offset is relative to the caller stack frame.
797 // Since the real stack size is unknown here, a negative SPOffset
798 // is used so there's a way to adjust these offsets when the stack
799 // size get known (on EliminateFrameIndex). A dummy SPOffset is
800 // used instead of a direct negative address (which is recorded to
801 // be used on emitPrologue) to avoid mis-calc of the first stack
802 // offset on PEI::calculateFrameObjectOffsets.
803 // Arguments are always 32-bit.
804 int FI = MFI->CreateFixedObject(4, 0);
805 MipsFI->recordStoreVarArgsFI(FI, -(4+(i*4)));
806 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
808 // emit ISD::STORE whichs stores the
809 // parameter value to a stack Location
810 ArgValues.push_back(DAG.getStore(Root, ArgValue, PtrOff, NULL, 0));
813 } else { // VA.isRegLoc()
816 assert(VA.isMemLoc());
818 // The stack pointer offset is relative to the caller stack frame.
819 // Since the real stack size is unknown here, a negative SPOffset
820 // is used so there's a way to adjust these offsets when the stack
821 // size get known (on EliminateFrameIndex). A dummy SPOffset is
822 // used instead of a direct negative address (which is recorded to
823 // be used on emitPrologue) to avoid mis-calc of the first stack
824 // offset on PEI::calculateFrameObjectOffsets.
825 // Arguments are always 32-bit.
826 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
827 int FI = MFI->CreateFixedObject(ArgSize, 0);
828 MipsFI->recordLoadArgsFI(FI, -(ArgSize+
829 (FirstStackArgLoc + VA.getLocMemOffset())));
831 // Create load nodes to retrieve arguments from the stack
832 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
833 ArgValues.push_back(DAG.getLoad(VA.getValVT(), Root, FIN, NULL, 0));
837 // The mips ABIs for returning structs by value requires that we copy
838 // the sret argument into $v0 for the return. Save the argument into
839 // a virtual register so that we can access it from the return points.
840 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
841 unsigned Reg = MipsFI->getSRetReturnReg();
843 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
844 MipsFI->setSRetReturnReg(Reg);
846 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
847 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
850 ArgValues.push_back(Root);
852 // Return the new list of results.
853 return DAG.getMergeValues(Op.Val->getVTList(), &ArgValues[0],
854 ArgValues.size()).getValue(Op.ResNo);
857 //===----------------------------------------------------------------------===//
858 // Return Value Calling Convention Implementation
859 //===----------------------------------------------------------------------===//
861 SDValue MipsTargetLowering::
862 LowerRET(SDValue Op, SelectionDAG &DAG)
864 // CCValAssign - represent the assignment of
865 // the return value to a location
866 SmallVector<CCValAssign, 16> RVLocs;
867 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
868 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
870 // CCState - Info about the registers and stack slot.
871 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
873 // Analize return values of ISD::RET
874 CCInfo.AnalyzeReturn(Op.Val, RetCC_Mips);
876 // If this is the first return lowered for this function, add
877 // the regs to the liveout set for the function.
878 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
879 for (unsigned i = 0; i != RVLocs.size(); ++i)
880 if (RVLocs[i].isRegLoc())
881 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
884 // The chain is always operand #0
885 SDValue Chain = Op.getOperand(0);
888 // Copy the result values into the output registers.
889 for (unsigned i = 0; i != RVLocs.size(); ++i) {
890 CCValAssign &VA = RVLocs[i];
891 assert(VA.isRegLoc() && "Can only return in registers!");
893 // ISD::RET => ret chain, (regnum1,val1), ...
894 // So i*2+1 index only the regnums
895 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
897 // guarantee that all emitted copies are
898 // stuck together, avoiding something bad
899 Flag = Chain.getValue(1);
902 // The mips ABIs for returning structs by value requires that we copy
903 // the sret argument into $v0 for the return. We saved the argument into
904 // a virtual register in the entry block, so now we copy the value out
906 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
907 MachineFunction &MF = DAG.getMachineFunction();
908 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
909 unsigned Reg = MipsFI->getSRetReturnReg();
912 assert(0 && "sret virtual register not created in the entry block");
913 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
915 Chain = DAG.getCopyToReg(Chain, Mips::V0, Val, Flag);
916 Flag = Chain.getValue(1);
919 // Return on Mips is always a "jr $ra"
921 return DAG.getNode(MipsISD::Ret, MVT::Other,
922 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
924 return DAG.getNode(MipsISD::Ret, MVT::Other,
925 Chain, DAG.getRegister(Mips::RA, MVT::i32));
928 //===----------------------------------------------------------------------===//
929 // Mips Inline Assembly Support
930 //===----------------------------------------------------------------------===//
932 /// getConstraintType - Given a constraint letter, return the type of
933 /// constraint it is for this target.
934 MipsTargetLowering::ConstraintType MipsTargetLowering::
935 getConstraintType(const std::string &Constraint) const
937 // Mips specific constrainy
938 // GCC config/mips/constraints.md
940 // 'd' : An address register. Equivalent to r
941 // unless generating MIPS16 code.
942 // 'y' : Equivalent to r; retained for
943 // backwards compatibility.
944 // 'f' : Floating Point registers.
945 if (Constraint.size() == 1) {
946 switch (Constraint[0]) {
951 return C_RegisterClass;
955 return TargetLowering::getConstraintType(Constraint);
958 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
959 /// return a list of registers that can be used to satisfy the constraint.
960 /// This should only be used for C_RegisterClass constraints.
961 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
962 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
964 if (Constraint.size() == 1) {
965 switch (Constraint[0]) {
967 return std::make_pair(0U, Mips::CPURegsRegisterClass);
969 if (VT == MVT::f32) {
970 if (Subtarget->isSingleFloat())
971 return std::make_pair(0U, Mips::FGR32RegisterClass);
973 return std::make_pair(0U, Mips::AFGR32RegisterClass);
976 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
977 return std::make_pair(0U, Mips::AFGR64RegisterClass);
980 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
983 /// Given a register class constraint, like 'r', if this corresponds directly
984 /// to an LLVM register class, return a register of 0 and the register class
986 std::vector<unsigned> MipsTargetLowering::
987 getRegClassForInlineAsmConstraint(const std::string &Constraint,
990 if (Constraint.size() != 1)
991 return std::vector<unsigned>();
993 switch (Constraint[0]) {
996 // GCC Mips Constraint Letters
999 return make_vector<unsigned>(Mips::T0, Mips::T1, Mips::T2, Mips::T3,
1000 Mips::T4, Mips::T5, Mips::T6, Mips::T7, Mips::S0, Mips::S1,
1001 Mips::S2, Mips::S3, Mips::S4, Mips::S5, Mips::S6, Mips::S7,
1005 if (VT == MVT::f32) {
1006 if (Subtarget->isSingleFloat())
1007 return make_vector<unsigned>(Mips::F2, Mips::F3, Mips::F4, Mips::F5,
1008 Mips::F6, Mips::F7, Mips::F8, Mips::F9, Mips::F10, Mips::F11,
1009 Mips::F20, Mips::F21, Mips::F22, Mips::F23, Mips::F24,
1010 Mips::F25, Mips::F26, Mips::F27, Mips::F28, Mips::F29,
1011 Mips::F30, Mips::F31, 0);
1013 return make_vector<unsigned>(Mips::F2, Mips::F4, Mips::F6, Mips::F8,
1014 Mips::F10, Mips::F20, Mips::F22, Mips::F24, Mips::F26,
1015 Mips::F28, Mips::F30, 0);
1019 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
1020 return make_vector<unsigned>(Mips::D1, Mips::D2, Mips::D3, Mips::D4,
1021 Mips::D5, Mips::D10, Mips::D11, Mips::D12, Mips::D13,
1022 Mips::D14, Mips::D15, 0);
1024 return std::vector<unsigned>();