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)
60 new XCoreTargetObjectFile(XTM.getSubtargetImpl()->isXS1A())),
62 Subtarget(*XTM.getSubtargetImpl()) {
64 // Set up the register classes.
65 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
67 // Compute derived properties from the register classes
68 computeRegisterProperties();
70 // Division is expensive
71 setIntDivIsCheap(false);
73 setShiftAmountType(MVT::i32);
74 setStackPointerRegisterToSaveRestore(XCore::SP);
76 setSchedulingPreference(SchedulingForRegPressure);
78 // Use i32 for setcc operations results (slt, sgt, ...).
79 setBooleanContents(ZeroOrOneBooleanContent);
81 // XCore does not have the NodeTypes below.
82 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
83 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
84 setOperationAction(ISD::ADDC, MVT::i32, Expand);
85 setOperationAction(ISD::ADDE, MVT::i32, Expand);
86 setOperationAction(ISD::SUBC, MVT::i32, Expand);
87 setOperationAction(ISD::SUBE, MVT::i32, Expand);
89 // Stop the combiner recombining select and set_cc
90 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
93 if (!Subtarget.isXS1A()) {
94 setOperationAction(ISD::ADD, MVT::i64, Custom);
95 setOperationAction(ISD::SUB, MVT::i64, Custom);
97 if (Subtarget.isXS1A()) {
98 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
100 setOperationAction(ISD::MULHS, MVT::i32, Expand);
101 setOperationAction(ISD::MULHU, MVT::i32, Expand);
102 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
103 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
104 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
108 setOperationAction(ISD::ROTL , MVT::i32, Expand);
109 setOperationAction(ISD::ROTR , MVT::i32, Expand);
111 setOperationAction(ISD::TRAP, MVT::Other, Legal);
113 // Expand jump tables for now
114 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
115 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
117 // RET must be custom lowered, to meet ABI requirements
118 setOperationAction(ISD::RET, MVT::Other, Custom);
120 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
122 // Thread Local Storage
123 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
125 // Conversion of i64 -> double produces constantpool nodes
126 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
129 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
130 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
131 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
134 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
136 // Custom expand misaligned loads / stores.
137 setOperationAction(ISD::LOAD, MVT::i32, Custom);
138 setOperationAction(ISD::STORE, MVT::i32, Custom);
141 setOperationAction(ISD::VAEND, MVT::Other, Expand);
142 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
143 setOperationAction(ISD::VAARG, MVT::Other, Custom);
144 setOperationAction(ISD::VASTART, MVT::Other, Custom);
147 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
148 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
149 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
152 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
153 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
155 maxStoresPerMemset = 4;
156 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
158 // We have target-specific dag combine patterns for the following nodes:
159 setTargetDAGCombine(ISD::STORE);
162 SDValue XCoreTargetLowering::
163 LowerOperation(SDValue Op, SelectionDAG &DAG) {
164 switch (Op.getOpcode())
166 case ISD::CALL: return LowerCALL(Op, DAG);
167 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
168 case ISD::RET: return LowerRET(Op, DAG);
169 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
170 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
171 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
172 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
173 case ISD::LOAD: return LowerLOAD(Op, DAG);
174 case ISD::STORE: return LowerSTORE(Op, DAG);
175 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
176 case ISD::VAARG: return LowerVAARG(Op, DAG);
177 case ISD::VASTART: return LowerVASTART(Op, DAG);
178 // FIXME: Remove these when LegalizeDAGTypes lands.
180 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
181 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
183 llvm_unreachable("unimplemented operand");
188 /// ReplaceNodeResults - Replace the results of node with an illegal result
189 /// type with new values built out of custom code.
190 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
191 SmallVectorImpl<SDValue>&Results,
193 switch (N->getOpcode()) {
195 llvm_unreachable("Don't know how to custom expand this!");
199 Results.push_back(ExpandADDSUB(N, DAG));
204 /// getFunctionAlignment - Return the Log2 alignment of this function.
205 unsigned XCoreTargetLowering::
206 getFunctionAlignment(const Function *) const {
210 //===----------------------------------------------------------------------===//
211 // Misc Lower Operation implementation
212 //===----------------------------------------------------------------------===//
214 SDValue XCoreTargetLowering::
215 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
217 DebugLoc dl = Op.getDebugLoc();
218 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
219 Op.getOperand(3), Op.getOperand(4));
220 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
224 SDValue XCoreTargetLowering::
225 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
227 // FIXME there is no actual debug info here
228 DebugLoc dl = GA.getDebugLoc();
229 if (isa<Function>(GV)) {
230 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
231 } else if (!Subtarget.isXS1A()) {
232 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
234 // If GV is an alias then use the aliasee to determine constness
235 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
236 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
238 bool isConst = GVar && GVar->isConstant();
240 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
243 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
246 SDValue XCoreTargetLowering::
247 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
249 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
250 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
251 // If it's a debug information descriptor, don't mess with it.
252 if (DAG.isVerifiedDebugInfoDesc(Op))
254 return getGlobalAddressWrapper(GA, GV, DAG);
257 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
258 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
259 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
262 static inline bool isZeroLengthArray(const Type *Ty) {
263 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
264 return AT && (AT->getNumElements() == 0);
267 SDValue XCoreTargetLowering::
268 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
270 // FIXME there isn't really debug info here
271 DebugLoc dl = Op.getDebugLoc();
272 // transform to label + getid() * size
273 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
274 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
275 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
277 // If GV is an alias then use the aliasee to determine size
278 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
279 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
282 llvm_unreachable("Thread local object not a GlobalVariable?");
285 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
286 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
288 errs() << "Size of thread local object " << GVar->getName()
293 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
294 const TargetData *TD = TM.getTargetData();
295 unsigned Size = TD->getTypeAllocSize(Ty);
296 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
297 DAG.getConstant(Size, MVT::i32));
298 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
301 SDValue XCoreTargetLowering::
302 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
304 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
305 // FIXME there isn't really debug info here
306 DebugLoc dl = CP->getDebugLoc();
307 if (Subtarget.isXS1A()) {
308 llvm_unreachable("Lowering of constant pool unimplemented");
311 MVT PtrVT = Op.getValueType();
313 if (CP->isMachineConstantPoolEntry()) {
314 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
317 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
320 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
324 SDValue XCoreTargetLowering::
325 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
327 // FIXME there isn't really debug info here
328 DebugLoc dl = Op.getDebugLoc();
329 MVT PtrVT = Op.getValueType();
330 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
331 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
332 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
336 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
339 if (Addr.getOpcode() != ISD::ADD) {
342 ConstantSDNode *CN = 0;
343 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
346 int64_t off = CN->getSExtValue();
347 const SDValue &Base = Addr.getOperand(0);
348 const SDValue *Root = &Base;
349 if (Base.getOpcode() == ISD::ADD &&
350 Base.getOperand(1).getOpcode() == ISD::SHL) {
351 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
353 if (CN && (CN->getSExtValue() >= 2)) {
354 Root = &Base.getOperand(0);
357 if (isa<FrameIndexSDNode>(*Root)) {
358 // All frame indicies are word aligned
363 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
364 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
365 // All dp / cp relative addresses are word aligned
373 SDValue XCoreTargetLowering::
374 LowerLOAD(SDValue Op, SelectionDAG &DAG)
376 LoadSDNode *LD = cast<LoadSDNode>(Op);
377 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && "Unexpected extension type");
378 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load MVT");
379 if (allowsUnalignedMemoryAccesses()) {
382 unsigned ABIAlignment = getTargetData()->
383 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
384 // Leave aligned load alone.
385 if (LD->getAlignment() >= ABIAlignment) {
388 SDValue Chain = LD->getChain();
389 SDValue BasePtr = LD->getBasePtr();
390 DebugLoc dl = Op.getDebugLoc();
394 if (!LD->isVolatile() &&
395 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
396 if (Offset % 4 == 0) {
397 // We've managed to infer better alignment information than the load
398 // already has. Use an aligned load.
399 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
402 // ldw low, base[offset >> 2]
403 // ldw high, base[(offset >> 2) + 1]
404 // shr low_shifted, low, (offset & 0x3) * 8
405 // shl high_shifted, high, 32 - (offset & 0x3) * 8
406 // or result, low_shifted, high_shifted
407 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
408 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
409 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
410 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
412 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
413 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
415 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
417 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
419 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
420 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
421 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
422 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
424 SDValue Ops[] = { Result, Chain };
425 return DAG.getMergeValues(Ops, 2, dl);
428 if (LD->getAlignment() == 2) {
429 int SVOffset = LD->getSrcValueOffset();
430 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
431 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
432 LD->isVolatile(), 2);
433 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
434 DAG.getConstant(2, MVT::i32));
435 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
436 HighAddr, LD->getSrcValue(), SVOffset + 2,
437 MVT::i16, LD->isVolatile(), 2);
438 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
439 DAG.getConstant(16, MVT::i32));
440 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
441 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
443 SDValue Ops[] = { Result, Chain };
444 return DAG.getMergeValues(Ops, 2, dl);
447 // Lower to a call to __misaligned_load(BasePtr).
448 const Type *IntPtrTy = getTargetData()->getIntPtrType();
449 TargetLowering::ArgListTy Args;
450 TargetLowering::ArgListEntry Entry;
453 Entry.Node = BasePtr;
454 Args.push_back(Entry);
456 std::pair<SDValue, SDValue> CallResult =
457 LowerCallTo(Chain, IntPtrTy, false, false,
458 false, false, 0, CallingConv::C, false,
459 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
463 { CallResult.first, CallResult.second };
465 return DAG.getMergeValues(Ops, 2, dl);
468 SDValue XCoreTargetLowering::
469 LowerSTORE(SDValue Op, SelectionDAG &DAG)
471 StoreSDNode *ST = cast<StoreSDNode>(Op);
472 assert(!ST->isTruncatingStore() && "Unexpected store type");
473 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store MVT");
474 if (allowsUnalignedMemoryAccesses()) {
477 unsigned ABIAlignment = getTargetData()->
478 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
479 // Leave aligned store alone.
480 if (ST->getAlignment() >= ABIAlignment) {
483 SDValue Chain = ST->getChain();
484 SDValue BasePtr = ST->getBasePtr();
485 SDValue Value = ST->getValue();
486 DebugLoc dl = Op.getDebugLoc();
488 if (ST->getAlignment() == 2) {
489 int SVOffset = ST->getSrcValueOffset();
491 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
492 DAG.getConstant(16, MVT::i32));
493 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
494 ST->getSrcValue(), SVOffset, MVT::i16,
495 ST->isVolatile(), 2);
496 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
497 DAG.getConstant(2, MVT::i32));
498 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
499 ST->getSrcValue(), SVOffset + 2,
500 MVT::i16, ST->isVolatile(), 2);
501 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
504 // Lower to a call to __misaligned_store(BasePtr, Value).
505 const Type *IntPtrTy = getTargetData()->getIntPtrType();
506 TargetLowering::ArgListTy Args;
507 TargetLowering::ArgListEntry Entry;
510 Entry.Node = BasePtr;
511 Args.push_back(Entry);
514 Args.push_back(Entry);
516 std::pair<SDValue, SDValue> CallResult =
517 LowerCallTo(Chain, Type::VoidTy, false, false,
518 false, false, 0, CallingConv::C, false,
519 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
522 return CallResult.second;
525 SDValue XCoreTargetLowering::
526 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
528 assert(N->getValueType(0) == MVT::i64 &&
529 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
530 "Unknown operand to lower!");
531 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
532 DebugLoc dl = N->getDebugLoc();
534 // Extract components
535 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
536 N->getOperand(0), DAG.getConstant(0, MVT::i32));
537 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
538 N->getOperand(0), DAG.getConstant(1, MVT::i32));
539 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
540 N->getOperand(1), DAG.getConstant(0, MVT::i32));
541 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
542 N->getOperand(1), DAG.getConstant(1, MVT::i32));
545 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
547 SDValue Zero = DAG.getConstant(0, MVT::i32);
548 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
550 SDValue Lo(Carry.getNode(), 1);
552 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
554 SDValue Hi(Ignored.getNode(), 1);
556 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
559 SDValue XCoreTargetLowering::
560 LowerVAARG(SDValue Op, SelectionDAG &DAG)
562 llvm_unreachable("unimplemented");
563 // FIX Arguments passed by reference need a extra dereference.
564 SDNode *Node = Op.getNode();
565 DebugLoc dl = Node->getDebugLoc();
566 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
567 MVT VT = Node->getValueType(0);
568 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
569 Node->getOperand(1), V, 0);
570 // Increment the pointer, VAList, to the next vararg
571 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
572 DAG.getConstant(VT.getSizeInBits(),
574 // Store the incremented VAList to the legalized pointer
575 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
576 // Load the actual argument out of the pointer VAList
577 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
580 SDValue XCoreTargetLowering::
581 LowerVASTART(SDValue Op, SelectionDAG &DAG)
583 DebugLoc dl = Op.getDebugLoc();
584 // vastart stores the address of the VarArgsFrameIndex slot into the
585 // memory location argument
586 MachineFunction &MF = DAG.getMachineFunction();
587 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
588 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
589 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
590 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
593 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
594 DebugLoc dl = Op.getDebugLoc();
595 // Depths > 0 not supported yet!
596 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
599 MachineFunction &MF = DAG.getMachineFunction();
600 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
601 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
602 RegInfo->getFrameRegister(MF), MVT::i32);
605 //===----------------------------------------------------------------------===//
606 // Calling Convention Implementation
608 // The lower operations present on calling convention works on this order:
609 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
610 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
611 // LowerRET (virt regs --> phys regs)
612 // LowerCALL (phys regs --> virt regs)
614 //===----------------------------------------------------------------------===//
616 #include "XCoreGenCallingConv.inc"
618 //===----------------------------------------------------------------------===//
619 // CALL Calling Convention Implementation
620 //===----------------------------------------------------------------------===//
622 /// XCore custom CALL implementation
623 SDValue XCoreTargetLowering::
624 LowerCALL(SDValue Op, SelectionDAG &DAG)
626 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
627 unsigned CallingConv = TheCall->getCallingConv();
628 // For now, only CallingConv::C implemented
632 llvm_unreachable("Unsupported calling convention");
633 case CallingConv::Fast:
635 return LowerCCCCallTo(Op, DAG, CallingConv);
639 /// LowerCCCCallTo - functions arguments are copied from virtual
640 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
641 /// CALLSEQ_END are emitted.
642 /// TODO: isTailCall, sret.
643 SDValue XCoreTargetLowering::
644 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
646 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
647 SDValue Chain = TheCall->getChain();
648 SDValue Callee = TheCall->getCallee();
649 bool isVarArg = TheCall->isVarArg();
650 DebugLoc dl = Op.getDebugLoc();
652 // Analyze operands of the call, assigning locations to each operand.
653 SmallVector<CCValAssign, 16> ArgLocs;
654 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
656 // The ABI dictates there should be one stack slot available to the callee
657 // on function entry (for saving lr).
658 CCInfo.AllocateStack(4, 4);
660 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
662 // Get a count of how many bytes are to be pushed on the stack.
663 unsigned NumBytes = CCInfo.getNextStackOffset();
665 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
666 getPointerTy(), true));
668 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
669 SmallVector<SDValue, 12> MemOpChains;
671 // Walk the register/memloc assignments, inserting copies/loads.
672 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
673 CCValAssign &VA = ArgLocs[i];
675 // Arguments start after the 5 first operands of ISD::CALL
676 SDValue Arg = TheCall->getArg(i);
678 // Promote the value if needed.
679 switch (VA.getLocInfo()) {
680 default: llvm_unreachable("Unknown loc info!");
681 case CCValAssign::Full: break;
682 case CCValAssign::SExt:
683 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
685 case CCValAssign::ZExt:
686 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
688 case CCValAssign::AExt:
689 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
693 // Arguments that can be passed on register must be kept at
696 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
698 assert(VA.isMemLoc());
700 int Offset = VA.getLocMemOffset();
702 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
704 DAG.getConstant(Offset/4, MVT::i32)));
708 // Transform all store nodes into one single node because
709 // all store nodes are independent of each other.
710 if (!MemOpChains.empty())
711 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
712 &MemOpChains[0], MemOpChains.size());
714 // Build a sequence of copy-to-reg nodes chained together with token
715 // chain and flag operands which copy the outgoing args into registers.
716 // The InFlag in necessary since all emited instructions must be
719 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
720 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
721 RegsToPass[i].second, InFlag);
722 InFlag = Chain.getValue(1);
725 // If the callee is a GlobalAddress node (quite common, every direct call is)
726 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
727 // Likewise ExternalSymbol -> TargetExternalSymbol.
728 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
729 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
730 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
731 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
733 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
734 // = Chain, Callee, Reg#1, Reg#2, ...
736 // Returns a chain & a flag for retval copy to use.
737 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
738 SmallVector<SDValue, 8> Ops;
739 Ops.push_back(Chain);
740 Ops.push_back(Callee);
742 // Add argument registers to the end of the list so that they are
743 // known live into the call.
744 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
745 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
746 RegsToPass[i].second.getValueType()));
748 if (InFlag.getNode())
749 Ops.push_back(InFlag);
751 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
752 InFlag = Chain.getValue(1);
754 // Create the CALLSEQ_END node.
755 Chain = DAG.getCALLSEQ_END(Chain,
756 DAG.getConstant(NumBytes, getPointerTy(), true),
757 DAG.getConstant(0, getPointerTy(), true),
759 InFlag = Chain.getValue(1);
761 // Handle result values, copying them out of physregs into vregs that we
763 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
767 /// LowerCallResult - Lower the result values of an ISD::CALL into the
768 /// appropriate copies out of appropriate physical registers. This assumes that
769 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
770 /// being lowered. Returns a SDNode with the same number of values as the
772 SDNode *XCoreTargetLowering::
773 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
774 unsigned CallingConv, SelectionDAG &DAG) {
775 bool isVarArg = TheCall->isVarArg();
776 DebugLoc dl = TheCall->getDebugLoc();
778 // Assign locations to each value returned by this call.
779 SmallVector<CCValAssign, 16> RVLocs;
780 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
781 RVLocs, *DAG.getContext());
783 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
784 SmallVector<SDValue, 8> ResultVals;
786 // Copy all of the result registers out of their specified physreg.
787 for (unsigned i = 0; i != RVLocs.size(); ++i) {
788 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
789 RVLocs[i].getValVT(), InFlag).getValue(1);
790 InFlag = Chain.getValue(2);
791 ResultVals.push_back(Chain.getValue(0));
794 ResultVals.push_back(Chain);
796 // Merge everything together with a MERGE_VALUES node.
797 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
798 &ResultVals[0], ResultVals.size()).getNode();
801 //===----------------------------------------------------------------------===//
802 // FORMAL_ARGUMENTS Calling Convention Implementation
803 //===----------------------------------------------------------------------===//
805 /// XCore custom FORMAL_ARGUMENTS implementation
806 SDValue XCoreTargetLowering::
807 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
809 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
813 llvm_unreachable("Unsupported calling convention");
815 case CallingConv::Fast:
816 return LowerCCCArguments(Op, DAG);
820 /// LowerCCCArguments - transform physical registers into
821 /// virtual registers and generate load operations for
822 /// arguments places on the stack.
824 SDValue XCoreTargetLowering::
825 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
827 MachineFunction &MF = DAG.getMachineFunction();
828 MachineFrameInfo *MFI = MF.getFrameInfo();
829 MachineRegisterInfo &RegInfo = MF.getRegInfo();
830 SDValue Root = Op.getOperand(0);
831 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
832 unsigned CC = MF.getFunction()->getCallingConv();
833 DebugLoc dl = Op.getDebugLoc();
835 // Assign locations to all of the incoming arguments.
836 SmallVector<CCValAssign, 16> ArgLocs;
837 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
839 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
841 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
843 SmallVector<SDValue, 16> ArgValues;
845 unsigned LRSaveSize = StackSlotSize;
847 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
849 CCValAssign &VA = ArgLocs[i];
852 // Arguments passed in registers
853 MVT RegVT = VA.getLocVT();
854 switch (RegVT.getSimpleVT()) {
858 errs() << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
859 << RegVT.getSimpleVT() << "\n";
864 unsigned VReg = RegInfo.createVirtualRegister(
865 XCore::GRRegsRegisterClass);
866 RegInfo.addLiveIn(VA.getLocReg(), VReg);
867 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
871 assert(VA.isMemLoc());
872 // Load the argument to a virtual register
873 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
874 if (ObjSize > StackSlotSize) {
875 errs() << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
876 << VA.getLocVT().getSimpleVT()
879 // Create the frame index object for this incoming parameter...
880 int FI = MFI->CreateFixedObject(ObjSize,
881 LRSaveSize + VA.getLocMemOffset());
883 // Create the SelectionDAG nodes corresponding to a load
884 //from this parameter
885 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
886 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
891 /* Argument registers */
892 static const unsigned ArgRegs[] = {
893 XCore::R0, XCore::R1, XCore::R2, XCore::R3
895 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
896 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
897 array_lengthof(ArgRegs));
898 if (FirstVAReg < array_lengthof(ArgRegs)) {
899 SmallVector<SDValue, 4> MemOps;
901 // Save remaining registers, storing higher register numbers at a higher
903 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
904 // Create a stack slot
905 int FI = MFI->CreateFixedObject(4, offset);
906 if (i == FirstVAReg) {
907 XFI->setVarArgsFrameIndex(FI);
909 offset -= StackSlotSize;
910 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
911 // Move argument from phys reg -> virt reg
912 unsigned VReg = RegInfo.createVirtualRegister(
913 XCore::GRRegsRegisterClass);
914 RegInfo.addLiveIn(ArgRegs[i], VReg);
915 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
916 // Move argument from virt reg -> stack
917 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
918 MemOps.push_back(Store);
921 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
922 &MemOps[0], MemOps.size());
924 // This will point to the next argument passed via stack.
925 XFI->setVarArgsFrameIndex(
926 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
930 ArgValues.push_back(Root);
932 // Return the new list of results.
933 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
934 Op.getNode()->value_end());
935 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
936 &ArgValues[0], ArgValues.size());
939 //===----------------------------------------------------------------------===//
940 // Return Value Calling Convention Implementation
941 //===----------------------------------------------------------------------===//
943 SDValue XCoreTargetLowering::
944 LowerRET(SDValue Op, SelectionDAG &DAG)
946 // CCValAssign - represent the assignment of
947 // the return value to a location
948 SmallVector<CCValAssign, 16> RVLocs;
949 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
950 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
951 DebugLoc dl = Op.getDebugLoc();
953 // CCState - Info about the registers and stack slot.
954 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, *DAG.getContext());
956 // Analize return values of ISD::RET
957 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
959 // If this is the first return lowered for this function, add
960 // the regs to the liveout set for the function.
961 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
962 for (unsigned i = 0; i != RVLocs.size(); ++i)
963 if (RVLocs[i].isRegLoc())
964 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
967 // The chain is always operand #0
968 SDValue Chain = Op.getOperand(0);
971 // Copy the result values into the output registers.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 CCValAssign &VA = RVLocs[i];
974 assert(VA.isRegLoc() && "Can only return in registers!");
976 // ISD::RET => ret chain, (regnum1,val1), ...
977 // So i*2+1 index only the regnums
978 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
979 Op.getOperand(i*2+1), Flag);
981 // guarantee that all emitted copies are
982 // stuck together, avoiding something bad
983 Flag = Chain.getValue(1);
986 // Return on XCore is always a "retsp 0"
988 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
989 Chain, DAG.getConstant(0, MVT::i32), Flag);
991 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
992 Chain, DAG.getConstant(0, MVT::i32));
995 //===----------------------------------------------------------------------===//
996 // Other Lowering Code
997 //===----------------------------------------------------------------------===//
1000 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1001 MachineBasicBlock *BB) const {
1002 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1003 DebugLoc dl = MI->getDebugLoc();
1004 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1005 "Unexpected instr type to insert");
1007 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1008 // control-flow pattern. The incoming instruction knows the destination vreg
1009 // to set, the condition code register to branch on, the true/false values to
1010 // select between, and a branch opcode to use.
1011 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1012 MachineFunction::iterator It = BB;
1018 // cmpTY ccX, r1, r2
1020 // fallthrough --> copy0MBB
1021 MachineBasicBlock *thisMBB = BB;
1022 MachineFunction *F = BB->getParent();
1023 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1024 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1025 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1026 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1027 F->insert(It, copy0MBB);
1028 F->insert(It, sinkMBB);
1029 // Update machine-CFG edges by transferring all successors of the current
1030 // block to the new block which will contain the Phi node for the select.
1031 sinkMBB->transferSuccessors(BB);
1032 // Next, add the true and fallthrough blocks as its successors.
1033 BB->addSuccessor(copy0MBB);
1034 BB->addSuccessor(sinkMBB);
1037 // %FalseValue = ...
1038 // # fallthrough to sinkMBB
1041 // Update machine-CFG edges
1042 BB->addSuccessor(sinkMBB);
1045 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1048 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1049 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1050 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1052 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1056 //===----------------------------------------------------------------------===//
1057 // Target Optimization Hooks
1058 //===----------------------------------------------------------------------===//
1060 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1061 DAGCombinerInfo &DCI) const {
1062 SelectionDAG &DAG = DCI.DAG;
1063 DebugLoc dl = N->getDebugLoc();
1064 switch (N->getOpcode()) {
1067 // Replace unaligned store of unaligned load with memmove.
1068 StoreSDNode *ST = cast<StoreSDNode>(N);
1069 if (!DCI.isBeforeLegalize() || allowsUnalignedMemoryAccesses() ||
1070 ST->isVolatile() || ST->isIndexed()) {
1073 SDValue Chain = ST->getChain();
1075 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1076 if (StoreBits % 8) {
1079 unsigned ABIAlignment = getTargetData()->
1080 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1081 unsigned Alignment = ST->getAlignment();
1082 if (Alignment >= ABIAlignment) {
1086 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1087 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1088 LD->getAlignment() == Alignment &&
1089 !LD->isVolatile() && !LD->isIndexed() &&
1090 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1091 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1093 DAG.getConstant(StoreBits/8, MVT::i32),
1094 Alignment, ST->getSrcValue(),
1095 ST->getSrcValueOffset(), LD->getSrcValue(),
1096 LD->getSrcValueOffset());
1105 //===----------------------------------------------------------------------===//
1106 // Addressing mode description hooks
1107 //===----------------------------------------------------------------------===//
1109 static inline bool isImmUs(int64_t val)
1111 return (val >= 0 && val <= 11);
1114 static inline bool isImmUs2(int64_t val)
1116 return (val%2 == 0 && isImmUs(val/2));
1119 static inline bool isImmUs4(int64_t val)
1121 return (val%4 == 0 && isImmUs(val/4));
1124 /// isLegalAddressingMode - Return true if the addressing mode represented
1125 /// by AM is legal for this target, for a load/store of the specified type.
1127 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1128 const Type *Ty) const {
1129 // Be conservative with void
1130 // FIXME: Can we be more aggressive?
1131 if (Ty->getTypeID() == Type::VoidTyID)
1134 const TargetData *TD = TM.getTargetData();
1135 unsigned Size = TD->getTypeAllocSize(Ty);
1137 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1144 if (AM.Scale == 0) {
1145 return isImmUs(AM.BaseOffs);
1148 return AM.Scale == 1 && AM.BaseOffs == 0;
1152 if (AM.Scale == 0) {
1153 return isImmUs2(AM.BaseOffs);
1156 return AM.Scale == 2 && AM.BaseOffs == 0;
1159 if (AM.Scale == 0) {
1160 return isImmUs4(AM.BaseOffs);
1163 return AM.Scale == 4 && AM.BaseOffs == 0;
1169 //===----------------------------------------------------------------------===//
1170 // XCore Inline Assembly Support
1171 //===----------------------------------------------------------------------===//
1173 std::vector<unsigned> XCoreTargetLowering::
1174 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1177 if (Constraint.size() != 1)
1178 return std::vector<unsigned>();
1180 switch (Constraint[0]) {
1183 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1184 XCore::R3, XCore::R4, XCore::R5,
1185 XCore::R6, XCore::R7, XCore::R8,
1186 XCore::R9, XCore::R10, XCore::R11, 0);
1189 return std::vector<unsigned>();