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 "XCoreTargetObjectFile.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreSubtarget.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/GlobalAlias.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ADT/VectorExtras.h"
43 const char *XCoreTargetLowering::
44 getTargetNodeName(unsigned Opcode) const
48 case XCoreISD::BL : return "XCoreISD::BL";
49 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
50 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
51 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
52 case XCoreISD::STWSP : return "XCoreISD::STWSP";
53 case XCoreISD::RETSP : return "XCoreISD::RETSP";
54 default : return NULL;
58 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
59 : TargetLowering(XTM, new XCoreTargetObjectFile()),
61 Subtarget(*XTM.getSubtargetImpl()) {
63 // Set up the register classes.
64 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
66 // Compute derived properties from the register classes
67 computeRegisterProperties();
69 // Division is expensive
70 setIntDivIsCheap(false);
72 setShiftAmountType(MVT::i32);
73 setStackPointerRegisterToSaveRestore(XCore::SP);
75 setSchedulingPreference(SchedulingForRegPressure);
77 // Use i32 for setcc operations results (slt, sgt, ...).
78 setBooleanContents(ZeroOrOneBooleanContent);
80 // XCore does not have the NodeTypes below.
81 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
82 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
83 setOperationAction(ISD::ADDC, MVT::i32, Expand);
84 setOperationAction(ISD::ADDE, MVT::i32, Expand);
85 setOperationAction(ISD::SUBC, MVT::i32, Expand);
86 setOperationAction(ISD::SUBE, MVT::i32, Expand);
88 // Stop the combiner recombining select and set_cc
89 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
92 if (!Subtarget.isXS1A()) {
93 setOperationAction(ISD::ADD, MVT::i64, Custom);
94 setOperationAction(ISD::SUB, MVT::i64, Custom);
96 if (Subtarget.isXS1A()) {
97 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
99 setOperationAction(ISD::MULHS, MVT::i32, Expand);
100 setOperationAction(ISD::MULHU, MVT::i32, Expand);
101 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
102 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
103 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
106 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
107 setOperationAction(ISD::ROTL , MVT::i32, Expand);
108 setOperationAction(ISD::ROTR , MVT::i32, Expand);
110 setOperationAction(ISD::TRAP, MVT::Other, Legal);
112 // Expand jump tables for now
113 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
114 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
116 // RET must be custom lowered, to meet ABI requirements
117 setOperationAction(ISD::RET, MVT::Other, Custom);
119 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
121 // Thread Local Storage
122 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
124 // Conversion of i64 -> double produces constantpool nodes
125 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
128 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
129 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
130 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
132 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
133 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
135 // Custom expand misaligned loads / stores.
136 setOperationAction(ISD::LOAD, MVT::i32, Custom);
137 setOperationAction(ISD::STORE, MVT::i32, Custom);
140 setOperationAction(ISD::VAEND, MVT::Other, Expand);
141 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
142 setOperationAction(ISD::VAARG, MVT::Other, Custom);
143 setOperationAction(ISD::VASTART, MVT::Other, Custom);
146 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
147 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
148 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
151 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
152 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
154 maxStoresPerMemset = 4;
155 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
157 // We have target-specific dag combine patterns for the following nodes:
158 setTargetDAGCombine(ISD::STORE);
161 SDValue XCoreTargetLowering::
162 LowerOperation(SDValue Op, SelectionDAG &DAG) {
163 switch (Op.getOpcode())
165 case ISD::CALL: return LowerCALL(Op, DAG);
166 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
167 case ISD::RET: return LowerRET(Op, DAG);
168 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
169 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
170 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
171 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
172 case ISD::LOAD: return LowerLOAD(Op, DAG);
173 case ISD::STORE: return LowerSTORE(Op, DAG);
174 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
175 case ISD::VAARG: return LowerVAARG(Op, DAG);
176 case ISD::VASTART: return LowerVASTART(Op, DAG);
177 // FIXME: Remove these when LegalizeDAGTypes lands.
179 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
180 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
182 llvm_unreachable("unimplemented operand");
187 /// ReplaceNodeResults - Replace the results of node with an illegal result
188 /// type with new values built out of custom code.
189 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
190 SmallVectorImpl<SDValue>&Results,
192 switch (N->getOpcode()) {
194 llvm_unreachable("Don't know how to custom expand this!");
198 Results.push_back(ExpandADDSUB(N, DAG));
203 /// getFunctionAlignment - Return the Log2 alignment of this function.
204 unsigned XCoreTargetLowering::
205 getFunctionAlignment(const Function *) const {
209 //===----------------------------------------------------------------------===//
210 // Misc Lower Operation implementation
211 //===----------------------------------------------------------------------===//
213 SDValue XCoreTargetLowering::
214 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
216 DebugLoc dl = Op.getDebugLoc();
217 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
218 Op.getOperand(3), Op.getOperand(4));
219 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
223 SDValue XCoreTargetLowering::
224 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
226 // FIXME there is no actual debug info here
227 DebugLoc dl = GA.getDebugLoc();
228 if (isa<Function>(GV)) {
229 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
230 } else if (!Subtarget.isXS1A()) {
231 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
233 // If GV is an alias then use the aliasee to determine constness
234 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
235 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
237 bool isConst = GVar && GVar->isConstant();
239 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
242 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
245 SDValue XCoreTargetLowering::
246 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
248 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
249 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
250 // If it's a debug information descriptor, don't mess with it.
251 if (DAG.isVerifiedDebugInfoDesc(Op))
253 return getGlobalAddressWrapper(GA, GV, DAG);
256 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
257 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
258 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
261 static inline bool isZeroLengthArray(const Type *Ty) {
262 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
263 return AT && (AT->getNumElements() == 0);
266 SDValue XCoreTargetLowering::
267 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
269 // FIXME there isn't really debug info here
270 DebugLoc dl = Op.getDebugLoc();
271 // transform to label + getid() * size
272 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
273 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
274 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
276 // If GV is an alias then use the aliasee to determine size
277 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
278 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
281 llvm_unreachable("Thread local object not a GlobalVariable?");
284 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
285 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
287 errs() << "Size of thread local object " << GVar->getName()
292 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
293 const TargetData *TD = TM.getTargetData();
294 unsigned Size = TD->getTypeAllocSize(Ty);
295 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
296 DAG.getConstant(Size, MVT::i32));
297 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
300 SDValue XCoreTargetLowering::
301 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
303 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
304 // FIXME there isn't really debug info here
305 DebugLoc dl = CP->getDebugLoc();
306 if (Subtarget.isXS1A()) {
307 llvm_unreachable("Lowering of constant pool unimplemented");
310 MVT PtrVT = Op.getValueType();
312 if (CP->isMachineConstantPoolEntry()) {
313 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
316 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
319 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
323 SDValue XCoreTargetLowering::
324 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
326 // FIXME there isn't really debug info here
327 DebugLoc dl = Op.getDebugLoc();
328 MVT PtrVT = Op.getValueType();
329 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
330 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
331 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
335 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
338 if (Addr.getOpcode() != ISD::ADD) {
341 ConstantSDNode *CN = 0;
342 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
345 int64_t off = CN->getSExtValue();
346 const SDValue &Base = Addr.getOperand(0);
347 const SDValue *Root = &Base;
348 if (Base.getOpcode() == ISD::ADD &&
349 Base.getOperand(1).getOpcode() == ISD::SHL) {
350 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
352 if (CN && (CN->getSExtValue() >= 2)) {
353 Root = &Base.getOperand(0);
356 if (isa<FrameIndexSDNode>(*Root)) {
357 // All frame indicies are word aligned
362 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
363 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
364 // All dp / cp relative addresses are word aligned
372 SDValue XCoreTargetLowering::
373 LowerLOAD(SDValue Op, SelectionDAG &DAG)
375 LoadSDNode *LD = cast<LoadSDNode>(Op);
376 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && "Unexpected extension type");
377 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load MVT");
378 if (allowsUnalignedMemoryAccesses()) {
381 unsigned ABIAlignment = getTargetData()->
382 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
383 // Leave aligned load alone.
384 if (LD->getAlignment() >= ABIAlignment) {
387 SDValue Chain = LD->getChain();
388 SDValue BasePtr = LD->getBasePtr();
389 DebugLoc dl = Op.getDebugLoc();
393 if (!LD->isVolatile() &&
394 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
395 if (Offset % 4 == 0) {
396 // We've managed to infer better alignment information than the load
397 // already has. Use an aligned load.
398 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
401 // ldw low, base[offset >> 2]
402 // ldw high, base[(offset >> 2) + 1]
403 // shr low_shifted, low, (offset & 0x3) * 8
404 // shl high_shifted, high, 32 - (offset & 0x3) * 8
405 // or result, low_shifted, high_shifted
406 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
407 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
408 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
409 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
411 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
412 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
414 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
416 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
418 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
419 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
420 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
421 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
423 SDValue Ops[] = { Result, Chain };
424 return DAG.getMergeValues(Ops, 2, dl);
427 if (LD->getAlignment() == 2) {
428 int SVOffset = LD->getSrcValueOffset();
429 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
430 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
431 LD->isVolatile(), 2);
432 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
433 DAG.getConstant(2, MVT::i32));
434 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
435 HighAddr, LD->getSrcValue(), SVOffset + 2,
436 MVT::i16, LD->isVolatile(), 2);
437 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
438 DAG.getConstant(16, MVT::i32));
439 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
440 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
442 SDValue Ops[] = { Result, Chain };
443 return DAG.getMergeValues(Ops, 2, dl);
446 // Lower to a call to __misaligned_load(BasePtr).
447 const Type *IntPtrTy = getTargetData()->getIntPtrType();
448 TargetLowering::ArgListTy Args;
449 TargetLowering::ArgListEntry Entry;
452 Entry.Node = BasePtr;
453 Args.push_back(Entry);
455 std::pair<SDValue, SDValue> CallResult =
456 LowerCallTo(Chain, IntPtrTy, false, false,
457 false, false, 0, CallingConv::C, false,
458 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
462 { CallResult.first, CallResult.second };
464 return DAG.getMergeValues(Ops, 2, dl);
467 SDValue XCoreTargetLowering::
468 LowerSTORE(SDValue Op, SelectionDAG &DAG)
470 StoreSDNode *ST = cast<StoreSDNode>(Op);
471 assert(!ST->isTruncatingStore() && "Unexpected store type");
472 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store MVT");
473 if (allowsUnalignedMemoryAccesses()) {
476 unsigned ABIAlignment = getTargetData()->
477 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
478 // Leave aligned store alone.
479 if (ST->getAlignment() >= ABIAlignment) {
482 SDValue Chain = ST->getChain();
483 SDValue BasePtr = ST->getBasePtr();
484 SDValue Value = ST->getValue();
485 DebugLoc dl = Op.getDebugLoc();
487 if (ST->getAlignment() == 2) {
488 int SVOffset = ST->getSrcValueOffset();
490 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
491 DAG.getConstant(16, MVT::i32));
492 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
493 ST->getSrcValue(), SVOffset, MVT::i16,
494 ST->isVolatile(), 2);
495 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
496 DAG.getConstant(2, MVT::i32));
497 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
498 ST->getSrcValue(), SVOffset + 2,
499 MVT::i16, ST->isVolatile(), 2);
500 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
503 // Lower to a call to __misaligned_store(BasePtr, Value).
504 const Type *IntPtrTy = getTargetData()->getIntPtrType();
505 TargetLowering::ArgListTy Args;
506 TargetLowering::ArgListEntry Entry;
509 Entry.Node = BasePtr;
510 Args.push_back(Entry);
513 Args.push_back(Entry);
515 std::pair<SDValue, SDValue> CallResult =
516 LowerCallTo(Chain, Type::VoidTy, false, false,
517 false, false, 0, CallingConv::C, false,
518 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
521 return CallResult.second;
524 SDValue XCoreTargetLowering::
525 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
527 assert(N->getValueType(0) == MVT::i64 &&
528 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
529 "Unknown operand to lower!");
530 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
531 DebugLoc dl = N->getDebugLoc();
533 // Extract components
534 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
535 N->getOperand(0), DAG.getConstant(0, MVT::i32));
536 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
537 N->getOperand(0), DAG.getConstant(1, MVT::i32));
538 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
539 N->getOperand(1), DAG.getConstant(0, MVT::i32));
540 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
541 N->getOperand(1), DAG.getConstant(1, MVT::i32));
544 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
546 SDValue Zero = DAG.getConstant(0, MVT::i32);
547 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
549 SDValue Lo(Carry.getNode(), 1);
551 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
553 SDValue Hi(Ignored.getNode(), 1);
555 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
558 SDValue XCoreTargetLowering::
559 LowerVAARG(SDValue Op, SelectionDAG &DAG)
561 llvm_unreachable("unimplemented");
562 // FIX Arguments passed by reference need a extra dereference.
563 SDNode *Node = Op.getNode();
564 DebugLoc dl = Node->getDebugLoc();
565 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
566 MVT VT = Node->getValueType(0);
567 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
568 Node->getOperand(1), V, 0);
569 // Increment the pointer, VAList, to the next vararg
570 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
571 DAG.getConstant(VT.getSizeInBits(),
573 // Store the incremented VAList to the legalized pointer
574 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
575 // Load the actual argument out of the pointer VAList
576 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
579 SDValue XCoreTargetLowering::
580 LowerVASTART(SDValue Op, SelectionDAG &DAG)
582 DebugLoc dl = Op.getDebugLoc();
583 // vastart stores the address of the VarArgsFrameIndex slot into the
584 // memory location argument
585 MachineFunction &MF = DAG.getMachineFunction();
586 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
587 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
588 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
589 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
592 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
593 DebugLoc dl = Op.getDebugLoc();
594 // Depths > 0 not supported yet!
595 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
598 MachineFunction &MF = DAG.getMachineFunction();
599 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
600 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
601 RegInfo->getFrameRegister(MF), MVT::i32);
604 //===----------------------------------------------------------------------===//
605 // Calling Convention Implementation
607 // The lower operations present on calling convention works on this order:
608 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
609 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
610 // LowerRET (virt regs --> phys regs)
611 // LowerCALL (phys regs --> virt regs)
613 //===----------------------------------------------------------------------===//
615 #include "XCoreGenCallingConv.inc"
617 //===----------------------------------------------------------------------===//
618 // CALL Calling Convention Implementation
619 //===----------------------------------------------------------------------===//
621 /// XCore custom CALL implementation
622 SDValue XCoreTargetLowering::
623 LowerCALL(SDValue Op, SelectionDAG &DAG)
625 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
626 unsigned CallingConv = TheCall->getCallingConv();
627 // For now, only CallingConv::C implemented
631 llvm_unreachable("Unsupported calling convention");
632 case CallingConv::Fast:
634 return LowerCCCCallTo(Op, DAG, CallingConv);
638 /// LowerCCCCallTo - functions arguments are copied from virtual
639 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
640 /// CALLSEQ_END are emitted.
641 /// TODO: isTailCall, sret.
642 SDValue XCoreTargetLowering::
643 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
645 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
646 SDValue Chain = TheCall->getChain();
647 SDValue Callee = TheCall->getCallee();
648 bool isVarArg = TheCall->isVarArg();
649 DebugLoc dl = Op.getDebugLoc();
651 // Analyze operands of the call, assigning locations to each operand.
652 SmallVector<CCValAssign, 16> ArgLocs;
653 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
655 // The ABI dictates there should be one stack slot available to the callee
656 // on function entry (for saving lr).
657 CCInfo.AllocateStack(4, 4);
659 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
661 // Get a count of how many bytes are to be pushed on the stack.
662 unsigned NumBytes = CCInfo.getNextStackOffset();
664 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
665 getPointerTy(), true));
667 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
668 SmallVector<SDValue, 12> MemOpChains;
670 // Walk the register/memloc assignments, inserting copies/loads.
671 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
672 CCValAssign &VA = ArgLocs[i];
674 // Arguments start after the 5 first operands of ISD::CALL
675 SDValue Arg = TheCall->getArg(i);
677 // Promote the value if needed.
678 switch (VA.getLocInfo()) {
679 default: llvm_unreachable("Unknown loc info!");
680 case CCValAssign::Full: break;
681 case CCValAssign::SExt:
682 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
684 case CCValAssign::ZExt:
685 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
687 case CCValAssign::AExt:
688 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
692 // Arguments that can be passed on register must be kept at
695 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
697 assert(VA.isMemLoc());
699 int Offset = VA.getLocMemOffset();
701 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
703 DAG.getConstant(Offset/4, MVT::i32)));
707 // Transform all store nodes into one single node because
708 // all store nodes are independent of each other.
709 if (!MemOpChains.empty())
710 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
711 &MemOpChains[0], MemOpChains.size());
713 // Build a sequence of copy-to-reg nodes chained together with token
714 // chain and flag operands which copy the outgoing args into registers.
715 // The InFlag in necessary since all emited instructions must be
718 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
719 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
720 RegsToPass[i].second, InFlag);
721 InFlag = Chain.getValue(1);
724 // If the callee is a GlobalAddress node (quite common, every direct call is)
725 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
726 // Likewise ExternalSymbol -> TargetExternalSymbol.
727 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
728 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
729 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
730 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
732 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
733 // = Chain, Callee, Reg#1, Reg#2, ...
735 // Returns a chain & a flag for retval copy to use.
736 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
737 SmallVector<SDValue, 8> Ops;
738 Ops.push_back(Chain);
739 Ops.push_back(Callee);
741 // Add argument registers to the end of the list so that they are
742 // known live into the call.
743 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
744 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
745 RegsToPass[i].second.getValueType()));
747 if (InFlag.getNode())
748 Ops.push_back(InFlag);
750 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
751 InFlag = Chain.getValue(1);
753 // Create the CALLSEQ_END node.
754 Chain = DAG.getCALLSEQ_END(Chain,
755 DAG.getConstant(NumBytes, getPointerTy(), true),
756 DAG.getConstant(0, getPointerTy(), true),
758 InFlag = Chain.getValue(1);
760 // Handle result values, copying them out of physregs into vregs that we
762 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
766 /// LowerCallResult - Lower the result values of an ISD::CALL into the
767 /// appropriate copies out of appropriate physical registers. This assumes that
768 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
769 /// being lowered. Returns a SDNode with the same number of values as the
771 SDNode *XCoreTargetLowering::
772 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
773 unsigned CallingConv, SelectionDAG &DAG) {
774 bool isVarArg = TheCall->isVarArg();
775 DebugLoc dl = TheCall->getDebugLoc();
777 // Assign locations to each value returned by this call.
778 SmallVector<CCValAssign, 16> RVLocs;
779 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
780 RVLocs, *DAG.getContext());
782 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
783 SmallVector<SDValue, 8> ResultVals;
785 // Copy all of the result registers out of their specified physreg.
786 for (unsigned i = 0; i != RVLocs.size(); ++i) {
787 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
788 RVLocs[i].getValVT(), InFlag).getValue(1);
789 InFlag = Chain.getValue(2);
790 ResultVals.push_back(Chain.getValue(0));
793 ResultVals.push_back(Chain);
795 // Merge everything together with a MERGE_VALUES node.
796 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
797 &ResultVals[0], ResultVals.size()).getNode();
800 //===----------------------------------------------------------------------===//
801 // FORMAL_ARGUMENTS Calling Convention Implementation
802 //===----------------------------------------------------------------------===//
804 /// XCore custom FORMAL_ARGUMENTS implementation
805 SDValue XCoreTargetLowering::
806 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
808 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
812 llvm_unreachable("Unsupported calling convention");
814 case CallingConv::Fast:
815 return LowerCCCArguments(Op, DAG);
819 /// LowerCCCArguments - transform physical registers into
820 /// virtual registers and generate load operations for
821 /// arguments places on the stack.
823 SDValue XCoreTargetLowering::
824 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
826 MachineFunction &MF = DAG.getMachineFunction();
827 MachineFrameInfo *MFI = MF.getFrameInfo();
828 MachineRegisterInfo &RegInfo = MF.getRegInfo();
829 SDValue Root = Op.getOperand(0);
830 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
831 unsigned CC = MF.getFunction()->getCallingConv();
832 DebugLoc dl = Op.getDebugLoc();
834 // Assign locations to all of the incoming arguments.
835 SmallVector<CCValAssign, 16> ArgLocs;
836 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
838 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
840 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
842 SmallVector<SDValue, 16> ArgValues;
844 unsigned LRSaveSize = StackSlotSize;
846 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
848 CCValAssign &VA = ArgLocs[i];
851 // Arguments passed in registers
852 MVT RegVT = VA.getLocVT();
853 switch (RegVT.getSimpleVT()) {
857 errs() << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
858 << RegVT.getSimpleVT() << "\n";
863 unsigned VReg = RegInfo.createVirtualRegister(
864 XCore::GRRegsRegisterClass);
865 RegInfo.addLiveIn(VA.getLocReg(), VReg);
866 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
870 assert(VA.isMemLoc());
871 // Load the argument to a virtual register
872 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
873 if (ObjSize > StackSlotSize) {
874 errs() << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
875 << VA.getLocVT().getSimpleVT()
878 // Create the frame index object for this incoming parameter...
879 int FI = MFI->CreateFixedObject(ObjSize,
880 LRSaveSize + VA.getLocMemOffset());
882 // Create the SelectionDAG nodes corresponding to a load
883 //from this parameter
884 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
885 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
890 /* Argument registers */
891 static const unsigned ArgRegs[] = {
892 XCore::R0, XCore::R1, XCore::R2, XCore::R3
894 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
895 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
896 array_lengthof(ArgRegs));
897 if (FirstVAReg < array_lengthof(ArgRegs)) {
898 SmallVector<SDValue, 4> MemOps;
900 // Save remaining registers, storing higher register numbers at a higher
902 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
903 // Create a stack slot
904 int FI = MFI->CreateFixedObject(4, offset);
905 if (i == FirstVAReg) {
906 XFI->setVarArgsFrameIndex(FI);
908 offset -= StackSlotSize;
909 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
910 // Move argument from phys reg -> virt reg
911 unsigned VReg = RegInfo.createVirtualRegister(
912 XCore::GRRegsRegisterClass);
913 RegInfo.addLiveIn(ArgRegs[i], VReg);
914 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
915 // Move argument from virt reg -> stack
916 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
917 MemOps.push_back(Store);
920 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
921 &MemOps[0], MemOps.size());
923 // This will point to the next argument passed via stack.
924 XFI->setVarArgsFrameIndex(
925 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
929 ArgValues.push_back(Root);
931 // Return the new list of results.
932 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
933 Op.getNode()->value_end());
934 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
935 &ArgValues[0], ArgValues.size());
938 //===----------------------------------------------------------------------===//
939 // Return Value Calling Convention Implementation
940 //===----------------------------------------------------------------------===//
942 SDValue XCoreTargetLowering::
943 LowerRET(SDValue Op, SelectionDAG &DAG)
945 // CCValAssign - represent the assignment of
946 // the return value to a location
947 SmallVector<CCValAssign, 16> RVLocs;
948 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
949 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
950 DebugLoc dl = Op.getDebugLoc();
952 // CCState - Info about the registers and stack slot.
953 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, *DAG.getContext());
955 // Analize return values of ISD::RET
956 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
958 // If this is the first return lowered for this function, add
959 // the regs to the liveout set for the function.
960 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
961 for (unsigned i = 0; i != RVLocs.size(); ++i)
962 if (RVLocs[i].isRegLoc())
963 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
966 // The chain is always operand #0
967 SDValue Chain = Op.getOperand(0);
970 // Copy the result values into the output registers.
971 for (unsigned i = 0; i != RVLocs.size(); ++i) {
972 CCValAssign &VA = RVLocs[i];
973 assert(VA.isRegLoc() && "Can only return in registers!");
975 // ISD::RET => ret chain, (regnum1,val1), ...
976 // So i*2+1 index only the regnums
977 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
978 Op.getOperand(i*2+1), Flag);
980 // guarantee that all emitted copies are
981 // stuck together, avoiding something bad
982 Flag = Chain.getValue(1);
985 // Return on XCore is always a "retsp 0"
987 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
988 Chain, DAG.getConstant(0, MVT::i32), Flag);
990 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
991 Chain, DAG.getConstant(0, MVT::i32));
994 //===----------------------------------------------------------------------===//
995 // Other Lowering Code
996 //===----------------------------------------------------------------------===//
999 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1000 MachineBasicBlock *BB) const {
1001 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1002 DebugLoc dl = MI->getDebugLoc();
1003 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1004 "Unexpected instr type to insert");
1006 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1007 // control-flow pattern. The incoming instruction knows the destination vreg
1008 // to set, the condition code register to branch on, the true/false values to
1009 // select between, and a branch opcode to use.
1010 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1011 MachineFunction::iterator It = BB;
1017 // cmpTY ccX, r1, r2
1019 // fallthrough --> copy0MBB
1020 MachineBasicBlock *thisMBB = BB;
1021 MachineFunction *F = BB->getParent();
1022 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1023 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1024 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1025 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1026 F->insert(It, copy0MBB);
1027 F->insert(It, sinkMBB);
1028 // Update machine-CFG edges by transferring all successors of the current
1029 // block to the new block which will contain the Phi node for the select.
1030 sinkMBB->transferSuccessors(BB);
1031 // Next, add the true and fallthrough blocks as its successors.
1032 BB->addSuccessor(copy0MBB);
1033 BB->addSuccessor(sinkMBB);
1036 // %FalseValue = ...
1037 // # fallthrough to sinkMBB
1040 // Update machine-CFG edges
1041 BB->addSuccessor(sinkMBB);
1044 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1047 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1048 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1049 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1051 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1055 //===----------------------------------------------------------------------===//
1056 // Target Optimization Hooks
1057 //===----------------------------------------------------------------------===//
1059 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1060 DAGCombinerInfo &DCI) const {
1061 SelectionDAG &DAG = DCI.DAG;
1062 DebugLoc dl = N->getDebugLoc();
1063 switch (N->getOpcode()) {
1066 // Replace unaligned store of unaligned load with memmove.
1067 StoreSDNode *ST = cast<StoreSDNode>(N);
1068 if (!DCI.isBeforeLegalize() || allowsUnalignedMemoryAccesses() ||
1069 ST->isVolatile() || ST->isIndexed()) {
1072 SDValue Chain = ST->getChain();
1074 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1075 if (StoreBits % 8) {
1078 unsigned ABIAlignment = getTargetData()->
1079 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1080 unsigned Alignment = ST->getAlignment();
1081 if (Alignment >= ABIAlignment) {
1085 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1086 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1087 LD->getAlignment() == Alignment &&
1088 !LD->isVolatile() && !LD->isIndexed() &&
1089 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1090 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1092 DAG.getConstant(StoreBits/8, MVT::i32),
1093 Alignment, ST->getSrcValue(),
1094 ST->getSrcValueOffset(), LD->getSrcValue(),
1095 LD->getSrcValueOffset());
1104 //===----------------------------------------------------------------------===//
1105 // Addressing mode description hooks
1106 //===----------------------------------------------------------------------===//
1108 static inline bool isImmUs(int64_t val)
1110 return (val >= 0 && val <= 11);
1113 static inline bool isImmUs2(int64_t val)
1115 return (val%2 == 0 && isImmUs(val/2));
1118 static inline bool isImmUs4(int64_t val)
1120 return (val%4 == 0 && isImmUs(val/4));
1123 /// isLegalAddressingMode - Return true if the addressing mode represented
1124 /// by AM is legal for this target, for a load/store of the specified type.
1126 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1127 const Type *Ty) const {
1128 // Be conservative with void
1129 // FIXME: Can we be more aggressive?
1130 if (Ty->getTypeID() == Type::VoidTyID)
1133 const TargetData *TD = TM.getTargetData();
1134 unsigned Size = TD->getTypeAllocSize(Ty);
1136 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1143 if (AM.Scale == 0) {
1144 return isImmUs(AM.BaseOffs);
1147 return AM.Scale == 1 && AM.BaseOffs == 0;
1151 if (AM.Scale == 0) {
1152 return isImmUs2(AM.BaseOffs);
1155 return AM.Scale == 2 && AM.BaseOffs == 0;
1158 if (AM.Scale == 0) {
1159 return isImmUs4(AM.BaseOffs);
1162 return AM.Scale == 4 && AM.BaseOffs == 0;
1168 //===----------------------------------------------------------------------===//
1169 // XCore Inline Assembly Support
1170 //===----------------------------------------------------------------------===//
1172 std::vector<unsigned> XCoreTargetLowering::
1173 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1176 if (Constraint.size() != 1)
1177 return std::vector<unsigned>();
1179 switch (Constraint[0]) {
1182 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1183 XCore::R3, XCore::R4, XCore::R5,
1184 XCore::R6, XCore::R7, XCore::R8,
1185 XCore::R9, XCore::R10, XCore::R11, 0);
1188 return std::vector<unsigned>();