1 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the XCoreTargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "xcore-lower"
16 #include "XCoreISelLowering.h"
17 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreTargetMachine.h"
20 #include "XCoreSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ADT/VectorExtras.h"
42 const char *XCoreTargetLowering::
43 getTargetNodeName(unsigned Opcode) const
47 case XCoreISD::BL : return "XCoreISD::BL";
48 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
49 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
50 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
51 case XCoreISD::STWSP : return "XCoreISD::STWSP";
52 case XCoreISD::RETSP : return "XCoreISD::RETSP";
53 default : return NULL;
57 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
58 : TargetLowering(XTM),
60 Subtarget(*XTM.getSubtargetImpl()) {
62 // Set up the register classes.
63 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
65 // Compute derived properties from the register classes
66 computeRegisterProperties();
68 // Division is expensive
69 setIntDivIsCheap(false);
71 setShiftAmountType(MVT::i32);
72 setStackPointerRegisterToSaveRestore(XCore::SP);
74 setSchedulingPreference(SchedulingForRegPressure);
76 // Use i32 for setcc operations results (slt, sgt, ...).
77 setBooleanContents(ZeroOrOneBooleanContent);
79 // XCore does not have the NodeTypes below.
80 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
81 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
82 setOperationAction(ISD::ADDC, MVT::i32, Expand);
83 setOperationAction(ISD::ADDE, MVT::i32, Expand);
84 setOperationAction(ISD::SUBC, MVT::i32, Expand);
85 setOperationAction(ISD::SUBE, MVT::i32, Expand);
87 // Stop the combiner recombining select and set_cc
88 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
91 if (!Subtarget.isXS1A()) {
92 setOperationAction(ISD::ADD, MVT::i64, Custom);
93 setOperationAction(ISD::SUB, MVT::i64, Custom);
95 if (Subtarget.isXS1A()) {
96 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
98 setOperationAction(ISD::MULHS, MVT::i32, Expand);
99 setOperationAction(ISD::MULHU, MVT::i32, Expand);
100 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
101 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
102 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
105 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
106 setOperationAction(ISD::ROTL , MVT::i32, Expand);
107 setOperationAction(ISD::ROTR , MVT::i32, Expand);
109 setOperationAction(ISD::TRAP, MVT::Other, Legal);
111 // Expand jump tables for now
112 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
113 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
115 // RET must be custom lowered, to meet ABI requirements
116 setOperationAction(ISD::RET, MVT::Other, Custom);
118 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
120 // Thread Local Storage
121 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
123 // Conversion of i64 -> double produces constantpool nodes
124 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
127 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
128 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
129 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
131 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
132 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
134 // Custom expand misaligned loads / stores.
135 setOperationAction(ISD::LOAD, MVT::i32, Custom);
136 setOperationAction(ISD::STORE, MVT::i32, Custom);
139 setOperationAction(ISD::VAEND, MVT::Other, Expand);
140 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
141 setOperationAction(ISD::VAARG, MVT::Other, Custom);
142 setOperationAction(ISD::VASTART, MVT::Other, Custom);
145 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
146 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
147 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
150 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
151 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
153 maxStoresPerMemset = 4;
154 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
156 // We have target-specific dag combine patterns for the following nodes:
157 setTargetDAGCombine(ISD::STORE);
160 SDValue XCoreTargetLowering::
161 LowerOperation(SDValue Op, SelectionDAG &DAG) {
162 switch (Op.getOpcode())
164 case ISD::CALL: return LowerCALL(Op, DAG);
165 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
166 case ISD::RET: return LowerRET(Op, DAG);
167 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
168 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
169 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
170 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
171 case ISD::LOAD: return LowerLOAD(Op, DAG);
172 case ISD::STORE: return LowerSTORE(Op, DAG);
173 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
174 case ISD::VAARG: return LowerVAARG(Op, DAG);
175 case ISD::VASTART: return LowerVASTART(Op, DAG);
176 // FIXME: Remove these when LegalizeDAGTypes lands.
178 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
179 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
181 llvm_unreachable("unimplemented operand");
186 /// ReplaceNodeResults - Replace the results of node with an illegal result
187 /// type with new values built out of custom code.
188 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
189 SmallVectorImpl<SDValue>&Results,
191 switch (N->getOpcode()) {
193 llvm_unreachable("Don't know how to custom expand this!");
197 Results.push_back(ExpandADDSUB(N, DAG));
202 /// getFunctionAlignment - Return the Log2 alignment of this function.
203 unsigned XCoreTargetLowering::
204 getFunctionAlignment(const Function *) const {
208 //===----------------------------------------------------------------------===//
209 // Misc Lower Operation implementation
210 //===----------------------------------------------------------------------===//
212 SDValue XCoreTargetLowering::
213 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
215 DebugLoc dl = Op.getDebugLoc();
216 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
217 Op.getOperand(3), Op.getOperand(4));
218 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
222 SDValue XCoreTargetLowering::
223 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
225 // FIXME there is no actual debug info here
226 DebugLoc dl = GA.getDebugLoc();
227 if (isa<Function>(GV)) {
228 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
229 } else if (!Subtarget.isXS1A()) {
230 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
232 // If GV is an alias then use the aliasee to determine constness
233 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
234 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
236 bool isConst = GVar && GVar->isConstant();
238 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
241 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
244 SDValue XCoreTargetLowering::
245 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
247 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
248 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
249 // If it's a debug information descriptor, don't mess with it.
250 if (DAG.isVerifiedDebugInfoDesc(Op))
252 return getGlobalAddressWrapper(GA, GV, DAG);
255 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
256 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
257 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
260 static inline bool isZeroLengthArray(const Type *Ty) {
261 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
262 return AT && (AT->getNumElements() == 0);
265 SDValue XCoreTargetLowering::
266 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
268 // FIXME there isn't really debug info here
269 DebugLoc dl = Op.getDebugLoc();
270 // transform to label + getid() * size
271 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
272 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
273 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
275 // If GV is an alias then use the aliasee to determine size
276 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
277 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
280 llvm_unreachable("Thread local object not a GlobalVariable?");
283 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
284 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
286 errs() << "Size of thread local object " << GVar->getName()
291 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
292 const TargetData *TD = TM.getTargetData();
293 unsigned Size = TD->getTypeAllocSize(Ty);
294 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
295 DAG.getConstant(Size, MVT::i32));
296 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
299 SDValue XCoreTargetLowering::
300 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
302 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
303 // FIXME there isn't really debug info here
304 DebugLoc dl = CP->getDebugLoc();
305 if (Subtarget.isXS1A()) {
306 llvm_unreachable("Lowering of constant pool unimplemented");
309 MVT 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);
322 SDValue XCoreTargetLowering::
323 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
325 // FIXME there isn't really debug info here
326 DebugLoc dl = Op.getDebugLoc();
327 MVT PtrVT = Op.getValueType();
328 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
329 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
330 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
334 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
337 if (Addr.getOpcode() != ISD::ADD) {
340 ConstantSDNode *CN = 0;
341 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
344 int64_t off = CN->getSExtValue();
345 const SDValue &Base = Addr.getOperand(0);
346 const SDValue *Root = &Base;
347 if (Base.getOpcode() == ISD::ADD &&
348 Base.getOperand(1).getOpcode() == ISD::SHL) {
349 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
351 if (CN && (CN->getSExtValue() >= 2)) {
352 Root = &Base.getOperand(0);
355 if (isa<FrameIndexSDNode>(*Root)) {
356 // All frame indicies are word aligned
361 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
362 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
363 // All dp / cp relative addresses are word aligned
371 SDValue XCoreTargetLowering::
372 LowerLOAD(SDValue Op, SelectionDAG &DAG)
374 LoadSDNode *LD = cast<LoadSDNode>(Op);
375 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && "Unexpected extension type");
376 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load MVT");
377 if (allowsUnalignedMemoryAccesses()) {
380 unsigned ABIAlignment = getTargetData()->
381 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT(*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();
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 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
461 { CallResult.first, CallResult.second };
463 return DAG.getMergeValues(Ops, 2, dl);
466 SDValue XCoreTargetLowering::
467 LowerSTORE(SDValue Op, SelectionDAG &DAG)
469 StoreSDNode *ST = cast<StoreSDNode>(Op);
470 assert(!ST->isTruncatingStore() && "Unexpected store type");
471 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store MVT");
472 if (allowsUnalignedMemoryAccesses()) {
475 unsigned ABIAlignment = getTargetData()->
476 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT(*DAG.getContext()));
477 // Leave aligned store alone.
478 if (ST->getAlignment() >= ABIAlignment) {
481 SDValue Chain = ST->getChain();
482 SDValue BasePtr = ST->getBasePtr();
483 SDValue Value = ST->getValue();
484 DebugLoc dl = Op.getDebugLoc();
486 if (ST->getAlignment() == 2) {
487 int SVOffset = ST->getSrcValueOffset();
489 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
490 DAG.getConstant(16, MVT::i32));
491 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
492 ST->getSrcValue(), SVOffset, MVT::i16,
493 ST->isVolatile(), 2);
494 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
495 DAG.getConstant(2, MVT::i32));
496 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
497 ST->getSrcValue(), SVOffset + 2,
498 MVT::i16, ST->isVolatile(), 2);
499 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
502 // Lower to a call to __misaligned_store(BasePtr, Value).
503 const Type *IntPtrTy = getTargetData()->getIntPtrType();
504 TargetLowering::ArgListTy Args;
505 TargetLowering::ArgListEntry Entry;
508 Entry.Node = BasePtr;
509 Args.push_back(Entry);
512 Args.push_back(Entry);
514 std::pair<SDValue, SDValue> CallResult =
515 LowerCallTo(Chain, Type::VoidTy, false, false,
516 false, false, 0, CallingConv::C, false,
517 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
520 return CallResult.second;
523 SDValue XCoreTargetLowering::
524 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
526 assert(N->getValueType(0) == MVT::i64 &&
527 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
528 "Unknown operand to lower!");
529 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
530 DebugLoc dl = N->getDebugLoc();
532 // Extract components
533 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
534 N->getOperand(0), DAG.getConstant(0, MVT::i32));
535 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
536 N->getOperand(0), DAG.getConstant(1, MVT::i32));
537 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
538 N->getOperand(1), DAG.getConstant(0, MVT::i32));
539 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
540 N->getOperand(1), DAG.getConstant(1, MVT::i32));
543 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
545 SDValue Zero = DAG.getConstant(0, MVT::i32);
546 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
548 SDValue Lo(Carry.getNode(), 1);
550 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
552 SDValue Hi(Ignored.getNode(), 1);
554 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
557 SDValue XCoreTargetLowering::
558 LowerVAARG(SDValue Op, SelectionDAG &DAG)
560 llvm_unreachable("unimplemented");
561 // FIX Arguments passed by reference need a extra dereference.
562 SDNode *Node = Op.getNode();
563 DebugLoc dl = Node->getDebugLoc();
564 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
565 MVT VT = Node->getValueType(0);
566 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
567 Node->getOperand(1), V, 0);
568 // Increment the pointer, VAList, to the next vararg
569 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
570 DAG.getConstant(VT.getSizeInBits(),
572 // Store the incremented VAList to the legalized pointer
573 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
574 // Load the actual argument out of the pointer VAList
575 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
578 SDValue XCoreTargetLowering::
579 LowerVASTART(SDValue Op, SelectionDAG &DAG)
581 DebugLoc dl = Op.getDebugLoc();
582 // vastart stores the address of the VarArgsFrameIndex slot into the
583 // memory location argument
584 MachineFunction &MF = DAG.getMachineFunction();
585 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
586 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
587 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
588 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
591 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
592 DebugLoc dl = Op.getDebugLoc();
593 // Depths > 0 not supported yet!
594 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
597 MachineFunction &MF = DAG.getMachineFunction();
598 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
599 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
600 RegInfo->getFrameRegister(MF), MVT::i32);
603 //===----------------------------------------------------------------------===//
604 // Calling Convention Implementation
606 // The lower operations present on calling convention works on this order:
607 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
608 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
609 // LowerRET (virt regs --> phys regs)
610 // LowerCALL (phys regs --> virt regs)
612 //===----------------------------------------------------------------------===//
614 #include "XCoreGenCallingConv.inc"
616 //===----------------------------------------------------------------------===//
617 // CALL Calling Convention Implementation
618 //===----------------------------------------------------------------------===//
620 /// XCore custom CALL implementation
621 SDValue XCoreTargetLowering::
622 LowerCALL(SDValue Op, SelectionDAG &DAG)
624 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
625 unsigned CallingConv = TheCall->getCallingConv();
626 // For now, only CallingConv::C implemented
630 llvm_unreachable("Unsupported calling convention");
631 case CallingConv::Fast:
633 return LowerCCCCallTo(Op, DAG, CallingConv);
637 /// LowerCCCCallTo - functions arguments are copied from virtual
638 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
639 /// CALLSEQ_END are emitted.
640 /// TODO: isTailCall, sret.
641 SDValue XCoreTargetLowering::
642 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
644 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
645 SDValue Chain = TheCall->getChain();
646 SDValue Callee = TheCall->getCallee();
647 bool isVarArg = TheCall->isVarArg();
648 DebugLoc dl = Op.getDebugLoc();
650 // Analyze operands of the call, assigning locations to each operand.
651 SmallVector<CCValAssign, 16> ArgLocs;
652 CCState CCInfo(CC, isVarArg, getTargetMachine(), 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(TheCall, 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];
673 // Arguments start after the 5 first operands of ISD::CALL
674 SDValue Arg = TheCall->getArg(i);
676 // Promote the value if needed.
677 switch (VA.getLocInfo()) {
678 default: llvm_unreachable("Unknown loc info!");
679 case CCValAssign::Full: break;
680 case CCValAssign::SExt:
681 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
683 case CCValAssign::ZExt:
684 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
686 case CCValAssign::AExt:
687 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
691 // Arguments that can be passed on register must be kept at
694 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
696 assert(VA.isMemLoc());
698 int Offset = VA.getLocMemOffset();
700 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
702 DAG.getConstant(Offset/4, MVT::i32)));
706 // Transform all store nodes into one single node because
707 // all store nodes are independent of each other.
708 if (!MemOpChains.empty())
709 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
710 &MemOpChains[0], MemOpChains.size());
712 // Build a sequence of copy-to-reg nodes chained together with token
713 // chain and flag operands which copy the outgoing args into registers.
714 // The InFlag in necessary since all emited instructions must be
717 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
718 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
719 RegsToPass[i].second, InFlag);
720 InFlag = Chain.getValue(1);
723 // If the callee is a GlobalAddress node (quite common, every direct call is)
724 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
725 // Likewise ExternalSymbol -> TargetExternalSymbol.
726 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
727 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
728 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
729 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
731 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
732 // = Chain, Callee, Reg#1, Reg#2, ...
734 // Returns a chain & a flag for retval copy to use.
735 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
736 SmallVector<SDValue, 8> Ops;
737 Ops.push_back(Chain);
738 Ops.push_back(Callee);
740 // Add argument registers to the end of the list so that they are
741 // known live into the call.
742 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
743 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
744 RegsToPass[i].second.getValueType()));
746 if (InFlag.getNode())
747 Ops.push_back(InFlag);
749 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
750 InFlag = Chain.getValue(1);
752 // Create the CALLSEQ_END node.
753 Chain = DAG.getCALLSEQ_END(Chain,
754 DAG.getConstant(NumBytes, getPointerTy(), true),
755 DAG.getConstant(0, getPointerTy(), true),
757 InFlag = Chain.getValue(1);
759 // Handle result values, copying them out of physregs into vregs that we
761 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
765 /// LowerCallResult - Lower the result values of an ISD::CALL into the
766 /// appropriate copies out of appropriate physical registers. This assumes that
767 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
768 /// being lowered. Returns a SDNode with the same number of values as the
770 SDNode *XCoreTargetLowering::
771 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
772 unsigned CallingConv, SelectionDAG &DAG) {
773 bool isVarArg = TheCall->isVarArg();
774 DebugLoc dl = TheCall->getDebugLoc();
776 // Assign locations to each value returned by this call.
777 SmallVector<CCValAssign, 16> RVLocs;
778 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
779 RVLocs, *DAG.getContext());
781 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
782 SmallVector<SDValue, 8> ResultVals;
784 // Copy all of the result registers out of their specified physreg.
785 for (unsigned i = 0; i != RVLocs.size(); ++i) {
786 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
787 RVLocs[i].getValVT(), InFlag).getValue(1);
788 InFlag = Chain.getValue(2);
789 ResultVals.push_back(Chain.getValue(0));
792 ResultVals.push_back(Chain);
794 // Merge everything together with a MERGE_VALUES node.
795 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
796 &ResultVals[0], ResultVals.size()).getNode();
799 //===----------------------------------------------------------------------===//
800 // FORMAL_ARGUMENTS Calling Convention Implementation
801 //===----------------------------------------------------------------------===//
803 /// XCore custom FORMAL_ARGUMENTS implementation
804 SDValue XCoreTargetLowering::
805 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
807 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
811 llvm_unreachable("Unsupported calling convention");
813 case CallingConv::Fast:
814 return LowerCCCArguments(Op, DAG);
818 /// LowerCCCArguments - transform physical registers into
819 /// virtual registers and generate load operations for
820 /// arguments places on the stack.
822 SDValue XCoreTargetLowering::
823 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
825 MachineFunction &MF = DAG.getMachineFunction();
826 MachineFrameInfo *MFI = MF.getFrameInfo();
827 MachineRegisterInfo &RegInfo = MF.getRegInfo();
828 SDValue Root = Op.getOperand(0);
829 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
830 unsigned CC = MF.getFunction()->getCallingConv();
831 DebugLoc dl = Op.getDebugLoc();
833 // Assign locations to all of the incoming arguments.
834 SmallVector<CCValAssign, 16> ArgLocs;
835 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
837 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
839 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
841 SmallVector<SDValue, 16> ArgValues;
843 unsigned LRSaveSize = StackSlotSize;
845 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
847 CCValAssign &VA = ArgLocs[i];
850 // Arguments passed in registers
851 MVT RegVT = VA.getLocVT();
852 switch (RegVT.getSimpleVT()) {
856 errs() << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
857 << RegVT.getSimpleVT() << "\n";
862 unsigned VReg = RegInfo.createVirtualRegister(
863 XCore::GRRegsRegisterClass);
864 RegInfo.addLiveIn(VA.getLocReg(), VReg);
865 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
869 assert(VA.isMemLoc());
870 // Load the argument to a virtual register
871 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
872 if (ObjSize > StackSlotSize) {
873 errs() << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
874 << VA.getLocVT().getSimpleVT()
877 // Create the frame index object for this incoming parameter...
878 int FI = MFI->CreateFixedObject(ObjSize,
879 LRSaveSize + VA.getLocMemOffset());
881 // Create the SelectionDAG nodes corresponding to a load
882 //from this parameter
883 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
884 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
889 /* Argument registers */
890 static const unsigned ArgRegs[] = {
891 XCore::R0, XCore::R1, XCore::R2, XCore::R3
893 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
894 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
895 array_lengthof(ArgRegs));
896 if (FirstVAReg < array_lengthof(ArgRegs)) {
897 SmallVector<SDValue, 4> MemOps;
899 // Save remaining registers, storing higher register numbers at a higher
901 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
902 // Create a stack slot
903 int FI = MFI->CreateFixedObject(4, offset);
904 if (i == FirstVAReg) {
905 XFI->setVarArgsFrameIndex(FI);
907 offset -= StackSlotSize;
908 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
909 // Move argument from phys reg -> virt reg
910 unsigned VReg = RegInfo.createVirtualRegister(
911 XCore::GRRegsRegisterClass);
912 RegInfo.addLiveIn(ArgRegs[i], VReg);
913 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
914 // Move argument from virt reg -> stack
915 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
916 MemOps.push_back(Store);
919 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
920 &MemOps[0], MemOps.size());
922 // This will point to the next argument passed via stack.
923 XFI->setVarArgsFrameIndex(
924 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
928 ArgValues.push_back(Root);
930 // Return the new list of results.
931 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
932 Op.getNode()->value_end());
933 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
934 &ArgValues[0], ArgValues.size());
937 //===----------------------------------------------------------------------===//
938 // Return Value Calling Convention Implementation
939 //===----------------------------------------------------------------------===//
941 SDValue XCoreTargetLowering::
942 LowerRET(SDValue Op, SelectionDAG &DAG)
944 // CCValAssign - represent the assignment of
945 // the return value to a location
946 SmallVector<CCValAssign, 16> RVLocs;
947 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
948 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
949 DebugLoc dl = Op.getDebugLoc();
951 // CCState - Info about the registers and stack slot.
952 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, *DAG.getContext());
954 // Analize return values of ISD::RET
955 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
957 // If this is the first return lowered for this function, add
958 // the regs to the liveout set for the function.
959 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
960 for (unsigned i = 0; i != RVLocs.size(); ++i)
961 if (RVLocs[i].isRegLoc())
962 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
965 // The chain is always operand #0
966 SDValue Chain = Op.getOperand(0);
969 // Copy the result values into the output registers.
970 for (unsigned i = 0; i != RVLocs.size(); ++i) {
971 CCValAssign &VA = RVLocs[i];
972 assert(VA.isRegLoc() && "Can only return in registers!");
974 // ISD::RET => ret chain, (regnum1,val1), ...
975 // So i*2+1 index only the regnums
976 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
977 Op.getOperand(i*2+1), Flag);
979 // guarantee that all emitted copies are
980 // stuck together, avoiding something bad
981 Flag = Chain.getValue(1);
984 // Return on XCore is always a "retsp 0"
986 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
987 Chain, DAG.getConstant(0, MVT::i32), Flag);
989 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
990 Chain, DAG.getConstant(0, MVT::i32));
993 //===----------------------------------------------------------------------===//
994 // Other Lowering Code
995 //===----------------------------------------------------------------------===//
998 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
999 MachineBasicBlock *BB) const {
1000 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1001 DebugLoc dl = MI->getDebugLoc();
1002 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1003 "Unexpected instr type to insert");
1005 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1006 // control-flow pattern. The incoming instruction knows the destination vreg
1007 // to set, the condition code register to branch on, the true/false values to
1008 // select between, and a branch opcode to use.
1009 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1010 MachineFunction::iterator It = BB;
1016 // cmpTY ccX, r1, r2
1018 // fallthrough --> copy0MBB
1019 MachineBasicBlock *thisMBB = BB;
1020 MachineFunction *F = BB->getParent();
1021 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1022 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1023 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1024 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1025 F->insert(It, copy0MBB);
1026 F->insert(It, sinkMBB);
1027 // Update machine-CFG edges by transferring all successors of the current
1028 // block to the new block which will contain the Phi node for the select.
1029 sinkMBB->transferSuccessors(BB);
1030 // Next, add the true and fallthrough blocks as its successors.
1031 BB->addSuccessor(copy0MBB);
1032 BB->addSuccessor(sinkMBB);
1035 // %FalseValue = ...
1036 // # fallthrough to sinkMBB
1039 // Update machine-CFG edges
1040 BB->addSuccessor(sinkMBB);
1043 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1046 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1047 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1048 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1050 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1054 //===----------------------------------------------------------------------===//
1055 // Target Optimization Hooks
1056 //===----------------------------------------------------------------------===//
1058 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1059 DAGCombinerInfo &DCI) const {
1060 SelectionDAG &DAG = DCI.DAG;
1061 DebugLoc dl = N->getDebugLoc();
1062 switch (N->getOpcode()) {
1065 // Replace unaligned store of unaligned load with memmove.
1066 StoreSDNode *ST = cast<StoreSDNode>(N);
1067 if (!DCI.isBeforeLegalize() || allowsUnalignedMemoryAccesses() ||
1068 ST->isVolatile() || ST->isIndexed()) {
1071 SDValue Chain = ST->getChain();
1073 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1074 if (StoreBits % 8) {
1077 unsigned ABIAlignment = getTargetData()->
1078 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT(*DAG.getContext()));
1079 unsigned Alignment = ST->getAlignment();
1080 if (Alignment >= ABIAlignment) {
1084 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1085 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1086 LD->getAlignment() == Alignment &&
1087 !LD->isVolatile() && !LD->isIndexed() &&
1088 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1089 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1091 DAG.getConstant(StoreBits/8, MVT::i32),
1092 Alignment, ST->getSrcValue(),
1093 ST->getSrcValueOffset(), LD->getSrcValue(),
1094 LD->getSrcValueOffset());
1103 //===----------------------------------------------------------------------===//
1104 // Addressing mode description hooks
1105 //===----------------------------------------------------------------------===//
1107 static inline bool isImmUs(int64_t val)
1109 return (val >= 0 && val <= 11);
1112 static inline bool isImmUs2(int64_t val)
1114 return (val%2 == 0 && isImmUs(val/2));
1117 static inline bool isImmUs4(int64_t val)
1119 return (val%4 == 0 && isImmUs(val/4));
1122 /// isLegalAddressingMode - Return true if the addressing mode represented
1123 /// by AM is legal for this target, for a load/store of the specified type.
1125 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1126 const Type *Ty) const {
1127 // Be conservative with void
1128 // FIXME: Can we be more aggressive?
1129 if (Ty->getTypeID() == Type::VoidTyID)
1132 const TargetData *TD = TM.getTargetData();
1133 unsigned Size = TD->getTypeAllocSize(Ty);
1135 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1142 if (AM.Scale == 0) {
1143 return isImmUs(AM.BaseOffs);
1146 return AM.Scale == 1 && AM.BaseOffs == 0;
1150 if (AM.Scale == 0) {
1151 return isImmUs2(AM.BaseOffs);
1154 return AM.Scale == 2 && AM.BaseOffs == 0;
1157 if (AM.Scale == 0) {
1158 return isImmUs4(AM.BaseOffs);
1161 return AM.Scale == 4 && AM.BaseOffs == 0;
1167 //===----------------------------------------------------------------------===//
1168 // XCore Inline Assembly Support
1169 //===----------------------------------------------------------------------===//
1171 std::vector<unsigned> XCoreTargetLowering::
1172 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1175 if (Constraint.size() != 1)
1176 return std::vector<unsigned>();
1178 switch (Constraint[0]) {
1181 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1182 XCore::R3, XCore::R4, XCore::R5,
1183 XCore::R6, XCore::R7, XCore::R8,
1184 XCore::R9, XCore::R10, XCore::R11, 0);
1187 return std::vector<unsigned>();