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);
115 // Thread Local Storage
116 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
118 // Conversion of i64 -> double produces constantpool nodes
119 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
122 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
123 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
126 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
127 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
129 // Custom expand misaligned loads / stores.
130 setOperationAction(ISD::LOAD, MVT::i32, Custom);
131 setOperationAction(ISD::STORE, MVT::i32, Custom);
134 setOperationAction(ISD::VAEND, MVT::Other, Expand);
135 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
136 setOperationAction(ISD::VAARG, MVT::Other, Custom);
137 setOperationAction(ISD::VASTART, MVT::Other, Custom);
140 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
141 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
142 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
145 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
146 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
148 maxStoresPerMemset = 4;
149 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
151 // We have target-specific dag combine patterns for the following nodes:
152 setTargetDAGCombine(ISD::STORE);
155 SDValue XCoreTargetLowering::
156 LowerOperation(SDValue Op, SelectionDAG &DAG) {
157 switch (Op.getOpcode())
159 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
160 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
161 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
162 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
163 case ISD::LOAD: return LowerLOAD(Op, DAG);
164 case ISD::STORE: return LowerSTORE(Op, DAG);
165 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
166 case ISD::VAARG: return LowerVAARG(Op, DAG);
167 case ISD::VASTART: return LowerVASTART(Op, DAG);
168 // FIXME: Remove these when LegalizeDAGTypes lands.
170 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
171 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
173 llvm_unreachable("unimplemented operand");
178 /// ReplaceNodeResults - Replace the results of node with an illegal result
179 /// type with new values built out of custom code.
180 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
181 SmallVectorImpl<SDValue>&Results,
183 switch (N->getOpcode()) {
185 llvm_unreachable("Don't know how to custom expand this!");
189 Results.push_back(ExpandADDSUB(N, DAG));
194 /// getFunctionAlignment - Return the Log2 alignment of this function.
195 unsigned XCoreTargetLowering::
196 getFunctionAlignment(const Function *) const {
200 //===----------------------------------------------------------------------===//
201 // Misc Lower Operation implementation
202 //===----------------------------------------------------------------------===//
204 SDValue XCoreTargetLowering::
205 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
207 DebugLoc dl = Op.getDebugLoc();
208 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
209 Op.getOperand(3), Op.getOperand(4));
210 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
214 SDValue XCoreTargetLowering::
215 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
217 // FIXME there is no actual debug info here
218 DebugLoc dl = GA.getDebugLoc();
219 if (isa<Function>(GV)) {
220 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
222 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
224 // If GV is an alias then use the aliasee to determine constness
225 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
226 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
228 bool isConst = GVar && GVar->isConstant();
230 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
232 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
235 SDValue XCoreTargetLowering::
236 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
238 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
239 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
240 // If it's a debug information descriptor, don't mess with it.
241 if (DAG.isVerifiedDebugInfoDesc(Op))
243 return getGlobalAddressWrapper(GA, GV, DAG);
246 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
247 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
248 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
251 static inline bool isZeroLengthArray(const Type *Ty) {
252 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
253 return AT && (AT->getNumElements() == 0);
256 SDValue XCoreTargetLowering::
257 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
259 // FIXME there isn't really debug info here
260 DebugLoc dl = Op.getDebugLoc();
261 // transform to label + getid() * size
262 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
263 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
264 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
266 // If GV is an alias then use the aliasee to determine size
267 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
268 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
271 llvm_unreachable("Thread local object not a GlobalVariable?");
274 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
275 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
277 errs() << "Size of thread local object " << GVar->getName()
282 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
283 const TargetData *TD = TM.getTargetData();
284 unsigned Size = TD->getTypeAllocSize(Ty);
285 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
286 DAG.getConstant(Size, MVT::i32));
287 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
290 SDValue XCoreTargetLowering::
291 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
293 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
294 // FIXME there isn't really debug info here
295 DebugLoc dl = CP->getDebugLoc();
296 EVT PtrVT = Op.getValueType();
298 if (CP->isMachineConstantPoolEntry()) {
299 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
302 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
305 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
308 SDValue XCoreTargetLowering::
309 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
311 // FIXME there isn't really debug info here
312 DebugLoc dl = Op.getDebugLoc();
313 EVT PtrVT = Op.getValueType();
314 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
315 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
316 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
320 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
323 if (Addr.getOpcode() != ISD::ADD) {
326 ConstantSDNode *CN = 0;
327 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
330 int64_t off = CN->getSExtValue();
331 const SDValue &Base = Addr.getOperand(0);
332 const SDValue *Root = &Base;
333 if (Base.getOpcode() == ISD::ADD &&
334 Base.getOperand(1).getOpcode() == ISD::SHL) {
335 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
337 if (CN && (CN->getSExtValue() >= 2)) {
338 Root = &Base.getOperand(0);
341 if (isa<FrameIndexSDNode>(*Root)) {
342 // All frame indicies are word aligned
347 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
348 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
349 // All dp / cp relative addresses are word aligned
357 SDValue XCoreTargetLowering::
358 LowerLOAD(SDValue Op, SelectionDAG &DAG)
360 LoadSDNode *LD = cast<LoadSDNode>(Op);
361 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
362 "Unexpected extension type");
363 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
364 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
367 unsigned ABIAlignment = getTargetData()->
368 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
369 // Leave aligned load alone.
370 if (LD->getAlignment() >= ABIAlignment) {
373 SDValue Chain = LD->getChain();
374 SDValue BasePtr = LD->getBasePtr();
375 DebugLoc dl = Op.getDebugLoc();
379 if (!LD->isVolatile() &&
380 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
381 if (Offset % 4 == 0) {
382 // We've managed to infer better alignment information than the load
383 // already has. Use an aligned load.
384 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
387 // ldw low, base[offset >> 2]
388 // ldw high, base[(offset >> 2) + 1]
389 // shr low_shifted, low, (offset & 0x3) * 8
390 // shl high_shifted, high, 32 - (offset & 0x3) * 8
391 // or result, low_shifted, high_shifted
392 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
393 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
394 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
395 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
397 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
398 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
400 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
402 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
404 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
405 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
406 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
407 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
409 SDValue Ops[] = { Result, Chain };
410 return DAG.getMergeValues(Ops, 2, dl);
413 if (LD->getAlignment() == 2) {
414 int SVOffset = LD->getSrcValueOffset();
415 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
416 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
417 LD->isVolatile(), 2);
418 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
419 DAG.getConstant(2, MVT::i32));
420 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
421 HighAddr, LD->getSrcValue(), SVOffset + 2,
422 MVT::i16, LD->isVolatile(), 2);
423 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
424 DAG.getConstant(16, MVT::i32));
425 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
426 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
428 SDValue Ops[] = { Result, Chain };
429 return DAG.getMergeValues(Ops, 2, dl);
432 // Lower to a call to __misaligned_load(BasePtr).
433 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
434 TargetLowering::ArgListTy Args;
435 TargetLowering::ArgListEntry Entry;
438 Entry.Node = BasePtr;
439 Args.push_back(Entry);
441 std::pair<SDValue, SDValue> CallResult =
442 LowerCallTo(Chain, IntPtrTy, false, false,
443 false, false, 0, CallingConv::C, false,
444 /*isReturnValueUsed=*/true,
445 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
449 { CallResult.first, CallResult.second };
451 return DAG.getMergeValues(Ops, 2, dl);
454 SDValue XCoreTargetLowering::
455 LowerSTORE(SDValue Op, SelectionDAG &DAG)
457 StoreSDNode *ST = cast<StoreSDNode>(Op);
458 assert(!ST->isTruncatingStore() && "Unexpected store type");
459 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
460 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
463 unsigned ABIAlignment = getTargetData()->
464 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
465 // Leave aligned store alone.
466 if (ST->getAlignment() >= ABIAlignment) {
469 SDValue Chain = ST->getChain();
470 SDValue BasePtr = ST->getBasePtr();
471 SDValue Value = ST->getValue();
472 DebugLoc dl = Op.getDebugLoc();
474 if (ST->getAlignment() == 2) {
475 int SVOffset = ST->getSrcValueOffset();
477 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
478 DAG.getConstant(16, MVT::i32));
479 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
480 ST->getSrcValue(), SVOffset, MVT::i16,
481 ST->isVolatile(), 2);
482 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
483 DAG.getConstant(2, MVT::i32));
484 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
485 ST->getSrcValue(), SVOffset + 2,
486 MVT::i16, ST->isVolatile(), 2);
487 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
490 // Lower to a call to __misaligned_store(BasePtr, Value).
491 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
492 TargetLowering::ArgListTy Args;
493 TargetLowering::ArgListEntry Entry;
496 Entry.Node = BasePtr;
497 Args.push_back(Entry);
500 Args.push_back(Entry);
502 std::pair<SDValue, SDValue> CallResult =
503 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
504 false, false, 0, CallingConv::C, false,
505 /*isReturnValueUsed=*/true,
506 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
509 return CallResult.second;
512 SDValue XCoreTargetLowering::
513 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
515 assert(N->getValueType(0) == MVT::i64 &&
516 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
517 "Unknown operand to lower!");
518 DebugLoc dl = N->getDebugLoc();
520 // Extract components
521 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
522 N->getOperand(0), DAG.getConstant(0, MVT::i32));
523 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
524 N->getOperand(0), DAG.getConstant(1, MVT::i32));
525 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
526 N->getOperand(1), DAG.getConstant(0, MVT::i32));
527 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
528 N->getOperand(1), DAG.getConstant(1, MVT::i32));
531 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
533 SDValue Zero = DAG.getConstant(0, MVT::i32);
534 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
536 SDValue Lo(Carry.getNode(), 1);
538 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
540 SDValue Hi(Ignored.getNode(), 1);
542 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
545 SDValue XCoreTargetLowering::
546 LowerVAARG(SDValue Op, SelectionDAG &DAG)
548 llvm_unreachable("unimplemented");
549 // FIX Arguments passed by reference need a extra dereference.
550 SDNode *Node = Op.getNode();
551 DebugLoc dl = Node->getDebugLoc();
552 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
553 EVT VT = Node->getValueType(0);
554 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
555 Node->getOperand(1), V, 0);
556 // Increment the pointer, VAList, to the next vararg
557 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
558 DAG.getConstant(VT.getSizeInBits(),
560 // Store the incremented VAList to the legalized pointer
561 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
562 // Load the actual argument out of the pointer VAList
563 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
566 SDValue XCoreTargetLowering::
567 LowerVASTART(SDValue Op, SelectionDAG &DAG)
569 DebugLoc dl = Op.getDebugLoc();
570 // vastart stores the address of the VarArgsFrameIndex slot into the
571 // memory location argument
572 MachineFunction &MF = DAG.getMachineFunction();
573 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
574 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
575 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
576 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
579 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
580 DebugLoc dl = Op.getDebugLoc();
581 // Depths > 0 not supported yet!
582 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
585 MachineFunction &MF = DAG.getMachineFunction();
586 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
587 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
588 RegInfo->getFrameRegister(MF), MVT::i32);
591 //===----------------------------------------------------------------------===//
592 // Calling Convention Implementation
593 //===----------------------------------------------------------------------===//
595 #include "XCoreGenCallingConv.inc"
597 //===----------------------------------------------------------------------===//
598 // Call Calling Convention Implementation
599 //===----------------------------------------------------------------------===//
601 /// XCore call implementation
603 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
604 CallingConv::ID CallConv, bool isVarArg,
606 const SmallVectorImpl<ISD::OutputArg> &Outs,
607 const SmallVectorImpl<ISD::InputArg> &Ins,
608 DebugLoc dl, SelectionDAG &DAG,
609 SmallVectorImpl<SDValue> &InVals) {
611 // For now, only CallingConv::C implemented
615 llvm_unreachable("Unsupported calling convention");
616 case CallingConv::Fast:
618 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
619 Outs, Ins, dl, DAG, InVals);
623 /// LowerCCCCallTo - functions arguments are copied from virtual
624 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
625 /// CALLSEQ_END are emitted.
626 /// TODO: isTailCall, sret.
628 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
629 CallingConv::ID CallConv, bool isVarArg,
631 const SmallVectorImpl<ISD::OutputArg> &Outs,
632 const SmallVectorImpl<ISD::InputArg> &Ins,
633 DebugLoc dl, SelectionDAG &DAG,
634 SmallVectorImpl<SDValue> &InVals) {
636 // Analyze operands of the call, assigning locations to each operand.
637 SmallVector<CCValAssign, 16> ArgLocs;
638 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
639 ArgLocs, *DAG.getContext());
641 // The ABI dictates there should be one stack slot available to the callee
642 // on function entry (for saving lr).
643 CCInfo.AllocateStack(4, 4);
645 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
647 // Get a count of how many bytes are to be pushed on the stack.
648 unsigned NumBytes = CCInfo.getNextStackOffset();
650 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
651 getPointerTy(), true));
653 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
654 SmallVector<SDValue, 12> MemOpChains;
656 // Walk the register/memloc assignments, inserting copies/loads.
657 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
658 CCValAssign &VA = ArgLocs[i];
659 SDValue Arg = Outs[i].Val;
661 // Promote the value if needed.
662 switch (VA.getLocInfo()) {
663 default: llvm_unreachable("Unknown loc info!");
664 case CCValAssign::Full: break;
665 case CCValAssign::SExt:
666 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
668 case CCValAssign::ZExt:
669 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
671 case CCValAssign::AExt:
672 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
676 // Arguments that can be passed on register must be kept at
679 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
681 assert(VA.isMemLoc());
683 int Offset = VA.getLocMemOffset();
685 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
687 DAG.getConstant(Offset/4, MVT::i32)));
691 // Transform all store nodes into one single node because
692 // all store nodes are independent of each other.
693 if (!MemOpChains.empty())
694 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
695 &MemOpChains[0], MemOpChains.size());
697 // Build a sequence of copy-to-reg nodes chained together with token
698 // chain and flag operands which copy the outgoing args into registers.
699 // The InFlag in necessary since all emited instructions must be
702 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
703 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
704 RegsToPass[i].second, InFlag);
705 InFlag = Chain.getValue(1);
708 // If the callee is a GlobalAddress node (quite common, every direct call is)
709 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
710 // Likewise ExternalSymbol -> TargetExternalSymbol.
711 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
712 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
713 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
714 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
716 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
717 // = Chain, Callee, Reg#1, Reg#2, ...
719 // Returns a chain & a flag for retval copy to use.
720 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
721 SmallVector<SDValue, 8> Ops;
722 Ops.push_back(Chain);
723 Ops.push_back(Callee);
725 // Add argument registers to the end of the list so that they are
726 // known live into the call.
727 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
728 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
729 RegsToPass[i].second.getValueType()));
731 if (InFlag.getNode())
732 Ops.push_back(InFlag);
734 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
735 InFlag = Chain.getValue(1);
737 // Create the CALLSEQ_END node.
738 Chain = DAG.getCALLSEQ_END(Chain,
739 DAG.getConstant(NumBytes, getPointerTy(), true),
740 DAG.getConstant(0, getPointerTy(), true),
742 InFlag = Chain.getValue(1);
744 // Handle result values, copying them out of physregs into vregs that we
746 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
747 Ins, dl, DAG, InVals);
750 /// LowerCallResult - Lower the result values of a call into the
751 /// appropriate copies out of appropriate physical registers.
753 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
754 CallingConv::ID CallConv, bool isVarArg,
755 const SmallVectorImpl<ISD::InputArg> &Ins,
756 DebugLoc dl, SelectionDAG &DAG,
757 SmallVectorImpl<SDValue> &InVals) {
759 // Assign locations to each value returned by this call.
760 SmallVector<CCValAssign, 16> RVLocs;
761 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
762 RVLocs, *DAG.getContext());
764 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
766 // Copy all of the result registers out of their specified physreg.
767 for (unsigned i = 0; i != RVLocs.size(); ++i) {
768 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
769 RVLocs[i].getValVT(), InFlag).getValue(1);
770 InFlag = Chain.getValue(2);
771 InVals.push_back(Chain.getValue(0));
777 //===----------------------------------------------------------------------===//
778 // Formal Arguments Calling Convention Implementation
779 //===----------------------------------------------------------------------===//
781 /// XCore formal arguments implementation
783 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
784 CallingConv::ID CallConv,
786 const SmallVectorImpl<ISD::InputArg> &Ins,
789 SmallVectorImpl<SDValue> &InVals) {
793 llvm_unreachable("Unsupported calling convention");
795 case CallingConv::Fast:
796 return LowerCCCArguments(Chain, CallConv, isVarArg,
797 Ins, dl, DAG, InVals);
801 /// LowerCCCArguments - transform physical registers into
802 /// virtual registers and generate load operations for
803 /// arguments places on the stack.
806 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
807 CallingConv::ID CallConv,
809 const SmallVectorImpl<ISD::InputArg>
813 SmallVectorImpl<SDValue> &InVals) {
814 MachineFunction &MF = DAG.getMachineFunction();
815 MachineFrameInfo *MFI = MF.getFrameInfo();
816 MachineRegisterInfo &RegInfo = MF.getRegInfo();
818 // Assign locations to all of the incoming arguments.
819 SmallVector<CCValAssign, 16> ArgLocs;
820 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
821 ArgLocs, *DAG.getContext());
823 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
825 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
827 unsigned LRSaveSize = StackSlotSize;
829 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
831 CCValAssign &VA = ArgLocs[i];
834 // Arguments passed in registers
835 EVT RegVT = VA.getLocVT();
836 switch (RegVT.getSimpleVT().SimpleTy) {
840 errs() << "LowerFormalArguments Unhandled argument type: "
841 << RegVT.getSimpleVT().SimpleTy << "\n";
846 unsigned VReg = RegInfo.createVirtualRegister(
847 XCore::GRRegsRegisterClass);
848 RegInfo.addLiveIn(VA.getLocReg(), VReg);
849 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
853 assert(VA.isMemLoc());
854 // Load the argument to a virtual register
855 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
856 if (ObjSize > StackSlotSize) {
857 errs() << "LowerFormalArguments Unhandled argument type: "
858 << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
861 // Create the frame index object for this incoming parameter...
862 int FI = MFI->CreateFixedObject(ObjSize,
863 LRSaveSize + VA.getLocMemOffset());
865 // Create the SelectionDAG nodes corresponding to a load
866 //from this parameter
867 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
868 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0));
873 /* Argument registers */
874 static const unsigned ArgRegs[] = {
875 XCore::R0, XCore::R1, XCore::R2, XCore::R3
877 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
878 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
879 array_lengthof(ArgRegs));
880 if (FirstVAReg < array_lengthof(ArgRegs)) {
881 SmallVector<SDValue, 4> MemOps;
883 // Save remaining registers, storing higher register numbers at a higher
885 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
886 // Create a stack slot
887 int FI = MFI->CreateFixedObject(4, offset);
888 if (i == FirstVAReg) {
889 XFI->setVarArgsFrameIndex(FI);
891 offset -= StackSlotSize;
892 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
893 // Move argument from phys reg -> virt reg
894 unsigned VReg = RegInfo.createVirtualRegister(
895 XCore::GRRegsRegisterClass);
896 RegInfo.addLiveIn(ArgRegs[i], VReg);
897 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
898 // Move argument from virt reg -> stack
899 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
900 MemOps.push_back(Store);
903 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
904 &MemOps[0], MemOps.size());
906 // This will point to the next argument passed via stack.
907 XFI->setVarArgsFrameIndex(
908 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
915 //===----------------------------------------------------------------------===//
916 // Return Value Calling Convention Implementation
917 //===----------------------------------------------------------------------===//
920 XCoreTargetLowering::LowerReturn(SDValue Chain,
921 CallingConv::ID CallConv, bool isVarArg,
922 const SmallVectorImpl<ISD::OutputArg> &Outs,
923 DebugLoc dl, SelectionDAG &DAG) {
925 // CCValAssign - represent the assignment of
926 // the return value to a location
927 SmallVector<CCValAssign, 16> RVLocs;
929 // CCState - Info about the registers and stack slot.
930 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
931 RVLocs, *DAG.getContext());
933 // Analize return values.
934 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
936 // If this is the first return lowered for this function, add
937 // the regs to the liveout set for the function.
938 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
939 for (unsigned i = 0; i != RVLocs.size(); ++i)
940 if (RVLocs[i].isRegLoc())
941 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
946 // Copy the result values into the output registers.
947 for (unsigned i = 0; i != RVLocs.size(); ++i) {
948 CCValAssign &VA = RVLocs[i];
949 assert(VA.isRegLoc() && "Can only return in registers!");
951 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
954 // guarantee that all emitted copies are
955 // stuck together, avoiding something bad
956 Flag = Chain.getValue(1);
959 // Return on XCore is always a "retsp 0"
961 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
962 Chain, DAG.getConstant(0, MVT::i32), Flag);
964 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
965 Chain, DAG.getConstant(0, MVT::i32));
968 //===----------------------------------------------------------------------===//
969 // Other Lowering Code
970 //===----------------------------------------------------------------------===//
973 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
974 MachineBasicBlock *BB,
975 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
976 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
977 DebugLoc dl = MI->getDebugLoc();
978 assert((MI->getOpcode() == XCore::SELECT_CC) &&
979 "Unexpected instr type to insert");
981 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
982 // control-flow pattern. The incoming instruction knows the destination vreg
983 // to set, the condition code register to branch on, the true/false values to
984 // select between, and a branch opcode to use.
985 const BasicBlock *LLVM_BB = BB->getBasicBlock();
986 MachineFunction::iterator It = BB;
994 // fallthrough --> copy0MBB
995 MachineBasicBlock *thisMBB = BB;
996 MachineFunction *F = BB->getParent();
997 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
998 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
999 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1000 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1001 F->insert(It, copy0MBB);
1002 F->insert(It, sinkMBB);
1003 // Update machine-CFG edges by first adding all successors of the current
1004 // block to the new block which will contain the Phi node for the select.
1005 // Also inform sdisel of the edge changes.
1006 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1007 E = BB->succ_end(); I != E; ++I) {
1008 EM->insert(std::make_pair(*I, sinkMBB));
1009 sinkMBB->addSuccessor(*I);
1011 // Next, remove all successors of the current block, and add the true
1012 // and fallthrough blocks as its successors.
1013 while (!BB->succ_empty())
1014 BB->removeSuccessor(BB->succ_begin());
1015 // Next, add the true and fallthrough blocks as its successors.
1016 BB->addSuccessor(copy0MBB);
1017 BB->addSuccessor(sinkMBB);
1020 // %FalseValue = ...
1021 // # fallthrough to sinkMBB
1024 // Update machine-CFG edges
1025 BB->addSuccessor(sinkMBB);
1028 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1031 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1032 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1033 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1035 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1039 //===----------------------------------------------------------------------===//
1040 // Target Optimization Hooks
1041 //===----------------------------------------------------------------------===//
1043 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1044 DAGCombinerInfo &DCI) const {
1045 SelectionDAG &DAG = DCI.DAG;
1046 DebugLoc dl = N->getDebugLoc();
1047 switch (N->getOpcode()) {
1050 // Replace unaligned store of unaligned load with memmove.
1051 StoreSDNode *ST = cast<StoreSDNode>(N);
1052 if (!DCI.isBeforeLegalize() ||
1053 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1054 ST->isVolatile() || ST->isIndexed()) {
1057 SDValue Chain = ST->getChain();
1059 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1060 if (StoreBits % 8) {
1063 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1064 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1065 unsigned Alignment = ST->getAlignment();
1066 if (Alignment >= ABIAlignment) {
1070 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1071 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1072 LD->getAlignment() == Alignment &&
1073 !LD->isVolatile() && !LD->isIndexed() &&
1074 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1075 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1077 DAG.getConstant(StoreBits/8, MVT::i32),
1078 Alignment, ST->getSrcValue(),
1079 ST->getSrcValueOffset(), LD->getSrcValue(),
1080 LD->getSrcValueOffset());
1089 //===----------------------------------------------------------------------===//
1090 // Addressing mode description hooks
1091 //===----------------------------------------------------------------------===//
1093 static inline bool isImmUs(int64_t val)
1095 return (val >= 0 && val <= 11);
1098 static inline bool isImmUs2(int64_t val)
1100 return (val%2 == 0 && isImmUs(val/2));
1103 static inline bool isImmUs4(int64_t val)
1105 return (val%4 == 0 && isImmUs(val/4));
1108 /// isLegalAddressingMode - Return true if the addressing mode represented
1109 /// by AM is legal for this target, for a load/store of the specified type.
1111 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1112 const Type *Ty) const {
1113 // Be conservative with void
1114 // FIXME: Can we be more aggressive?
1115 if (Ty->getTypeID() == Type::VoidTyID)
1118 const TargetData *TD = TM.getTargetData();
1119 unsigned Size = TD->getTypeAllocSize(Ty);
1121 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1128 if (AM.Scale == 0) {
1129 return isImmUs(AM.BaseOffs);
1132 return AM.Scale == 1 && AM.BaseOffs == 0;
1136 if (AM.Scale == 0) {
1137 return isImmUs2(AM.BaseOffs);
1140 return AM.Scale == 2 && AM.BaseOffs == 0;
1143 if (AM.Scale == 0) {
1144 return isImmUs4(AM.BaseOffs);
1147 return AM.Scale == 4 && AM.BaseOffs == 0;
1153 //===----------------------------------------------------------------------===//
1154 // XCore Inline Assembly Support
1155 //===----------------------------------------------------------------------===//
1157 std::vector<unsigned> XCoreTargetLowering::
1158 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1161 if (Constraint.size() != 1)
1162 return std::vector<unsigned>();
1164 switch (Constraint[0]) {
1167 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1168 XCore::R3, XCore::R4, XCore::R5,
1169 XCore::R6, XCore::R7, XCore::R8,
1170 XCore::R9, XCore::R10, XCore::R11, 0);
1173 return std::vector<unsigned>();