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 ExpandADDSUB(Op.getNode(), DAG);
165 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
167 assert(0 && "unimplemented operand");
172 /// ReplaceNodeResults - Replace the results of node with an illegal result
173 /// type with new values built out of custom code.
174 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
175 SmallVectorImpl<SDValue>&Results,
177 switch (N->getOpcode()) {
179 assert(0 && "Don't know how to custom expand this!");
183 Results.push_back(ExpandADDSUB(N, DAG));
188 //===----------------------------------------------------------------------===//
189 // Misc Lower Operation implementation
190 //===----------------------------------------------------------------------===//
192 SDValue XCoreTargetLowering::
193 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
195 SDValue Cond = DAG.getNode(ISD::SETCC, MVT::i32, Op.getOperand(2),
196 Op.getOperand(3), Op.getOperand(4));
197 return DAG.getNode(ISD::SELECT, MVT::i32, Cond, Op.getOperand(0),
201 SDValue XCoreTargetLowering::
202 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
204 if (isa<Function>(GV)) {
205 return DAG.getNode(XCoreISD::PCRelativeWrapper, MVT::i32, GA);
206 } else if (!Subtarget.isXS1A()) {
207 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
209 // If GV is an alias then use the aliasee to determine constness
210 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
211 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
213 bool isConst = GVar && GVar->isConstant();
215 return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, GA);
218 return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, GA);
221 SDValue XCoreTargetLowering::
222 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
224 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
225 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
226 // If it's a debug information descriptor, don't mess with it.
227 if (DAG.isVerifiedDebugInfoDesc(Op))
229 return getGlobalAddressWrapper(GA, GV, DAG);
232 static inline SDValue BuildGetId(SelectionDAG &DAG) {
233 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, MVT::i32,
234 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
237 static inline bool isZeroLengthArray(const Type *Ty) {
238 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
239 return AT && (AT->getNumElements() == 0);
242 SDValue XCoreTargetLowering::
243 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
245 // transform to label + getid() * size
246 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
247 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
248 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
250 // If GV is an alias then use the aliasee to determine size
251 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
252 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
255 assert(0 && "Thread local object not a GlobalVariable?");
258 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
259 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
260 cerr << "Size of thread local object " << GVar->getName()
264 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
265 const TargetData *TD = TM.getTargetData();
266 unsigned Size = TD->getABITypeSize(Ty);
267 SDValue offset = DAG.getNode(ISD::MUL, MVT::i32, BuildGetId(DAG),
268 DAG.getConstant(Size, MVT::i32));
269 return DAG.getNode(ISD::ADD, MVT::i32, base, offset);
272 SDValue XCoreTargetLowering::
273 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
275 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
276 if (Subtarget.isXS1A()) {
277 assert(0 && "Lowering of constant pool unimplemented");
280 MVT PtrVT = Op.getValueType();
282 if (CP->isMachineConstantPoolEntry()) {
283 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
286 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
289 return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, Res);
293 SDValue XCoreTargetLowering::
294 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
296 MVT PtrVT = Op.getValueType();
297 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
298 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
299 return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, JTI);
302 SDValue XCoreTargetLowering::
303 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
305 assert(N->getValueType(0) == MVT::i64 &&
306 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
307 "Unknown operand to lower!");
308 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
310 // Extract components
311 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
312 DAG.getConstant(0, MVT::i32));
313 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
314 DAG.getConstant(1, MVT::i32));
315 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
316 DAG.getConstant(0, MVT::i32));
317 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
318 DAG.getConstant(1, MVT::i32));
321 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
323 SDValue Zero = DAG.getConstant(0, MVT::i32);
324 SDValue Carry = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
326 SDValue Lo(Carry.getNode(), 1);
328 SDValue Ignored = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
330 SDValue Hi(Ignored.getNode(), 1);
332 return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
335 SDValue XCoreTargetLowering::
336 LowerVAARG(SDValue Op, SelectionDAG &DAG)
338 assert(0 && "unimplemented");
339 // FIX Arguments passed by reference need a extra dereference.
340 SDNode *Node = Op.getNode();
341 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
342 MVT VT = Node->getValueType(0);
343 SDValue VAList = DAG.getLoad(getPointerTy(), Node->getOperand(0),
344 Node->getOperand(1), V, 0);
345 // Increment the pointer, VAList, to the next vararg
346 SDValue Tmp3 = DAG.getNode(ISD::ADD, getPointerTy(), VAList,
347 DAG.getConstant(VT.getSizeInBits(),
349 // Store the incremented VAList to the legalized pointer
350 Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Node->getOperand(1), V, 0);
351 // Load the actual argument out of the pointer VAList
352 return DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
355 SDValue XCoreTargetLowering::
356 LowerVASTART(SDValue Op, SelectionDAG &DAG)
358 // vastart stores the address of the VarArgsFrameIndex slot into the
359 // memory location argument
360 MachineFunction &MF = DAG.getMachineFunction();
361 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
362 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
363 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
364 return DAG.getStore(Op.getOperand(0), Addr, Op.getOperand(1), SV, 0);
367 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
368 // Depths > 0 not supported yet!
369 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
372 MachineFunction &MF = DAG.getMachineFunction();
373 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
374 return DAG.getCopyFromReg(DAG.getEntryNode(), RegInfo->getFrameRegister(MF),
378 //===----------------------------------------------------------------------===//
379 // Calling Convention Implementation
381 // The lower operations present on calling convention works on this order:
382 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
383 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
384 // LowerRET (virt regs --> phys regs)
385 // LowerCALL (phys regs --> virt regs)
387 //===----------------------------------------------------------------------===//
389 #include "XCoreGenCallingConv.inc"
391 //===----------------------------------------------------------------------===//
392 // CALL Calling Convention Implementation
393 //===----------------------------------------------------------------------===//
395 /// XCore custom CALL implementation
396 SDValue XCoreTargetLowering::
397 LowerCALL(SDValue Op, SelectionDAG &DAG)
399 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
400 unsigned CallingConv = TheCall->getCallingConv();
401 // For now, only CallingConv::C implemented
405 assert(0 && "Unsupported calling convention");
406 case CallingConv::Fast:
408 return LowerCCCCallTo(Op, DAG, CallingConv);
412 /// LowerCCCCallTo - functions arguments are copied from virtual
413 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
414 /// CALLSEQ_END are emitted.
415 /// TODO: isTailCall, sret.
416 SDValue XCoreTargetLowering::
417 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
419 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
420 SDValue Chain = TheCall->getChain();
421 SDValue Callee = TheCall->getCallee();
422 bool isVarArg = TheCall->isVarArg();
424 // Analyze operands of the call, assigning locations to each operand.
425 SmallVector<CCValAssign, 16> ArgLocs;
426 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
428 // The ABI dictates there should be one stack slot available to the callee
429 // on function entry (for saving lr).
430 CCInfo.AllocateStack(4, 4);
432 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
434 // Get a count of how many bytes are to be pushed on the stack.
435 unsigned NumBytes = CCInfo.getNextStackOffset();
437 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
438 getPointerTy(), true));
440 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
441 SmallVector<SDValue, 12> MemOpChains;
443 // Walk the register/memloc assignments, inserting copies/loads.
444 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
445 CCValAssign &VA = ArgLocs[i];
447 // Arguments start after the 5 first operands of ISD::CALL
448 SDValue Arg = TheCall->getArg(i);
450 // Promote the value if needed.
451 switch (VA.getLocInfo()) {
452 default: assert(0 && "Unknown loc info!");
453 case CCValAssign::Full: break;
454 case CCValAssign::SExt:
455 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
457 case CCValAssign::ZExt:
458 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
460 case CCValAssign::AExt:
461 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
465 // Arguments that can be passed on register must be kept at
468 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
470 assert(VA.isMemLoc());
472 int Offset = VA.getLocMemOffset();
474 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, MVT::Other, Chain, Arg,
475 DAG.getConstant(Offset/4, MVT::i32)));
479 // Transform all store nodes into one single node because
480 // all store nodes are independent of each other.
481 if (!MemOpChains.empty())
482 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
483 &MemOpChains[0], MemOpChains.size());
485 // Build a sequence of copy-to-reg nodes chained together with token
486 // chain and flag operands which copy the outgoing args into registers.
487 // The InFlag in necessary since all emited instructions must be
490 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
491 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first,
492 RegsToPass[i].second, InFlag);
493 InFlag = Chain.getValue(1);
496 // If the callee is a GlobalAddress node (quite common, every direct call is)
497 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
498 // Likewise ExternalSymbol -> TargetExternalSymbol.
499 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
500 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
501 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
502 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
504 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
505 // = Chain, Callee, Reg#1, Reg#2, ...
507 // Returns a chain & a flag for retval copy to use.
508 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
509 SmallVector<SDValue, 8> Ops;
510 Ops.push_back(Chain);
511 Ops.push_back(Callee);
513 // Add argument registers to the end of the list so that they are
514 // known live into the call.
515 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
516 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
517 RegsToPass[i].second.getValueType()));
519 if (InFlag.getNode())
520 Ops.push_back(InFlag);
522 Chain = DAG.getNode(XCoreISD::BL, NodeTys, &Ops[0], Ops.size());
523 InFlag = Chain.getValue(1);
525 // Create the CALLSEQ_END node.
526 Chain = DAG.getCALLSEQ_END(Chain,
527 DAG.getConstant(NumBytes, getPointerTy(), true),
528 DAG.getConstant(0, getPointerTy(), true),
530 InFlag = Chain.getValue(1);
532 // Handle result values, copying them out of physregs into vregs that we
534 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
538 /// LowerCallResult - Lower the result values of an ISD::CALL into the
539 /// appropriate copies out of appropriate physical registers. This assumes that
540 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
541 /// being lowered. Returns a SDNode with the same number of values as the
543 SDNode *XCoreTargetLowering::
544 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
545 unsigned CallingConv, SelectionDAG &DAG) {
546 bool isVarArg = TheCall->isVarArg();
548 // Assign locations to each value returned by this call.
549 SmallVector<CCValAssign, 16> RVLocs;
550 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
552 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
553 SmallVector<SDValue, 8> ResultVals;
555 // Copy all of the result registers out of their specified physreg.
556 for (unsigned i = 0; i != RVLocs.size(); ++i) {
557 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
558 RVLocs[i].getValVT(), InFlag).getValue(1);
559 InFlag = Chain.getValue(2);
560 ResultVals.push_back(Chain.getValue(0));
563 ResultVals.push_back(Chain);
565 // Merge everything together with a MERGE_VALUES node.
566 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
567 &ResultVals[0], ResultVals.size()).getNode();
570 //===----------------------------------------------------------------------===//
571 // FORMAL_ARGUMENTS Calling Convention Implementation
572 //===----------------------------------------------------------------------===//
574 /// XCore custom FORMAL_ARGUMENTS implementation
575 SDValue XCoreTargetLowering::
576 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
578 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
582 assert(0 && "Unsupported calling convention");
584 case CallingConv::Fast:
585 return LowerCCCArguments(Op, DAG);
589 /// LowerCCCArguments - transform physical registers into
590 /// virtual registers and generate load operations for
591 /// arguments places on the stack.
593 SDValue XCoreTargetLowering::
594 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
596 MachineFunction &MF = DAG.getMachineFunction();
597 MachineFrameInfo *MFI = MF.getFrameInfo();
598 MachineRegisterInfo &RegInfo = MF.getRegInfo();
599 SDValue Root = Op.getOperand(0);
600 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
601 unsigned CC = MF.getFunction()->getCallingConv();
603 // Assign locations to all of the incoming arguments.
604 SmallVector<CCValAssign, 16> ArgLocs;
605 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
607 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
609 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
611 SmallVector<SDValue, 16> ArgValues;
613 unsigned LRSaveSize = StackSlotSize;
615 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
617 CCValAssign &VA = ArgLocs[i];
620 // Arguments passed in registers
621 MVT RegVT = VA.getLocVT();
622 switch (RegVT.getSimpleVT()) {
624 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
625 << RegVT.getSimpleVT()
629 unsigned VReg = RegInfo.createVirtualRegister(
630 XCore::GRRegsRegisterClass);
631 RegInfo.addLiveIn(VA.getLocReg(), VReg);
632 ArgValues.push_back(DAG.getCopyFromReg(Root, VReg, RegVT));
636 assert(VA.isMemLoc());
637 // Load the argument to a virtual register
638 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
639 if (ObjSize > StackSlotSize) {
640 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
641 << VA.getLocVT().getSimpleVT()
644 // Create the frame index object for this incoming parameter...
645 int FI = MFI->CreateFixedObject(ObjSize,
646 LRSaveSize + VA.getLocMemOffset());
648 // Create the SelectionDAG nodes corresponding to a load
649 //from this parameter
650 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
651 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), Root, FIN, NULL, 0));
656 /* Argument registers */
657 static const unsigned ArgRegs[] = {
658 XCore::R0, XCore::R1, XCore::R2, XCore::R3
660 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
661 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
662 array_lengthof(ArgRegs));
663 if (FirstVAReg < array_lengthof(ArgRegs)) {
664 SmallVector<SDValue, 4> MemOps;
666 // Save remaining registers, storing higher register numbers at a higher
668 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
669 // Create a stack slot
670 int FI = MFI->CreateFixedObject(4, offset);
671 if (i == FirstVAReg) {
672 XFI->setVarArgsFrameIndex(FI);
674 offset -= StackSlotSize;
675 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
676 // Move argument from phys reg -> virt reg
677 unsigned VReg = RegInfo.createVirtualRegister(
678 XCore::GRRegsRegisterClass);
679 RegInfo.addLiveIn(ArgRegs[i], VReg);
680 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
681 // Move argument from virt reg -> stack
682 SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
683 MemOps.push_back(Store);
686 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
687 &MemOps[0], MemOps.size());
689 // This will point to the next argument passed via stack.
690 XFI->setVarArgsFrameIndex(
691 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
695 ArgValues.push_back(Root);
697 // Return the new list of results.
698 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
699 Op.getNode()->value_end());
700 return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
703 //===----------------------------------------------------------------------===//
704 // Return Value Calling Convention Implementation
705 //===----------------------------------------------------------------------===//
707 SDValue XCoreTargetLowering::
708 LowerRET(SDValue Op, SelectionDAG &DAG)
710 // CCValAssign - represent the assignment of
711 // the return value to a location
712 SmallVector<CCValAssign, 16> RVLocs;
713 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
714 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
716 // CCState - Info about the registers and stack slot.
717 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
719 // Analize return values of ISD::RET
720 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
722 // If this is the first return lowered for this function, add
723 // the regs to the liveout set for the function.
724 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
725 for (unsigned i = 0; i != RVLocs.size(); ++i)
726 if (RVLocs[i].isRegLoc())
727 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
730 // The chain is always operand #0
731 SDValue Chain = Op.getOperand(0);
734 // Copy the result values into the output registers.
735 for (unsigned i = 0; i != RVLocs.size(); ++i) {
736 CCValAssign &VA = RVLocs[i];
737 assert(VA.isRegLoc() && "Can only return in registers!");
739 // ISD::RET => ret chain, (regnum1,val1), ...
740 // So i*2+1 index only the regnums
741 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
743 // guarantee that all emitted copies are
744 // stuck together, avoiding something bad
745 Flag = Chain.getValue(1);
748 // Return on XCore is always a "retsp 0"
750 return DAG.getNode(XCoreISD::RETSP, MVT::Other,
751 Chain, DAG.getConstant(0, MVT::i32), Flag);
753 return DAG.getNode(XCoreISD::RETSP, MVT::Other,
754 Chain, DAG.getConstant(0, MVT::i32));
757 //===----------------------------------------------------------------------===//
758 // Other Lowering Code
759 //===----------------------------------------------------------------------===//
762 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
763 MachineBasicBlock *BB) {
764 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
765 assert((MI->getOpcode() == XCore::SELECT_CC) &&
766 "Unexpected instr type to insert");
768 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
769 // control-flow pattern. The incoming instruction knows the destination vreg
770 // to set, the condition code register to branch on, the true/false values to
771 // select between, and a branch opcode to use.
772 const BasicBlock *LLVM_BB = BB->getBasicBlock();
773 MachineFunction::iterator It = BB;
781 // fallthrough --> copy0MBB
782 MachineBasicBlock *thisMBB = BB;
783 MachineFunction *F = BB->getParent();
784 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
785 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
786 BuildMI(BB, TII.get(XCore::BRFT_lru6))
787 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
788 F->insert(It, copy0MBB);
789 F->insert(It, sinkMBB);
790 // Update machine-CFG edges by transferring all successors of the current
791 // block to the new block which will contain the Phi node for the select.
792 sinkMBB->transferSuccessors(BB);
793 // Next, add the true and fallthrough blocks as its successors.
794 BB->addSuccessor(copy0MBB);
795 BB->addSuccessor(sinkMBB);
799 // # fallthrough to sinkMBB
802 // Update machine-CFG edges
803 BB->addSuccessor(sinkMBB);
806 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
809 BuildMI(BB, TII.get(XCore::PHI), MI->getOperand(0).getReg())
810 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
811 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
813 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
817 //===----------------------------------------------------------------------===//
818 // Addressing mode description hooks
819 //===----------------------------------------------------------------------===//
821 static inline bool isImmUs(int64_t val)
823 return (val >= 0 && val <= 11);
826 static inline bool isImmUs2(int64_t val)
828 return (val%2 == 0 && isImmUs(val/2));
831 static inline bool isImmUs4(int64_t val)
833 return (val%4 == 0 && isImmUs(val/4));
836 /// isLegalAddressingMode - Return true if the addressing mode represented
837 /// by AM is legal for this target, for a load/store of the specified type.
839 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
840 const Type *Ty) const {
841 MVT VT = getValueType(Ty, true);
842 // Get expected value type after legalization
843 switch (VT.getSimpleVT()) {
844 // Legal load / stores
853 // Everything else is lowered to words
859 return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
863 switch (VT.getSimpleVT()) {
869 return isImmUs(AM.BaseOffs);
871 return AM.Scale == 1 && AM.BaseOffs == 0;
875 return isImmUs2(AM.BaseOffs);
877 return AM.Scale == 2 && AM.BaseOffs == 0;
881 return isImmUs4(AM.BaseOffs);
884 return AM.Scale == 4 && AM.BaseOffs == 0;
890 //===----------------------------------------------------------------------===//
891 // XCore Inline Assembly Support
892 //===----------------------------------------------------------------------===//
894 std::vector<unsigned> XCoreTargetLowering::
895 getRegClassForInlineAsmConstraint(const std::string &Constraint,
898 if (Constraint.size() != 1)
899 return std::vector<unsigned>();
901 switch (Constraint[0]) {
904 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
905 XCore::R3, XCore::R4, XCore::R5,
906 XCore::R6, XCore::R7, XCore::R8,
907 XCore::R9, XCore::R10, XCore::R11, 0);
910 return std::vector<unsigned>();