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 case XCoreISD::LADD : return "XCoreISD::LADD";
55 case XCoreISD::LSUB : return "XCoreISD::LSUB";
56 default : return NULL;
60 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
61 : TargetLowering(XTM, new XCoreTargetObjectFile()),
63 Subtarget(*XTM.getSubtargetImpl()) {
65 // Set up the register classes.
66 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
68 // Compute derived properties from the register classes
69 computeRegisterProperties();
71 // Division is expensive
72 setIntDivIsCheap(false);
74 setShiftAmountType(MVT::i32);
75 setStackPointerRegisterToSaveRestore(XCore::SP);
77 setSchedulingPreference(SchedulingForRegPressure);
79 // Use i32 for setcc operations results (slt, sgt, ...).
80 setBooleanContents(ZeroOrOneBooleanContent);
82 // XCore does not have the NodeTypes below.
83 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
84 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
85 setOperationAction(ISD::ADDC, MVT::i32, Expand);
86 setOperationAction(ISD::ADDE, MVT::i32, Expand);
87 setOperationAction(ISD::SUBC, MVT::i32, Expand);
88 setOperationAction(ISD::SUBE, MVT::i32, Expand);
90 // Stop the combiner recombining select and set_cc
91 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
94 setOperationAction(ISD::ADD, MVT::i64, Custom);
95 setOperationAction(ISD::SUB, MVT::i64, Custom);
96 setOperationAction(ISD::MULHS, MVT::i32, Expand);
97 setOperationAction(ISD::MULHU, MVT::i32, Expand);
98 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
99 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
100 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
103 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
104 setOperationAction(ISD::ROTL , MVT::i32, Expand);
105 setOperationAction(ISD::ROTR , MVT::i32, Expand);
107 setOperationAction(ISD::TRAP, MVT::Other, Legal);
109 // Expand jump tables for now
110 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
111 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
113 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
114 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
116 // Thread Local Storage
117 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
119 // Conversion of i64 -> double produces constantpool nodes
120 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
123 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
127 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
128 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
130 // Custom expand misaligned loads / stores.
131 setOperationAction(ISD::LOAD, MVT::i32, Custom);
132 setOperationAction(ISD::STORE, MVT::i32, Custom);
135 setOperationAction(ISD::VAEND, MVT::Other, Expand);
136 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
137 setOperationAction(ISD::VAARG, MVT::Other, Custom);
138 setOperationAction(ISD::VASTART, MVT::Other, Custom);
141 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
142 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
143 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
146 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
147 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
149 maxStoresPerMemset = 4;
150 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
152 // We have target-specific dag combine patterns for the following nodes:
153 setTargetDAGCombine(ISD::STORE);
156 SDValue XCoreTargetLowering::
157 LowerOperation(SDValue Op, SelectionDAG &DAG) {
158 switch (Op.getOpcode())
160 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
161 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
162 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
163 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
164 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
165 case ISD::LOAD: return LowerLOAD(Op, DAG);
166 case ISD::STORE: return LowerSTORE(Op, DAG);
167 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
168 case ISD::VAARG: return LowerVAARG(Op, DAG);
169 case ISD::VASTART: return LowerVASTART(Op, DAG);
170 // FIXME: Remove these when LegalizeDAGTypes lands.
172 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
173 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
175 llvm_unreachable("unimplemented operand");
180 /// ReplaceNodeResults - Replace the results of node with an illegal result
181 /// type with new values built out of custom code.
182 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
183 SmallVectorImpl<SDValue>&Results,
185 switch (N->getOpcode()) {
187 llvm_unreachable("Don't know how to custom expand this!");
191 Results.push_back(ExpandADDSUB(N, DAG));
196 /// getFunctionAlignment - Return the Log2 alignment of this function.
197 unsigned XCoreTargetLowering::
198 getFunctionAlignment(const Function *) const {
202 //===----------------------------------------------------------------------===//
203 // Misc Lower Operation implementation
204 //===----------------------------------------------------------------------===//
206 SDValue XCoreTargetLowering::
207 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
209 DebugLoc dl = Op.getDebugLoc();
210 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
211 Op.getOperand(3), Op.getOperand(4));
212 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
216 SDValue XCoreTargetLowering::
217 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
219 // FIXME there is no actual debug info here
220 DebugLoc dl = GA.getDebugLoc();
221 if (isa<Function>(GV)) {
222 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
224 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
226 // If GV is an alias then use the aliasee to determine constness
227 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
228 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
230 bool isConst = GVar && GVar->isConstant();
232 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
234 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
237 SDValue XCoreTargetLowering::
238 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
240 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
241 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
242 // If it's a debug information descriptor, don't mess with it.
243 if (DAG.isVerifiedDebugInfoDesc(Op))
245 return getGlobalAddressWrapper(GA, GV, DAG);
248 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
249 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
250 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
253 static inline bool isZeroLengthArray(const Type *Ty) {
254 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
255 return AT && (AT->getNumElements() == 0);
258 SDValue XCoreTargetLowering::
259 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
261 // FIXME there isn't really debug info here
262 DebugLoc dl = Op.getDebugLoc();
263 // transform to label + getid() * size
264 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
265 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
266 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
268 // If GV is an alias then use the aliasee to determine size
269 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
270 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
273 llvm_unreachable("Thread local object not a GlobalVariable?");
276 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
277 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
279 errs() << "Size of thread local object " << GVar->getName()
284 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
285 const TargetData *TD = TM.getTargetData();
286 unsigned Size = TD->getTypeAllocSize(Ty);
287 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
288 DAG.getConstant(Size, MVT::i32));
289 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
292 SDValue XCoreTargetLowering::
293 LowerBlockAddress(SDValue Op, SelectionDAG &DAG)
295 DebugLoc DL = Op.getDebugLoc();
297 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
298 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
300 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
303 SDValue XCoreTargetLowering::
304 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
306 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
307 // FIXME there isn't really debug info here
308 DebugLoc dl = CP->getDebugLoc();
309 EVT PtrVT = Op.getValueType();
311 if (CP->isMachineConstantPoolEntry()) {
312 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
315 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
318 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
321 SDValue XCoreTargetLowering::
322 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
324 // FIXME there isn't really debug info here
325 DebugLoc dl = Op.getDebugLoc();
326 EVT PtrVT = Op.getValueType();
327 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
328 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
329 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
333 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
336 if (Addr.getOpcode() != ISD::ADD) {
339 ConstantSDNode *CN = 0;
340 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
343 int64_t off = CN->getSExtValue();
344 const SDValue &Base = Addr.getOperand(0);
345 const SDValue *Root = &Base;
346 if (Base.getOpcode() == ISD::ADD &&
347 Base.getOperand(1).getOpcode() == ISD::SHL) {
348 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
350 if (CN && (CN->getSExtValue() >= 2)) {
351 Root = &Base.getOperand(0);
354 if (isa<FrameIndexSDNode>(*Root)) {
355 // All frame indicies are word aligned
360 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
361 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
362 // All dp / cp relative addresses are word aligned
370 SDValue XCoreTargetLowering::
371 LowerLOAD(SDValue Op, SelectionDAG &DAG)
373 LoadSDNode *LD = cast<LoadSDNode>(Op);
374 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
375 "Unexpected extension type");
376 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
377 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
380 unsigned ABIAlignment = getTargetData()->
381 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
382 // Leave aligned load alone.
383 if (LD->getAlignment() >= ABIAlignment) {
386 SDValue Chain = LD->getChain();
387 SDValue BasePtr = LD->getBasePtr();
388 DebugLoc dl = Op.getDebugLoc();
392 if (!LD->isVolatile() &&
393 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
394 if (Offset % 4 == 0) {
395 // We've managed to infer better alignment information than the load
396 // already has. Use an aligned load.
397 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
400 // ldw low, base[offset >> 2]
401 // ldw high, base[(offset >> 2) + 1]
402 // shr low_shifted, low, (offset & 0x3) * 8
403 // shl high_shifted, high, 32 - (offset & 0x3) * 8
404 // or result, low_shifted, high_shifted
405 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
406 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
407 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
408 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
410 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
411 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
413 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
415 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
417 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
418 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
419 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
420 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
422 SDValue Ops[] = { Result, Chain };
423 return DAG.getMergeValues(Ops, 2, dl);
426 if (LD->getAlignment() == 2) {
427 int SVOffset = LD->getSrcValueOffset();
428 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
429 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
430 LD->isVolatile(), 2);
431 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
432 DAG.getConstant(2, MVT::i32));
433 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
434 HighAddr, LD->getSrcValue(), SVOffset + 2,
435 MVT::i16, LD->isVolatile(), 2);
436 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
437 DAG.getConstant(16, MVT::i32));
438 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
439 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
441 SDValue Ops[] = { Result, Chain };
442 return DAG.getMergeValues(Ops, 2, dl);
445 // Lower to a call to __misaligned_load(BasePtr).
446 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
447 TargetLowering::ArgListTy Args;
448 TargetLowering::ArgListEntry Entry;
451 Entry.Node = BasePtr;
452 Args.push_back(Entry);
454 std::pair<SDValue, SDValue> CallResult =
455 LowerCallTo(Chain, IntPtrTy, false, false,
456 false, false, 0, CallingConv::C, false,
457 /*isReturnValueUsed=*/true,
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 EVT");
473 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
476 unsigned ABIAlignment = getTargetData()->
477 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
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(*DAG.getContext());
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::getVoidTy(*DAG.getContext()), false, false,
517 false, false, 0, CallingConv::C, false,
518 /*isReturnValueUsed=*/true,
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 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 EVT 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
606 //===----------------------------------------------------------------------===//
608 #include "XCoreGenCallingConv.inc"
610 //===----------------------------------------------------------------------===//
611 // Call Calling Convention Implementation
612 //===----------------------------------------------------------------------===//
614 /// XCore call implementation
616 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
617 CallingConv::ID CallConv, bool isVarArg,
619 const SmallVectorImpl<ISD::OutputArg> &Outs,
620 const SmallVectorImpl<ISD::InputArg> &Ins,
621 DebugLoc dl, SelectionDAG &DAG,
622 SmallVectorImpl<SDValue> &InVals) {
624 // For now, only CallingConv::C implemented
628 llvm_unreachable("Unsupported calling convention");
629 case CallingConv::Fast:
631 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
632 Outs, Ins, dl, DAG, InVals);
636 /// LowerCCCCallTo - functions arguments are copied from virtual
637 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
638 /// CALLSEQ_END are emitted.
639 /// TODO: isTailCall, sret.
641 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
642 CallingConv::ID CallConv, bool isVarArg,
644 const SmallVectorImpl<ISD::OutputArg> &Outs,
645 const SmallVectorImpl<ISD::InputArg> &Ins,
646 DebugLoc dl, SelectionDAG &DAG,
647 SmallVectorImpl<SDValue> &InVals) {
649 // Analyze operands of the call, assigning locations to each operand.
650 SmallVector<CCValAssign, 16> ArgLocs;
651 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
652 ArgLocs, *DAG.getContext());
654 // The ABI dictates there should be one stack slot available to the callee
655 // on function entry (for saving lr).
656 CCInfo.AllocateStack(4, 4);
658 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
660 // Get a count of how many bytes are to be pushed on the stack.
661 unsigned NumBytes = CCInfo.getNextStackOffset();
663 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
664 getPointerTy(), true));
666 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
667 SmallVector<SDValue, 12> MemOpChains;
669 // Walk the register/memloc assignments, inserting copies/loads.
670 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
671 CCValAssign &VA = ArgLocs[i];
672 SDValue Arg = Outs[i].Val;
674 // Promote the value if needed.
675 switch (VA.getLocInfo()) {
676 default: llvm_unreachable("Unknown loc info!");
677 case CCValAssign::Full: break;
678 case CCValAssign::SExt:
679 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
681 case CCValAssign::ZExt:
682 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
684 case CCValAssign::AExt:
685 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
689 // Arguments that can be passed on register must be kept at
692 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
694 assert(VA.isMemLoc());
696 int Offset = VA.getLocMemOffset();
698 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
700 DAG.getConstant(Offset/4, MVT::i32)));
704 // Transform all store nodes into one single node because
705 // all store nodes are independent of each other.
706 if (!MemOpChains.empty())
707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
708 &MemOpChains[0], MemOpChains.size());
710 // Build a sequence of copy-to-reg nodes chained together with token
711 // chain and flag operands which copy the outgoing args into registers.
712 // The InFlag in necessary since all emited instructions must be
715 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
716 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
717 RegsToPass[i].second, InFlag);
718 InFlag = Chain.getValue(1);
721 // If the callee is a GlobalAddress node (quite common, every direct call is)
722 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
723 // Likewise ExternalSymbol -> TargetExternalSymbol.
724 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
725 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
726 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
727 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
729 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
730 // = Chain, Callee, Reg#1, Reg#2, ...
732 // Returns a chain & a flag for retval copy to use.
733 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
734 SmallVector<SDValue, 8> Ops;
735 Ops.push_back(Chain);
736 Ops.push_back(Callee);
738 // Add argument registers to the end of the list so that they are
739 // known live into the call.
740 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
741 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
742 RegsToPass[i].second.getValueType()));
744 if (InFlag.getNode())
745 Ops.push_back(InFlag);
747 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
748 InFlag = Chain.getValue(1);
750 // Create the CALLSEQ_END node.
751 Chain = DAG.getCALLSEQ_END(Chain,
752 DAG.getConstant(NumBytes, getPointerTy(), true),
753 DAG.getConstant(0, getPointerTy(), true),
755 InFlag = Chain.getValue(1);
757 // Handle result values, copying them out of physregs into vregs that we
759 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
760 Ins, dl, DAG, InVals);
763 /// LowerCallResult - Lower the result values of a call into the
764 /// appropriate copies out of appropriate physical registers.
766 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
767 CallingConv::ID CallConv, bool isVarArg,
768 const SmallVectorImpl<ISD::InputArg> &Ins,
769 DebugLoc dl, SelectionDAG &DAG,
770 SmallVectorImpl<SDValue> &InVals) {
772 // Assign locations to each value returned by this call.
773 SmallVector<CCValAssign, 16> RVLocs;
774 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
775 RVLocs, *DAG.getContext());
777 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
779 // Copy all of the result registers out of their specified physreg.
780 for (unsigned i = 0; i != RVLocs.size(); ++i) {
781 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
782 RVLocs[i].getValVT(), InFlag).getValue(1);
783 InFlag = Chain.getValue(2);
784 InVals.push_back(Chain.getValue(0));
790 //===----------------------------------------------------------------------===//
791 // Formal Arguments Calling Convention Implementation
792 //===----------------------------------------------------------------------===//
794 /// XCore formal arguments implementation
796 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
797 CallingConv::ID CallConv,
799 const SmallVectorImpl<ISD::InputArg> &Ins,
802 SmallVectorImpl<SDValue> &InVals) {
806 llvm_unreachable("Unsupported calling convention");
808 case CallingConv::Fast:
809 return LowerCCCArguments(Chain, CallConv, isVarArg,
810 Ins, dl, DAG, InVals);
814 /// LowerCCCArguments - transform physical registers into
815 /// virtual registers and generate load operations for
816 /// arguments places on the stack.
819 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
820 CallingConv::ID CallConv,
822 const SmallVectorImpl<ISD::InputArg>
826 SmallVectorImpl<SDValue> &InVals) {
827 MachineFunction &MF = DAG.getMachineFunction();
828 MachineFrameInfo *MFI = MF.getFrameInfo();
829 MachineRegisterInfo &RegInfo = MF.getRegInfo();
831 // Assign locations to all of the incoming arguments.
832 SmallVector<CCValAssign, 16> ArgLocs;
833 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
834 ArgLocs, *DAG.getContext());
836 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
838 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
840 unsigned LRSaveSize = StackSlotSize;
842 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
844 CCValAssign &VA = ArgLocs[i];
847 // Arguments passed in registers
848 EVT RegVT = VA.getLocVT();
849 switch (RegVT.getSimpleVT().SimpleTy) {
853 errs() << "LowerFormalArguments Unhandled argument type: "
854 << RegVT.getSimpleVT().SimpleTy << "\n";
859 unsigned VReg = RegInfo.createVirtualRegister(
860 XCore::GRRegsRegisterClass);
861 RegInfo.addLiveIn(VA.getLocReg(), VReg);
862 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
866 assert(VA.isMemLoc());
867 // Load the argument to a virtual register
868 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
869 if (ObjSize > StackSlotSize) {
870 errs() << "LowerFormalArguments Unhandled argument type: "
871 << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
874 // Create the frame index object for this incoming parameter...
875 int FI = MFI->CreateFixedObject(ObjSize,
876 LRSaveSize + VA.getLocMemOffset(),
879 // Create the SelectionDAG nodes corresponding to a load
880 //from this parameter
881 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
882 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0));
887 /* Argument registers */
888 static const unsigned ArgRegs[] = {
889 XCore::R0, XCore::R1, XCore::R2, XCore::R3
891 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
892 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
893 array_lengthof(ArgRegs));
894 if (FirstVAReg < array_lengthof(ArgRegs)) {
895 SmallVector<SDValue, 4> MemOps;
897 // Save remaining registers, storing higher register numbers at a higher
899 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
900 // Create a stack slot
901 int FI = MFI->CreateFixedObject(4, offset, true, false);
902 if (i == FirstVAReg) {
903 XFI->setVarArgsFrameIndex(FI);
905 offset -= StackSlotSize;
906 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
907 // Move argument from phys reg -> virt reg
908 unsigned VReg = RegInfo.createVirtualRegister(
909 XCore::GRRegsRegisterClass);
910 RegInfo.addLiveIn(ArgRegs[i], VReg);
911 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
912 // Move argument from virt reg -> stack
913 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
914 MemOps.push_back(Store);
917 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
918 &MemOps[0], MemOps.size());
920 // This will point to the next argument passed via stack.
921 XFI->setVarArgsFrameIndex(
922 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
930 //===----------------------------------------------------------------------===//
931 // Return Value Calling Convention Implementation
932 //===----------------------------------------------------------------------===//
934 bool XCoreTargetLowering::
935 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
936 const SmallVectorImpl<EVT> &OutTys,
937 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
939 SmallVector<CCValAssign, 16> RVLocs;
940 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
941 RVLocs, *DAG.getContext());
942 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_XCore);
946 XCoreTargetLowering::LowerReturn(SDValue Chain,
947 CallingConv::ID CallConv, bool isVarArg,
948 const SmallVectorImpl<ISD::OutputArg> &Outs,
949 DebugLoc dl, SelectionDAG &DAG) {
951 // CCValAssign - represent the assignment of
952 // the return value to a location
953 SmallVector<CCValAssign, 16> RVLocs;
955 // CCState - Info about the registers and stack slot.
956 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
957 RVLocs, *DAG.getContext());
959 // Analize return values.
960 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
962 // If this is the first return lowered for this function, add
963 // the regs to the liveout set for the function.
964 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
965 for (unsigned i = 0; i != RVLocs.size(); ++i)
966 if (RVLocs[i].isRegLoc())
967 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
972 // Copy the result values into the output registers.
973 for (unsigned i = 0; i != RVLocs.size(); ++i) {
974 CCValAssign &VA = RVLocs[i];
975 assert(VA.isRegLoc() && "Can only return in registers!");
977 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
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,
1001 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) 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 first adding all successors of the current
1030 // block to the new block which will contain the Phi node for the select.
1031 // Also inform sdisel of the edge changes.
1032 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1033 E = BB->succ_end(); I != E; ++I) {
1034 EM->insert(std::make_pair(*I, sinkMBB));
1035 sinkMBB->addSuccessor(*I);
1037 // Next, remove all successors of the current block, and add the true
1038 // and fallthrough blocks as its successors.
1039 while (!BB->succ_empty())
1040 BB->removeSuccessor(BB->succ_begin());
1041 // Next, add the true and fallthrough blocks as its successors.
1042 BB->addSuccessor(copy0MBB);
1043 BB->addSuccessor(sinkMBB);
1046 // %FalseValue = ...
1047 // # fallthrough to sinkMBB
1050 // Update machine-CFG edges
1051 BB->addSuccessor(sinkMBB);
1054 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1057 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1058 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1059 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1061 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1065 //===----------------------------------------------------------------------===//
1066 // Target Optimization Hooks
1067 //===----------------------------------------------------------------------===//
1069 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1070 DAGCombinerInfo &DCI) const {
1071 SelectionDAG &DAG = DCI.DAG;
1072 DebugLoc dl = N->getDebugLoc();
1073 switch (N->getOpcode()) {
1076 // Replace unaligned store of unaligned load with memmove.
1077 StoreSDNode *ST = cast<StoreSDNode>(N);
1078 if (!DCI.isBeforeLegalize() ||
1079 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1080 ST->isVolatile() || ST->isIndexed()) {
1083 SDValue Chain = ST->getChain();
1085 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1086 if (StoreBits % 8) {
1089 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1090 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1091 unsigned Alignment = ST->getAlignment();
1092 if (Alignment >= ABIAlignment) {
1096 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1097 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1098 LD->getAlignment() == Alignment &&
1099 !LD->isVolatile() && !LD->isIndexed() &&
1100 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1101 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1103 DAG.getConstant(StoreBits/8, MVT::i32),
1104 Alignment, ST->getSrcValue(),
1105 ST->getSrcValueOffset(), LD->getSrcValue(),
1106 LD->getSrcValueOffset());
1115 //===----------------------------------------------------------------------===//
1116 // Addressing mode description hooks
1117 //===----------------------------------------------------------------------===//
1119 static inline bool isImmUs(int64_t val)
1121 return (val >= 0 && val <= 11);
1124 static inline bool isImmUs2(int64_t val)
1126 return (val%2 == 0 && isImmUs(val/2));
1129 static inline bool isImmUs4(int64_t val)
1131 return (val%4 == 0 && isImmUs(val/4));
1134 /// isLegalAddressingMode - Return true if the addressing mode represented
1135 /// by AM is legal for this target, for a load/store of the specified type.
1137 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1138 const Type *Ty) const {
1139 // Be conservative with void
1140 // FIXME: Can we be more aggressive?
1141 if (Ty->getTypeID() == Type::VoidTyID)
1144 const TargetData *TD = TM.getTargetData();
1145 unsigned Size = TD->getTypeAllocSize(Ty);
1147 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1154 if (AM.Scale == 0) {
1155 return isImmUs(AM.BaseOffs);
1158 return AM.Scale == 1 && AM.BaseOffs == 0;
1162 if (AM.Scale == 0) {
1163 return isImmUs2(AM.BaseOffs);
1166 return AM.Scale == 2 && AM.BaseOffs == 0;
1169 if (AM.Scale == 0) {
1170 return isImmUs4(AM.BaseOffs);
1173 return AM.Scale == 4 && AM.BaseOffs == 0;
1179 //===----------------------------------------------------------------------===//
1180 // XCore Inline Assembly Support
1181 //===----------------------------------------------------------------------===//
1183 std::vector<unsigned> XCoreTargetLowering::
1184 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1187 if (Constraint.size() != 1)
1188 return std::vector<unsigned>();
1190 switch (Constraint[0]) {
1193 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1194 XCore::R3, XCore::R4, XCore::R5,
1195 XCore::R6, XCore::R7, XCore::R8,
1196 XCore::R9, XCore::R10, XCore::R11, 0);
1199 return std::vector<unsigned>();