1 //===-- XCoreISelLowering.cpp - XCore 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 implements the XCoreTargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "xcore-lower"
16 #include "XCoreISelLowering.h"
17 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreTargetMachine.h"
20 #include "XCoreSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/ADT/VectorExtras.h"
40 const char *XCoreTargetLowering::
41 getTargetNodeName(unsigned Opcode) const
45 case XCoreISD::BL : return "XCoreISD::BL";
46 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
47 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
48 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
49 case XCoreISD::STWSP : return "XCoreISD::STWSP";
50 case XCoreISD::RETSP : return "XCoreISD::RETSP";
51 default : return NULL;
55 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
56 : TargetLowering(XTM),
58 Subtarget(*XTM.getSubtargetImpl()) {
60 // Set up the register classes.
61 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
63 // Compute derived properties from the register classes
64 computeRegisterProperties();
66 // Division is expensive
67 setIntDivIsCheap(false);
69 setShiftAmountType(MVT::i32);
71 setShiftAmountFlavor(Extend);
72 setStackPointerRegisterToSaveRestore(XCore::SP);
74 setSchedulingPreference(SchedulingForRegPressure);
76 // Use i32 for setcc operations results (slt, sgt, ...).
77 setBooleanContents(ZeroOrOneBooleanContent);
79 // XCore does not have the NodeTypes below.
80 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
81 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
82 setOperationAction(ISD::ADDC, MVT::i32, Expand);
83 setOperationAction(ISD::ADDE, MVT::i32, Expand);
84 setOperationAction(ISD::SUBC, MVT::i32, Expand);
85 setOperationAction(ISD::SUBE, MVT::i32, Expand);
87 // Stop the combiner recombining select and set_cc
88 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
91 if (!Subtarget.isXS1A()) {
92 setOperationAction(ISD::ADD, MVT::i64, Custom);
93 setOperationAction(ISD::SUB, MVT::i64, Custom);
95 if (Subtarget.isXS1A()) {
96 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
98 setOperationAction(ISD::MULHS, MVT::i32, Expand);
99 setOperationAction(ISD::MULHU, MVT::i32, Expand);
100 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
101 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
102 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
105 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
106 setOperationAction(ISD::ROTL , MVT::i32, Expand);
107 setOperationAction(ISD::ROTR , MVT::i32, Expand);
109 // Expand jump tables for now
110 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
111 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
113 // RET must be custom lowered, to meet ABI requirements
114 setOperationAction(ISD::RET, MVT::Other, Custom);
116 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
118 // Thread Local Storage
119 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
121 // Conversion of i64 -> double produces constantpool nodes
122 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
125 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
126 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
127 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
129 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
130 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
133 setOperationAction(ISD::VAEND, MVT::Other, Expand);
134 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
135 setOperationAction(ISD::VAARG, MVT::Other, Custom);
136 setOperationAction(ISD::VASTART, MVT::Other, Custom);
139 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
140 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
141 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
144 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
145 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
148 SDValue XCoreTargetLowering::
149 LowerOperation(SDValue Op, SelectionDAG &DAG) {
150 switch (Op.getOpcode())
152 case ISD::CALL: return LowerCALL(Op, DAG);
153 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
154 case ISD::RET: return LowerRET(Op, DAG);
155 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
156 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
157 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
158 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
159 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
160 case ISD::VAARG: return LowerVAARG(Op, DAG);
161 case ISD::VASTART: return LowerVASTART(Op, DAG);
162 // FIXME: Remove these when LegalizeDAGTypes lands.
164 case ISD::SUB: return SDValue(ExpandADDSUB(Op.getNode(), DAG),0);
165 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
167 assert(0 && "unimplemented operand");
172 /// ReplaceNodeResults - Provide custom lowering hooks for nodes with illegal
174 SDNode *XCoreTargetLowering::
175 ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
176 switch (N->getOpcode()) {
178 assert(0 && "Don't know how to custom expand this!");
181 case ISD::SUB: return ExpandADDSUB(N, DAG);
185 //===----------------------------------------------------------------------===//
186 // Misc Lower Operation implementation
187 //===----------------------------------------------------------------------===//
189 SDValue XCoreTargetLowering::
190 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
192 SDValue Cond = DAG.getNode(ISD::SETCC, MVT::i32, Op.getOperand(2),
193 Op.getOperand(3), Op.getOperand(4));
194 return DAG.getNode(ISD::SELECT, MVT::i32, Cond, Op.getOperand(0),
198 SDValue XCoreTargetLowering::
199 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
201 if (isa<Function>(GV)) {
202 return DAG.getNode(XCoreISD::PCRelativeWrapper, MVT::i32, GA);
203 } else if (!Subtarget.isXS1A()) {
204 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
206 // If GV is an alias then use the aliasee to determine constness
207 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
208 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
210 bool isConst = GVar && GVar->isConstant();
212 return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, GA);
215 return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, GA);
218 SDValue XCoreTargetLowering::
219 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
221 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
222 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
223 // If it's a debug information descriptor, don't mess with it.
224 if (DAG.isVerifiedDebugInfoDesc(Op))
226 return getGlobalAddressWrapper(GA, GV, DAG);
229 static inline SDValue BuildGetId(SelectionDAG &DAG) {
230 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, MVT::i32,
231 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
234 static inline bool isZeroLengthArray(const Type *Ty) {
235 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
236 return AT && (AT->getNumElements() == 0);
239 SDValue XCoreTargetLowering::
240 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
242 // transform to label + getid() * size
243 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
244 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
245 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
247 // If GV is an alias then use the aliasee to determine size
248 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
249 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
252 assert(0 && "Thread local object not a GlobalVariable?");
255 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
256 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
257 cerr << "Size of thread local object " << GVar->getName()
261 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
262 const TargetData *TD = TM.getTargetData();
263 unsigned Size = TD->getABITypeSize(Ty);
264 SDValue offset = DAG.getNode(ISD::MUL, MVT::i32, BuildGetId(DAG),
265 DAG.getConstant(Size, MVT::i32));
266 return DAG.getNode(ISD::ADD, MVT::i32, base, offset);
269 SDValue XCoreTargetLowering::
270 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
272 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
273 if (Subtarget.isXS1A()) {
274 assert(0 && "Lowering of constant pool unimplemented");
277 MVT PtrVT = Op.getValueType();
279 if (CP->isMachineConstantPoolEntry()) {
280 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
283 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
286 return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, Res);
290 SDValue XCoreTargetLowering::
291 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
293 MVT PtrVT = Op.getValueType();
294 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
295 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
296 return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, JTI);
299 SDNode *XCoreTargetLowering::
300 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
302 assert(N->getValueType(0) == MVT::i64 &&
303 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
304 "Unknown operand to lower!");
305 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
307 // Extract components
308 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
309 DAG.getConstant(0, MVT::i32));
310 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
311 DAG.getConstant(1, MVT::i32));
312 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
313 DAG.getConstant(0, MVT::i32));
314 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
315 DAG.getConstant(1, MVT::i32));
318 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
320 SDValue Zero = DAG.getConstant(0, MVT::i32);
321 SDValue Carry = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
323 SDValue Lo(Carry.getNode(), 1);
325 SDValue Ignored = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
327 SDValue Hi(Ignored.getNode(), 1);
329 return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi).getNode();
332 SDValue XCoreTargetLowering::
333 LowerVAARG(SDValue Op, SelectionDAG &DAG)
335 assert(0 && "unimplemented");
336 // FIX Arguments passed by reference need a extra dereference.
337 SDNode *Node = Op.getNode();
338 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
339 MVT VT = Node->getValueType(0);
340 SDValue VAList = DAG.getLoad(getPointerTy(), Node->getOperand(0),
341 Node->getOperand(1), V, 0);
342 // Increment the pointer, VAList, to the next vararg
343 SDValue Tmp3 = DAG.getNode(ISD::ADD, getPointerTy(), VAList,
344 DAG.getConstant(VT.getSizeInBits(),
346 // Store the incremented VAList to the legalized pointer
347 Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Node->getOperand(1), V, 0);
348 // Load the actual argument out of the pointer VAList
349 return DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
352 SDValue XCoreTargetLowering::
353 LowerVASTART(SDValue Op, SelectionDAG &DAG)
355 // vastart stores the address of the VarArgsFrameIndex slot into the
356 // memory location argument
357 MachineFunction &MF = DAG.getMachineFunction();
358 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
359 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
360 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
361 return DAG.getStore(Op.getOperand(0), Addr, Op.getOperand(1), SV, 0);
364 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
365 // Depths > 0 not supported yet!
366 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
369 MachineFunction &MF = DAG.getMachineFunction();
370 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
371 return DAG.getCopyFromReg(DAG.getEntryNode(), RegInfo->getFrameRegister(MF),
375 //===----------------------------------------------------------------------===//
376 // Calling Convention Implementation
378 // The lower operations present on calling convention works on this order:
379 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
380 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
381 // LowerRET (virt regs --> phys regs)
382 // LowerCALL (phys regs --> virt regs)
384 //===----------------------------------------------------------------------===//
386 #include "XCoreGenCallingConv.inc"
388 //===----------------------------------------------------------------------===//
389 // CALL Calling Convention Implementation
390 //===----------------------------------------------------------------------===//
392 /// XCore custom CALL implementation
393 SDValue XCoreTargetLowering::
394 LowerCALL(SDValue Op, SelectionDAG &DAG)
396 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
397 unsigned CallingConv = TheCall->getCallingConv();
398 // For now, only CallingConv::C implemented
402 assert(0 && "Unsupported calling convention");
403 case CallingConv::Fast:
405 return LowerCCCCallTo(Op, DAG, CallingConv);
409 /// LowerCCCCallTo - functions arguments are copied from virtual
410 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
411 /// CALLSEQ_END are emitted.
412 /// TODO: isTailCall, sret.
413 SDValue XCoreTargetLowering::
414 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
416 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
417 SDValue Chain = TheCall->getChain();
418 SDValue Callee = TheCall->getCallee();
419 bool isVarArg = TheCall->isVarArg();
421 // Analyze operands of the call, assigning locations to each operand.
422 SmallVector<CCValAssign, 16> ArgLocs;
423 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
425 // The ABI dictates there should be one stack slot available to the callee
426 // on function entry (for saving lr).
427 CCInfo.AllocateStack(4, 4);
429 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
431 // Get a count of how many bytes are to be pushed on the stack.
432 unsigned NumBytes = CCInfo.getNextStackOffset();
434 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
435 getPointerTy(), true));
437 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
438 SmallVector<SDValue, 12> MemOpChains;
440 // Walk the register/memloc assignments, inserting copies/loads.
441 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
442 CCValAssign &VA = ArgLocs[i];
444 // Arguments start after the 5 first operands of ISD::CALL
445 SDValue Arg = TheCall->getArg(i);
447 // Promote the value if needed.
448 switch (VA.getLocInfo()) {
449 default: assert(0 && "Unknown loc info!");
450 case CCValAssign::Full: break;
451 case CCValAssign::SExt:
452 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
454 case CCValAssign::ZExt:
455 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
457 case CCValAssign::AExt:
458 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
462 // Arguments that can be passed on register must be kept at
465 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
467 assert(VA.isMemLoc());
469 int Offset = VA.getLocMemOffset();
471 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, MVT::Other, Chain, Arg,
472 DAG.getConstant(Offset/4, MVT::i32)));
476 // Transform all store nodes into one single node because
477 // all store nodes are independent of each other.
478 if (!MemOpChains.empty())
479 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
480 &MemOpChains[0], MemOpChains.size());
482 // Build a sequence of copy-to-reg nodes chained together with token
483 // chain and flag operands which copy the outgoing args into registers.
484 // The InFlag in necessary since all emited instructions must be
487 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
488 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first,
489 RegsToPass[i].second, InFlag);
490 InFlag = Chain.getValue(1);
493 // If the callee is a GlobalAddress node (quite common, every direct call is)
494 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
495 // Likewise ExternalSymbol -> TargetExternalSymbol.
496 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
497 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
498 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
499 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
501 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
502 // = Chain, Callee, Reg#1, Reg#2, ...
504 // Returns a chain & a flag for retval copy to use.
505 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
506 SmallVector<SDValue, 8> Ops;
507 Ops.push_back(Chain);
508 Ops.push_back(Callee);
510 // Add argument registers to the end of the list so that they are
511 // known live into the call.
512 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
513 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
514 RegsToPass[i].second.getValueType()));
516 if (InFlag.getNode())
517 Ops.push_back(InFlag);
519 Chain = DAG.getNode(XCoreISD::BL, NodeTys, &Ops[0], Ops.size());
520 InFlag = Chain.getValue(1);
522 // Create the CALLSEQ_END node.
523 Chain = DAG.getCALLSEQ_END(Chain,
524 DAG.getConstant(NumBytes, getPointerTy(), true),
525 DAG.getConstant(0, getPointerTy(), true),
527 InFlag = Chain.getValue(1);
529 // Handle result values, copying them out of physregs into vregs that we
531 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
535 /// LowerCallResult - Lower the result values of an ISD::CALL into the
536 /// appropriate copies out of appropriate physical registers. This assumes that
537 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
538 /// being lowered. Returns a SDNode with the same number of values as the
540 SDNode *XCoreTargetLowering::
541 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
542 unsigned CallingConv, SelectionDAG &DAG) {
543 bool isVarArg = TheCall->isVarArg();
545 // Assign locations to each value returned by this call.
546 SmallVector<CCValAssign, 16> RVLocs;
547 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
549 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
550 SmallVector<SDValue, 8> ResultVals;
552 // Copy all of the result registers out of their specified physreg.
553 for (unsigned i = 0; i != RVLocs.size(); ++i) {
554 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
555 RVLocs[i].getValVT(), InFlag).getValue(1);
556 InFlag = Chain.getValue(2);
557 ResultVals.push_back(Chain.getValue(0));
560 ResultVals.push_back(Chain);
562 // Merge everything together with a MERGE_VALUES node.
563 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
564 &ResultVals[0], ResultVals.size()).getNode();
567 //===----------------------------------------------------------------------===//
568 // FORMAL_ARGUMENTS Calling Convention Implementation
569 //===----------------------------------------------------------------------===//
571 /// XCore custom FORMAL_ARGUMENTS implementation
572 SDValue XCoreTargetLowering::
573 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
575 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
579 assert(0 && "Unsupported calling convention");
581 case CallingConv::Fast:
582 return LowerCCCArguments(Op, DAG);
586 /// LowerCCCArguments - transform physical registers into
587 /// virtual registers and generate load operations for
588 /// arguments places on the stack.
590 SDValue XCoreTargetLowering::
591 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
593 MachineFunction &MF = DAG.getMachineFunction();
594 MachineFrameInfo *MFI = MF.getFrameInfo();
595 MachineRegisterInfo &RegInfo = MF.getRegInfo();
596 SDValue Root = Op.getOperand(0);
597 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
598 unsigned CC = MF.getFunction()->getCallingConv();
600 // Assign locations to all of the incoming arguments.
601 SmallVector<CCValAssign, 16> ArgLocs;
602 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
604 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
606 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
608 SmallVector<SDValue, 16> ArgValues;
610 unsigned LRSaveSize = StackSlotSize;
612 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
614 CCValAssign &VA = ArgLocs[i];
617 // Arguments passed in registers
618 MVT RegVT = VA.getLocVT();
619 switch (RegVT.getSimpleVT()) {
621 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
622 << RegVT.getSimpleVT()
626 unsigned VReg = RegInfo.createVirtualRegister(
627 XCore::GRRegsRegisterClass);
628 RegInfo.addLiveIn(VA.getLocReg(), VReg);
629 ArgValues.push_back(DAG.getCopyFromReg(Root, VReg, RegVT));
633 assert(VA.isMemLoc());
634 // Load the argument to a virtual register
635 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
636 if (ObjSize > StackSlotSize) {
637 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
638 << VA.getLocVT().getSimpleVT()
641 // Create the frame index object for this incoming parameter...
642 int FI = MFI->CreateFixedObject(ObjSize,
643 LRSaveSize + VA.getLocMemOffset());
645 // Create the SelectionDAG nodes corresponding to a load
646 //from this parameter
647 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
648 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), Root, FIN, NULL, 0));
653 /* Argument registers */
654 static const unsigned ArgRegs[] = {
655 XCore::R0, XCore::R1, XCore::R2, XCore::R3
657 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
658 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
659 array_lengthof(ArgRegs));
660 if (FirstVAReg < array_lengthof(ArgRegs)) {
661 SmallVector<SDValue, 4> MemOps;
663 // Save remaining registers, storing higher register numbers at a higher
665 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
666 // Create a stack slot
667 int FI = MFI->CreateFixedObject(4, offset);
668 if (i == FirstVAReg) {
669 XFI->setVarArgsFrameIndex(FI);
671 offset -= StackSlotSize;
672 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
673 // Move argument from phys reg -> virt reg
674 unsigned VReg = RegInfo.createVirtualRegister(
675 XCore::GRRegsRegisterClass);
676 RegInfo.addLiveIn(ArgRegs[i], VReg);
677 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
678 // Move argument from virt reg -> stack
679 SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
680 MemOps.push_back(Store);
683 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
684 &MemOps[0], MemOps.size());
686 // This will point to the next argument passed via stack.
687 XFI->setVarArgsFrameIndex(
688 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
692 ArgValues.push_back(Root);
694 // Return the new list of results.
695 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
696 Op.getNode()->value_end());
697 return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
700 //===----------------------------------------------------------------------===//
701 // Return Value Calling Convention Implementation
702 //===----------------------------------------------------------------------===//
704 SDValue XCoreTargetLowering::
705 LowerRET(SDValue Op, SelectionDAG &DAG)
707 // CCValAssign - represent the assignment of
708 // the return value to a location
709 SmallVector<CCValAssign, 16> RVLocs;
710 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
711 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
713 // CCState - Info about the registers and stack slot.
714 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
716 // Analize return values of ISD::RET
717 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
719 // If this is the first return lowered for this function, add
720 // the regs to the liveout set for the function.
721 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
722 for (unsigned i = 0; i != RVLocs.size(); ++i)
723 if (RVLocs[i].isRegLoc())
724 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
727 // The chain is always operand #0
728 SDValue Chain = Op.getOperand(0);
731 // Copy the result values into the output registers.
732 for (unsigned i = 0; i != RVLocs.size(); ++i) {
733 CCValAssign &VA = RVLocs[i];
734 assert(VA.isRegLoc() && "Can only return in registers!");
736 // ISD::RET => ret chain, (regnum1,val1), ...
737 // So i*2+1 index only the regnums
738 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
740 // guarantee that all emitted copies are
741 // stuck together, avoiding something bad
742 Flag = Chain.getValue(1);
745 // Return on XCore is always a "retsp 0"
747 return DAG.getNode(XCoreISD::RETSP, MVT::Other,
748 Chain, DAG.getConstant(0, MVT::i32), Flag);
750 return DAG.getNode(XCoreISD::RETSP, MVT::Other,
751 Chain, DAG.getConstant(0, MVT::i32));
754 //===----------------------------------------------------------------------===//
755 // Other Lowering Code
756 //===----------------------------------------------------------------------===//
759 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
760 MachineBasicBlock *BB) {
761 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
762 assert((MI->getOpcode() == XCore::SELECT_CC) &&
763 "Unexpected instr type to insert");
765 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
766 // control-flow pattern. The incoming instruction knows the destination vreg
767 // to set, the condition code register to branch on, the true/false values to
768 // select between, and a branch opcode to use.
769 const BasicBlock *LLVM_BB = BB->getBasicBlock();
770 MachineFunction::iterator It = BB;
778 // fallthrough --> copy0MBB
779 MachineBasicBlock *thisMBB = BB;
780 MachineFunction *F = BB->getParent();
781 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
782 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
783 BuildMI(BB, TII.get(XCore::BRFT_lru6))
784 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
785 F->insert(It, copy0MBB);
786 F->insert(It, sinkMBB);
787 // Update machine-CFG edges by transferring all successors of the current
788 // block to the new block which will contain the Phi node for the select.
789 sinkMBB->transferSuccessors(BB);
790 // Next, add the true and fallthrough blocks as its successors.
791 BB->addSuccessor(copy0MBB);
792 BB->addSuccessor(sinkMBB);
796 // # fallthrough to sinkMBB
799 // Update machine-CFG edges
800 BB->addSuccessor(sinkMBB);
803 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
806 BuildMI(BB, TII.get(XCore::PHI), MI->getOperand(0).getReg())
807 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
808 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
810 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
814 //===----------------------------------------------------------------------===//
815 // Addressing mode description hooks
816 //===----------------------------------------------------------------------===//
818 static inline bool isImmUs(int64_t val)
820 return (val >= 0 && val <= 11);
823 static inline bool isImmUs2(int64_t val)
825 return (val%2 == 0 && isImmUs(val/2));
828 static inline bool isImmUs4(int64_t val)
830 return (val%4 == 0 && isImmUs(val/4));
833 /// isLegalAddressingMode - Return true if the addressing mode represented
834 /// by AM is legal for this target, for a load/store of the specified type.
836 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
837 const Type *Ty) const {
838 MVT VT = getValueType(Ty, true);
839 // Get expected value type after legalization
840 switch (VT.getSimpleVT()) {
841 // Legal load / stores
850 // Everything else is lowered to words
856 return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
860 switch (VT.getSimpleVT()) {
866 return isImmUs(AM.BaseOffs);
868 return AM.Scale == 1 && AM.BaseOffs == 0;
872 return isImmUs2(AM.BaseOffs);
874 return AM.Scale == 2 && AM.BaseOffs == 0;
878 return isImmUs4(AM.BaseOffs);
881 return AM.Scale == 4 && AM.BaseOffs == 0;
887 //===----------------------------------------------------------------------===//
888 // XCore Inline Assembly Support
889 //===----------------------------------------------------------------------===//
891 std::vector<unsigned> XCoreTargetLowering::
892 getRegClassForInlineAsmConstraint(const std::string &Constraint,
895 if (Constraint.size() != 1)
896 return std::vector<unsigned>();
898 switch (Constraint[0]) {
901 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
902 XCore::R3, XCore::R4, XCore::R5,
903 XCore::R6, XCore::R7, XCore::R8,
904 XCore::R9, XCore::R10, XCore::R11, 0);
907 return std::vector<unsigned>();