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 setSetCCResultContents(ZeroOrOneSetCCResult);
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 setOperationAction(ISD::ADD, MVT::i64, Custom);
92 setOperationAction(ISD::SUB, MVT::i64, Custom);
94 if (Subtarget.isXS1A()) {
95 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
97 setOperationAction(ISD::MULHS, MVT::i32, Expand);
98 setOperationAction(ISD::MULHU, MVT::i32, Expand);
99 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
100 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
101 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
104 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
105 setOperationAction(ISD::ROTL , MVT::i32, Expand);
106 setOperationAction(ISD::ROTR , MVT::i32, Expand);
108 // Expand jump tables for now
109 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
110 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
112 // RET must be custom lowered, to meet ABI requirements
113 setOperationAction(ISD::RET, MVT::Other, Custom);
115 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
117 // Thread Local Storage
118 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
120 // Conversion of i64 -> double produces constantpool nodes
121 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
124 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
125 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
126 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
128 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
129 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
132 setOperationAction(ISD::VAEND, MVT::Other, Expand);
133 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
134 setOperationAction(ISD::VAARG, MVT::Other, Custom);
135 setOperationAction(ISD::VASTART, MVT::Other, Custom);
138 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
139 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
140 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
143 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
144 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
147 SDValue XCoreTargetLowering::
148 LowerOperation(SDValue Op, SelectionDAG &DAG) {
149 switch (Op.getOpcode())
151 case ISD::CALL: return LowerCALL(Op, DAG);
152 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
153 case ISD::RET: return LowerRET(Op, DAG);
154 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
155 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
156 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
157 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
158 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
159 case ISD::VAARG: return LowerVAARG(Op, DAG);
160 case ISD::VASTART: return LowerVASTART(Op, DAG);
161 // FIXME: Remove these when LegalizeDAGTypes lands.
163 case ISD::SUB: return SDValue(ExpandADDSUB(Op.getNode(), DAG),0);
165 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
167 assert(0 && "unimplemented operand");
172 SDNode *XCoreTargetLowering::
173 ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
174 switch (N->getOpcode()) {
177 return ExpandADDSUB(N, DAG);
179 assert(0 && "Wasn't expecting to be able to lower this!");
184 //===----------------------------------------------------------------------===//
185 // Misc Lower Operation implementation
186 //===----------------------------------------------------------------------===//
188 SDValue XCoreTargetLowering::
189 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
191 SDValue Cond = DAG.getNode(ISD::SETCC, MVT::i32, Op.getOperand(2),
192 Op.getOperand(3), Op.getOperand(4));
193 return DAG.getNode(ISD::SELECT, MVT::i32, Cond, Op.getOperand(0),
197 SDValue XCoreTargetLowering::
198 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
200 if (isa<Function>(GV)) {
201 return DAG.getNode(XCoreISD::PCRelativeWrapper, MVT::i32, GA);
202 } else if (!Subtarget.isXS1A()) {
203 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
205 // If GV is an alias then use the aliasee to determine constness
206 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
207 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
209 bool isConst = GVar && GVar->isConstant();
211 return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, GA);
214 return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, GA);
217 SDValue XCoreTargetLowering::
218 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
220 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
221 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
222 // If it's a debug information descriptor, don't mess with it.
223 if (DAG.isVerifiedDebugInfoDesc(Op))
225 return getGlobalAddressWrapper(GA, GV, DAG);
228 static inline SDValue BuildGetId(SelectionDAG &DAG) {
229 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, MVT::i32,
230 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
233 static inline bool isZeroLengthArray(const Type *Ty) {
234 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
235 return AT && (AT->getNumElements() == 0);
238 SDValue XCoreTargetLowering::
239 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
241 // transform to label + getid() * size
242 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
243 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
244 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
246 // If GV is an alias then use the aliasee to determine size
247 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
248 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
251 assert(0 && "Thread local object not a GlobalVariable?");
254 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
255 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
256 cerr << "Size of thread local object " << GVar->getName()
260 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
261 const TargetData *TD = TM.getTargetData();
262 unsigned Size = TD->getABITypeSize(Ty);
263 SDValue offset = DAG.getNode(ISD::MUL, MVT::i32, BuildGetId(DAG),
264 DAG.getConstant(Size, MVT::i32));
265 return DAG.getNode(ISD::ADD, MVT::i32, base, offset);
268 SDValue XCoreTargetLowering::
269 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
271 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
272 if (Subtarget.isXS1A()) {
273 assert(0 && "Lowering of constant pool unimplemented");
276 MVT PtrVT = Op.getValueType();
278 if (CP->isMachineConstantPoolEntry()) {
279 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
282 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
285 return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, Res);
289 SDValue XCoreTargetLowering::
290 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
292 MVT PtrVT = Op.getValueType();
293 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
294 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
295 return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, JTI);
298 SDNode *XCoreTargetLowering::
299 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
301 assert(N->getValueType(0) == MVT::i64 &&
302 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
303 "Unknown operand to lower!");
305 // Extract components
306 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
307 DAG.getConstant(0, MVT::i32));
308 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
309 DAG.getConstant(1, MVT::i32));
310 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
311 DAG.getConstant(0, MVT::i32));
312 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
313 DAG.getConstant(1, MVT::i32));
316 if (Subtarget.isXS1A()) {
317 SDValue Lo = DAG.getNode(N->getOpcode(), MVT::i32, LHSL, RHSL);
319 ISD::CondCode CarryCC = (N->getOpcode() == ISD::ADD) ? ISD::SETULT :
321 SDValue Carry = DAG.getSetCC(MVT::i32, Lo, LHSL, CarryCC);
323 SDValue Hi = DAG.getNode(N->getOpcode(), MVT::i32, LHSH, Carry);
324 Hi = DAG.getNode(N->getOpcode(), MVT::i32, Hi, RHSH);
326 return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi).getNode();
328 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
330 SDValue Zero = DAG.getConstant(0, MVT::i32);
331 SDValue Carry = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
333 SDValue Lo(Carry.getNode(), 1);
335 SDValue Ignored = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
337 SDValue Hi(Ignored.getNode(), 1);
339 return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi).getNode();
342 SDValue XCoreTargetLowering::
343 LowerVAARG(SDValue Op, SelectionDAG &DAG)
345 assert(0 && "unimplemented");
346 // FIX Arguments passed by reference need a extra dereference.
347 SDNode *Node = Op.getNode();
348 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
349 MVT VT = Node->getValueType(0);
350 SDValue VAList = DAG.getLoad(getPointerTy(), Node->getOperand(0),
351 Node->getOperand(1), V, 0);
352 // Increment the pointer, VAList, to the next vararg
353 SDValue Tmp3 = DAG.getNode(ISD::ADD, getPointerTy(), VAList,
354 DAG.getConstant(VT.getSizeInBits(),
356 // Store the incremented VAList to the legalized pointer
357 Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Node->getOperand(1), V, 0);
358 // Load the actual argument out of the pointer VAList
359 return DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
362 SDValue XCoreTargetLowering::
363 LowerVASTART(SDValue Op, SelectionDAG &DAG)
365 // vastart stores the address of the VarArgsFrameIndex slot into the
366 // memory location argument
367 MachineFunction &MF = DAG.getMachineFunction();
368 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
369 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
370 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
371 return DAG.getStore(Op.getOperand(0), Addr, Op.getOperand(1), SV, 0);
374 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
375 // Depths > 0 not supported yet!
376 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
379 MachineFunction &MF = DAG.getMachineFunction();
380 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
381 return DAG.getCopyFromReg(DAG.getEntryNode(), RegInfo->getFrameRegister(MF),
385 //===----------------------------------------------------------------------===//
386 // Calling Convention Implementation
388 // The lower operations present on calling convention works on this order:
389 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
390 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
391 // LowerRET (virt regs --> phys regs)
392 // LowerCALL (phys regs --> virt regs)
394 //===----------------------------------------------------------------------===//
396 #include "XCoreGenCallingConv.inc"
398 //===----------------------------------------------------------------------===//
399 // CALL Calling Convention Implementation
400 //===----------------------------------------------------------------------===//
402 /// XCore custom CALL implementation
403 SDValue XCoreTargetLowering::
404 LowerCALL(SDValue Op, SelectionDAG &DAG)
406 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
407 unsigned CallingConv = TheCall->getCallingConv();
408 // For now, only CallingConv::C implemented
412 assert(0 && "Unsupported calling convention");
413 case CallingConv::Fast:
415 return LowerCCCCallTo(Op, DAG, CallingConv);
419 /// LowerCCCCallTo - functions arguments are copied from virtual
420 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
421 /// CALLSEQ_END are emitted.
422 /// TODO: isTailCall, sret.
423 SDValue XCoreTargetLowering::
424 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
426 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
427 SDValue Chain = TheCall->getChain();
428 SDValue Callee = TheCall->getCallee();
429 bool isVarArg = TheCall->isVarArg();
431 // Analyze operands of the call, assigning locations to each operand.
432 SmallVector<CCValAssign, 16> ArgLocs;
433 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
435 // The ABI dictates there should be one stack slot available to the callee
436 // on function entry (for saving lr).
437 CCInfo.AllocateStack(4, 4);
439 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
441 // Get a count of how many bytes are to be pushed on the stack.
442 unsigned NumBytes = CCInfo.getNextStackOffset();
444 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
445 getPointerTy(), true));
447 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
448 SmallVector<SDValue, 12> MemOpChains;
450 // Walk the register/memloc assignments, inserting copies/loads.
451 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
452 CCValAssign &VA = ArgLocs[i];
454 // Arguments start after the 5 first operands of ISD::CALL
455 SDValue Arg = TheCall->getArg(i);
457 // Promote the value if needed.
458 switch (VA.getLocInfo()) {
459 default: assert(0 && "Unknown loc info!");
460 case CCValAssign::Full: break;
461 case CCValAssign::SExt:
462 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
464 case CCValAssign::ZExt:
465 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
467 case CCValAssign::AExt:
468 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
472 // Arguments that can be passed on register must be kept at
475 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
477 assert(VA.isMemLoc());
479 int Offset = VA.getLocMemOffset();
481 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, MVT::Other, Chain, Arg,
482 DAG.getConstant(Offset/4, MVT::i32)));
486 // Transform all store nodes into one single node because
487 // all store nodes are independent of each other.
488 if (!MemOpChains.empty())
489 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
490 &MemOpChains[0], MemOpChains.size());
492 // Build a sequence of copy-to-reg nodes chained together with token
493 // chain and flag operands which copy the outgoing args into registers.
494 // The InFlag in necessary since all emited instructions must be
497 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
498 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first,
499 RegsToPass[i].second, InFlag);
500 InFlag = Chain.getValue(1);
503 // If the callee is a GlobalAddress node (quite common, every direct call is)
504 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
505 // Likewise ExternalSymbol -> TargetExternalSymbol.
506 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
507 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
508 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
509 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
511 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
512 // = Chain, Callee, Reg#1, Reg#2, ...
514 // Returns a chain & a flag for retval copy to use.
515 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
516 SmallVector<SDValue, 8> Ops;
517 Ops.push_back(Chain);
518 Ops.push_back(Callee);
520 // Add argument registers to the end of the list so that they are
521 // known live into the call.
522 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
523 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
524 RegsToPass[i].second.getValueType()));
526 if (InFlag.getNode())
527 Ops.push_back(InFlag);
529 Chain = DAG.getNode(XCoreISD::BL, NodeTys, &Ops[0], Ops.size());
530 InFlag = Chain.getValue(1);
532 // Create the CALLSEQ_END node.
533 Chain = DAG.getCALLSEQ_END(Chain,
534 DAG.getConstant(NumBytes, getPointerTy(), true),
535 DAG.getConstant(0, getPointerTy(), true),
537 InFlag = Chain.getValue(1);
539 // Handle result values, copying them out of physregs into vregs that we
541 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
545 /// LowerCallResult - Lower the result values of an ISD::CALL into the
546 /// appropriate copies out of appropriate physical registers. This assumes that
547 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
548 /// being lowered. Returns a SDNode with the same number of values as the
550 SDNode *XCoreTargetLowering::
551 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
552 unsigned CallingConv, SelectionDAG &DAG) {
553 bool isVarArg = TheCall->isVarArg();
555 // Assign locations to each value returned by this call.
556 SmallVector<CCValAssign, 16> RVLocs;
557 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
559 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
560 SmallVector<SDValue, 8> ResultVals;
562 // Copy all of the result registers out of their specified physreg.
563 for (unsigned i = 0; i != RVLocs.size(); ++i) {
564 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
565 RVLocs[i].getValVT(), InFlag).getValue(1);
566 InFlag = Chain.getValue(2);
567 ResultVals.push_back(Chain.getValue(0));
570 ResultVals.push_back(Chain);
572 // Merge everything together with a MERGE_VALUES node.
573 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
574 &ResultVals[0], ResultVals.size()).getNode();
577 //===----------------------------------------------------------------------===//
578 // FORMAL_ARGUMENTS Calling Convention Implementation
579 //===----------------------------------------------------------------------===//
581 /// XCore custom FORMAL_ARGUMENTS implementation
582 SDValue XCoreTargetLowering::
583 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
585 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
589 assert(0 && "Unsupported calling convention");
591 case CallingConv::Fast:
592 return LowerCCCArguments(Op, DAG);
596 /// LowerCCCArguments - transform physical registers into
597 /// virtual registers and generate load operations for
598 /// arguments places on the stack.
600 SDValue XCoreTargetLowering::
601 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
603 MachineFunction &MF = DAG.getMachineFunction();
604 MachineFrameInfo *MFI = MF.getFrameInfo();
605 MachineRegisterInfo &RegInfo = MF.getRegInfo();
606 SDValue Root = Op.getOperand(0);
607 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
608 unsigned CC = MF.getFunction()->getCallingConv();
610 // Assign locations to all of the incoming arguments.
611 SmallVector<CCValAssign, 16> ArgLocs;
612 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
614 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
616 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
618 SmallVector<SDValue, 16> ArgValues;
620 unsigned LRSaveSize = StackSlotSize;
622 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
624 CCValAssign &VA = ArgLocs[i];
627 // Arguments passed in registers
628 MVT RegVT = VA.getLocVT();
629 switch (RegVT.getSimpleVT()) {
631 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
632 << RegVT.getSimpleVT()
636 unsigned VReg = RegInfo.createVirtualRegister(
637 XCore::GRRegsRegisterClass);
638 RegInfo.addLiveIn(VA.getLocReg(), VReg);
639 ArgValues.push_back(DAG.getCopyFromReg(Root, VReg, RegVT));
643 assert(VA.isMemLoc());
644 // Load the argument to a virtual register
645 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
646 if (ObjSize > StackSlotSize) {
647 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
648 << VA.getLocVT().getSimpleVT()
651 // Create the frame index object for this incoming parameter...
652 int FI = MFI->CreateFixedObject(ObjSize,
653 LRSaveSize + VA.getLocMemOffset());
655 // Create the SelectionDAG nodes corresponding to a load
656 //from this parameter
657 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
658 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), Root, FIN, NULL, 0));
663 /* Argument registers */
664 static const unsigned ArgRegs[] = {
665 XCore::R0, XCore::R1, XCore::R2, XCore::R3
667 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
668 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
669 array_lengthof(ArgRegs));
670 if (FirstVAReg < array_lengthof(ArgRegs)) {
671 SmallVector<SDValue, 4> MemOps;
673 // Save remaining registers, storing higher register numbers at a higher
675 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
676 // Create a stack slot
677 int FI = MFI->CreateFixedObject(4, offset);
678 if (i == FirstVAReg) {
679 XFI->setVarArgsFrameIndex(FI);
681 offset -= StackSlotSize;
682 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
683 // Move argument from phys reg -> virt reg
684 unsigned VReg = RegInfo.createVirtualRegister(
685 XCore::GRRegsRegisterClass);
686 RegInfo.addLiveIn(ArgRegs[i], VReg);
687 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
688 // Move argument from virt reg -> stack
689 SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
690 MemOps.push_back(Store);
693 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
694 &MemOps[0], MemOps.size());
696 // This will point to the next argument passed via stack.
697 XFI->setVarArgsFrameIndex(
698 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
702 ArgValues.push_back(Root);
704 // Return the new list of results.
705 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
706 Op.getNode()->value_end());
707 return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
710 //===----------------------------------------------------------------------===//
711 // Return Value Calling Convention Implementation
712 //===----------------------------------------------------------------------===//
714 SDValue XCoreTargetLowering::
715 LowerRET(SDValue Op, SelectionDAG &DAG)
717 // CCValAssign - represent the assignment of
718 // the return value to a location
719 SmallVector<CCValAssign, 16> RVLocs;
720 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
721 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
723 // CCState - Info about the registers and stack slot.
724 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
726 // Analize return values of ISD::RET
727 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
729 // If this is the first return lowered for this function, add
730 // the regs to the liveout set for the function.
731 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
732 for (unsigned i = 0; i != RVLocs.size(); ++i)
733 if (RVLocs[i].isRegLoc())
734 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
737 // The chain is always operand #0
738 SDValue Chain = Op.getOperand(0);
741 // Copy the result values into the output registers.
742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
743 CCValAssign &VA = RVLocs[i];
744 assert(VA.isRegLoc() && "Can only return in registers!");
746 // ISD::RET => ret chain, (regnum1,val1), ...
747 // So i*2+1 index only the regnums
748 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
750 // guarantee that all emitted copies are
751 // stuck together, avoiding something bad
752 Flag = Chain.getValue(1);
755 // Return on XCore is always a "retsp 0"
757 return DAG.getNode(XCoreISD::RETSP, MVT::Other,
758 Chain, DAG.getConstant(0, MVT::i32), Flag);
760 return DAG.getNode(XCoreISD::RETSP, MVT::Other,
761 Chain, DAG.getConstant(0, MVT::i32));
764 //===----------------------------------------------------------------------===//
765 // Other Lowering Code
766 //===----------------------------------------------------------------------===//
769 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
770 MachineBasicBlock *BB) {
771 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
772 assert((MI->getOpcode() == XCore::SELECT_CC) &&
773 "Unexpected instr type to insert");
775 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
776 // control-flow pattern. The incoming instruction knows the destination vreg
777 // to set, the condition code register to branch on, the true/false values to
778 // select between, and a branch opcode to use.
779 const BasicBlock *LLVM_BB = BB->getBasicBlock();
780 MachineFunction::iterator It = BB;
788 // fallthrough --> copy0MBB
789 MachineBasicBlock *thisMBB = BB;
790 MachineFunction *F = BB->getParent();
791 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
792 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
793 BuildMI(BB, TII.get(XCore::BRFT_lru6))
794 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
795 F->insert(It, copy0MBB);
796 F->insert(It, sinkMBB);
797 // Update machine-CFG edges by transferring all successors of the current
798 // block to the new block which will contain the Phi node for the select.
799 sinkMBB->transferSuccessors(BB);
800 // Next, add the true and fallthrough blocks as its successors.
801 BB->addSuccessor(copy0MBB);
802 BB->addSuccessor(sinkMBB);
806 // # fallthrough to sinkMBB
809 // Update machine-CFG edges
810 BB->addSuccessor(sinkMBB);
813 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
816 BuildMI(BB, TII.get(XCore::PHI), MI->getOperand(0).getReg())
817 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
818 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
820 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
824 //===----------------------------------------------------------------------===//
825 // Addressing mode description hooks
826 //===----------------------------------------------------------------------===//
828 static inline bool isImmUs(int64_t val)
830 return (val >= 0 && val <= 11);
833 static inline bool isImmUs2(int64_t val)
835 return (val%2 == 0 && isImmUs(val/2));
838 static inline bool isImmUs4(int64_t val)
840 return (val%4 == 0 && isImmUs(val/4));
843 /// isLegalAddressingMode - Return true if the addressing mode represented
844 /// by AM is legal for this target, for a load/store of the specified type.
846 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
847 const Type *Ty) const {
848 MVT VT = getValueType(Ty, true);
849 // Get expected value type after legalization
850 switch (VT.getSimpleVT()) {
851 // Legal load / stores
860 // Everything else is lowered to words
866 return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
870 switch (VT.getSimpleVT()) {
876 return isImmUs(AM.BaseOffs);
878 return AM.Scale == 1 && AM.BaseOffs == 0;
882 return isImmUs2(AM.BaseOffs);
884 return AM.Scale == 2 && AM.BaseOffs == 0;
888 return isImmUs4(AM.BaseOffs);
891 return AM.Scale == 4 && AM.BaseOffs == 0;
897 //===----------------------------------------------------------------------===//
898 // XCore Inline Assembly Support
899 //===----------------------------------------------------------------------===//
901 std::vector<unsigned> XCoreTargetLowering::
902 getRegClassForInlineAsmConstraint(const std::string &Constraint,
905 if (Constraint.size() != 1)
906 return std::vector<unsigned>();
908 switch (Constraint[0]) {
911 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
912 XCore::R3, XCore::R4, XCore::R5,
913 XCore::R6, XCore::R7, XCore::R8,
914 XCore::R9, XCore::R10, XCore::R11, 0);
917 return std::vector<unsigned>();