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/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAGISel.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #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 case XCoreISD::LADD : return "XCoreISD::LADD";
54 case XCoreISD::LSUB : return "XCoreISD::LSUB";
55 case XCoreISD::LMUL : return "XCoreISD::LMUL";
56 case XCoreISD::MACCU : return "XCoreISD::MACCU";
57 case XCoreISD::MACCS : return "XCoreISD::MACCS";
58 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
59 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
60 default : return NULL;
64 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
65 : TargetLowering(XTM, new XCoreTargetObjectFile()),
67 Subtarget(*XTM.getSubtargetImpl()) {
69 // Set up the register classes.
70 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
72 // Compute derived properties from the register classes
73 computeRegisterProperties();
75 // Division is expensive
76 setIntDivIsCheap(false);
78 setStackPointerRegisterToSaveRestore(XCore::SP);
80 setSchedulingPreference(Sched::RegPressure);
82 // Use i32 for setcc operations results (slt, sgt, ...).
83 setBooleanContents(ZeroOrOneBooleanContent);
85 // XCore does not have the NodeTypes below.
86 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
87 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
88 setOperationAction(ISD::ADDC, MVT::i32, Expand);
89 setOperationAction(ISD::ADDE, MVT::i32, Expand);
90 setOperationAction(ISD::SUBC, MVT::i32, Expand);
91 setOperationAction(ISD::SUBE, MVT::i32, Expand);
93 // Stop the combiner recombining select and set_cc
94 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
97 setOperationAction(ISD::ADD, MVT::i64, Custom);
98 setOperationAction(ISD::SUB, MVT::i64, Custom);
99 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
100 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
101 setOperationAction(ISD::MULHS, MVT::i32, Expand);
102 setOperationAction(ISD::MULHU, MVT::i32, Expand);
103 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
104 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
105 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
109 setOperationAction(ISD::ROTL , MVT::i32, Expand);
110 setOperationAction(ISD::ROTR , MVT::i32, Expand);
112 setOperationAction(ISD::TRAP, MVT::Other, Legal);
115 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
117 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
118 setOperationAction(ISD::BlockAddress, 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);
149 // TRAMPOLINE is custom lowered.
150 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
152 maxStoresPerMemset = maxStoresPerMemsetOptSize = 4;
153 maxStoresPerMemmove = maxStoresPerMemmoveOptSize
154 = maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 2;
156 // We have target-specific dag combine patterns for the following nodes:
157 setTargetDAGCombine(ISD::STORE);
158 setTargetDAGCombine(ISD::ADD);
161 SDValue XCoreTargetLowering::
162 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
163 switch (Op.getOpcode())
165 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
166 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
167 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
168 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
169 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
170 case ISD::LOAD: return LowerLOAD(Op, DAG);
171 case ISD::STORE: return LowerSTORE(Op, DAG);
172 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
173 case ISD::VAARG: return LowerVAARG(Op, DAG);
174 case ISD::VASTART: return LowerVASTART(Op, DAG);
175 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
176 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
177 // FIXME: Remove these when LegalizeDAGTypes lands.
179 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
180 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
181 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
183 llvm_unreachable("unimplemented operand");
188 /// ReplaceNodeResults - Replace the results of node with an illegal result
189 /// type with new values built out of custom code.
190 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
191 SmallVectorImpl<SDValue>&Results,
192 SelectionDAG &DAG) const {
193 switch (N->getOpcode()) {
195 llvm_unreachable("Don't know how to custom expand this!");
199 Results.push_back(ExpandADDSUB(N, DAG));
204 /// getFunctionAlignment - Return the Log2 alignment of this function.
205 unsigned XCoreTargetLowering::
206 getFunctionAlignment(const Function *) const {
210 //===----------------------------------------------------------------------===//
211 // Misc Lower Operation implementation
212 //===----------------------------------------------------------------------===//
214 SDValue XCoreTargetLowering::
215 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
217 DebugLoc dl = Op.getDebugLoc();
218 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
219 Op.getOperand(3), Op.getOperand(4));
220 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
224 SDValue XCoreTargetLowering::
225 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
226 SelectionDAG &DAG) const
228 // FIXME there is no actual debug info here
229 DebugLoc dl = GA.getDebugLoc();
230 if (isa<Function>(GV)) {
231 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
233 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
235 // If GV is an alias then use the aliasee to determine constness
236 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
237 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
239 bool isConst = GVar && GVar->isConstant();
241 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
243 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
246 SDValue XCoreTargetLowering::
247 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
249 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
250 SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
251 // If it's a debug information descriptor, don't mess with it.
252 if (DAG.isVerifiedDebugInfoDesc(Op))
254 return getGlobalAddressWrapper(GA, GV, DAG);
257 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
258 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
259 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
262 static inline bool isZeroLengthArray(const Type *Ty) {
263 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
264 return AT && (AT->getNumElements() == 0);
267 SDValue XCoreTargetLowering::
268 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
270 // FIXME there isn't really debug info here
271 DebugLoc dl = Op.getDebugLoc();
272 // transform to label + getid() * size
273 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
274 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
275 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
277 // If GV is an alias then use the aliasee to determine size
278 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
279 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
282 llvm_unreachable("Thread local object not a GlobalVariable?");
285 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
286 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
288 errs() << "Size of thread local object " << GVar->getName()
293 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
294 const TargetData *TD = TM.getTargetData();
295 unsigned Size = TD->getTypeAllocSize(Ty);
296 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
297 DAG.getConstant(Size, MVT::i32));
298 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
301 SDValue XCoreTargetLowering::
302 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
304 DebugLoc DL = Op.getDebugLoc();
306 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
307 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
309 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
312 SDValue XCoreTargetLowering::
313 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
315 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
316 // FIXME there isn't really debug info here
317 DebugLoc dl = CP->getDebugLoc();
318 EVT PtrVT = Op.getValueType();
320 if (CP->isMachineConstantPoolEntry()) {
321 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
324 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
327 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
330 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
331 return MachineJumpTableInfo::EK_Inline;
334 SDValue XCoreTargetLowering::
335 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
337 SDValue Chain = Op.getOperand(0);
338 SDValue Table = Op.getOperand(1);
339 SDValue Index = Op.getOperand(2);
340 DebugLoc dl = Op.getDebugLoc();
341 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
342 unsigned JTI = JT->getIndex();
343 MachineFunction &MF = DAG.getMachineFunction();
344 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
345 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
347 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
348 if (NumEntries <= 32) {
349 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
351 assert((NumEntries >> 31) == 0);
352 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
353 DAG.getConstant(1, MVT::i32));
354 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
359 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
362 if (Addr.getOpcode() != ISD::ADD) {
365 ConstantSDNode *CN = 0;
366 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
369 int64_t off = CN->getSExtValue();
370 const SDValue &Base = Addr.getOperand(0);
371 const SDValue *Root = &Base;
372 if (Base.getOpcode() == ISD::ADD &&
373 Base.getOperand(1).getOpcode() == ISD::SHL) {
374 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
376 if (CN && (CN->getSExtValue() >= 2)) {
377 Root = &Base.getOperand(0);
380 if (isa<FrameIndexSDNode>(*Root)) {
381 // All frame indicies are word aligned
386 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
387 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
388 // All dp / cp relative addresses are word aligned
396 SDValue XCoreTargetLowering::
397 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
398 LoadSDNode *LD = cast<LoadSDNode>(Op);
399 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
400 "Unexpected extension type");
401 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
402 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
405 unsigned ABIAlignment = getTargetData()->
406 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
407 // Leave aligned load alone.
408 if (LD->getAlignment() >= ABIAlignment)
411 SDValue Chain = LD->getChain();
412 SDValue BasePtr = LD->getBasePtr();
413 DebugLoc DL = Op.getDebugLoc();
417 if (!LD->isVolatile() &&
418 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
419 if (Offset % 4 == 0) {
420 // We've managed to infer better alignment information than the load
421 // already has. Use an aligned load.
423 return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
424 MachinePointerInfo(),
428 // ldw low, base[offset >> 2]
429 // ldw high, base[(offset >> 2) + 1]
430 // shr low_shifted, low, (offset & 0x3) * 8
431 // shl high_shifted, high, 32 - (offset & 0x3) * 8
432 // or result, low_shifted, high_shifted
433 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
434 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
435 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
436 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
438 SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
439 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
441 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
442 LowAddr, MachinePointerInfo(), false, false, 0);
443 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
444 HighAddr, MachinePointerInfo(), false, false, 0);
445 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
446 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
447 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
448 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
450 SDValue Ops[] = { Result, Chain };
451 return DAG.getMergeValues(Ops, 2, DL);
454 if (LD->getAlignment() == 2) {
455 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
456 BasePtr, LD->getPointerInfo(), MVT::i16,
457 LD->isVolatile(), LD->isNonTemporal(), 2);
458 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
459 DAG.getConstant(2, MVT::i32));
460 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
462 LD->getPointerInfo().getWithOffset(2),
463 MVT::i16, LD->isVolatile(),
464 LD->isNonTemporal(), 2);
465 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
466 DAG.getConstant(16, MVT::i32));
467 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
468 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
470 SDValue Ops[] = { Result, Chain };
471 return DAG.getMergeValues(Ops, 2, DL);
474 // Lower to a call to __misaligned_load(BasePtr).
475 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
476 TargetLowering::ArgListTy Args;
477 TargetLowering::ArgListEntry Entry;
480 Entry.Node = BasePtr;
481 Args.push_back(Entry);
483 std::pair<SDValue, SDValue> CallResult =
484 LowerCallTo(Chain, IntPtrTy, false, false,
485 false, false, 0, CallingConv::C, false,
486 /*isReturnValueUsed=*/true,
487 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
491 { CallResult.first, CallResult.second };
493 return DAG.getMergeValues(Ops, 2, DL);
496 SDValue XCoreTargetLowering::
497 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
499 StoreSDNode *ST = cast<StoreSDNode>(Op);
500 assert(!ST->isTruncatingStore() && "Unexpected store type");
501 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
502 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
505 unsigned ABIAlignment = getTargetData()->
506 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
507 // Leave aligned store alone.
508 if (ST->getAlignment() >= ABIAlignment) {
511 SDValue Chain = ST->getChain();
512 SDValue BasePtr = ST->getBasePtr();
513 SDValue Value = ST->getValue();
514 DebugLoc dl = Op.getDebugLoc();
516 if (ST->getAlignment() == 2) {
518 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
519 DAG.getConstant(16, MVT::i32));
520 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
521 ST->getPointerInfo(), MVT::i16,
522 ST->isVolatile(), ST->isNonTemporal(),
524 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
525 DAG.getConstant(2, MVT::i32));
526 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
527 ST->getPointerInfo().getWithOffset(2),
528 MVT::i16, ST->isVolatile(),
529 ST->isNonTemporal(), 2);
530 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
533 // Lower to a call to __misaligned_store(BasePtr, Value).
534 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
535 TargetLowering::ArgListTy Args;
536 TargetLowering::ArgListEntry Entry;
539 Entry.Node = BasePtr;
540 Args.push_back(Entry);
543 Args.push_back(Entry);
545 std::pair<SDValue, SDValue> CallResult =
546 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
547 false, false, 0, CallingConv::C, false,
548 /*isReturnValueUsed=*/true,
549 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
552 return CallResult.second;
555 SDValue XCoreTargetLowering::
556 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
558 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
559 "Unexpected operand to lower!");
560 DebugLoc dl = Op.getDebugLoc();
561 SDValue LHS = Op.getOperand(0);
562 SDValue RHS = Op.getOperand(1);
563 SDValue Zero = DAG.getConstant(0, MVT::i32);
564 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
565 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
567 SDValue Lo(Hi.getNode(), 1);
568 SDValue Ops[] = { Lo, Hi };
569 return DAG.getMergeValues(Ops, 2, dl);
572 SDValue XCoreTargetLowering::
573 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
575 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
576 "Unexpected operand to lower!");
577 DebugLoc dl = Op.getDebugLoc();
578 SDValue LHS = Op.getOperand(0);
579 SDValue RHS = Op.getOperand(1);
580 SDValue Zero = DAG.getConstant(0, MVT::i32);
581 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
582 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
584 SDValue Lo(Hi.getNode(), 1);
585 SDValue Ops[] = { Lo, Hi };
586 return DAG.getMergeValues(Ops, 2, dl);
589 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
590 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
591 /// each intermediate result in the calculation must also have a single use.
592 /// If the Op is in the correct form the constituent parts are written to Mul0,
593 /// Mul1, Addend0 and Addend1.
595 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
596 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
598 if (Op.getOpcode() != ISD::ADD)
600 SDValue N0 = Op.getOperand(0);
601 SDValue N1 = Op.getOperand(1);
604 if (N0.getOpcode() == ISD::ADD) {
607 } else if (N1.getOpcode() == ISD::ADD) {
613 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
615 if (OtherOp.getOpcode() == ISD::MUL) {
616 // add(add(a,b),mul(x,y))
617 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
619 Mul0 = OtherOp.getOperand(0);
620 Mul1 = OtherOp.getOperand(1);
621 Addend0 = AddOp.getOperand(0);
622 Addend1 = AddOp.getOperand(1);
625 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
626 // add(add(mul(x,y),a),b)
627 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
629 Mul0 = AddOp.getOperand(0).getOperand(0);
630 Mul1 = AddOp.getOperand(0).getOperand(1);
631 Addend0 = AddOp.getOperand(1);
635 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
636 // add(add(a,mul(x,y)),b)
637 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
639 Mul0 = AddOp.getOperand(1).getOperand(0);
640 Mul1 = AddOp.getOperand(1).getOperand(1);
641 Addend0 = AddOp.getOperand(0);
648 SDValue XCoreTargetLowering::
649 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
653 if (N->getOperand(0).getOpcode() == ISD::MUL) {
654 Mul = N->getOperand(0);
655 Other = N->getOperand(1);
656 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
657 Mul = N->getOperand(1);
658 Other = N->getOperand(0);
662 DebugLoc dl = N->getDebugLoc();
663 SDValue LL, RL, AddendL, AddendH;
664 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
665 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
666 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
667 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
668 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
669 Other, DAG.getConstant(0, MVT::i32));
670 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
671 Other, DAG.getConstant(1, MVT::i32));
672 APInt HighMask = APInt::getHighBitsSet(64, 32);
673 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
674 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
675 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
676 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
677 // The inputs are both zero-extended.
678 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
679 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
681 SDValue Lo(Hi.getNode(), 1);
682 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
684 if (LHSSB > 32 && RHSSB > 32) {
685 // The inputs are both sign-extended.
686 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
687 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
689 SDValue Lo(Hi.getNode(), 1);
690 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
693 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
694 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
695 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
696 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
697 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
698 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
700 SDValue Lo(Hi.getNode(), 1);
701 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
702 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
703 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
704 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
705 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
708 SDValue XCoreTargetLowering::
709 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
711 assert(N->getValueType(0) == MVT::i64 &&
712 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
713 "Unknown operand to lower!");
715 if (N->getOpcode() == ISD::ADD) {
716 SDValue Result = TryExpandADDWithMul(N, DAG);
717 if (Result.getNode() != 0)
721 DebugLoc dl = N->getDebugLoc();
723 // Extract components
724 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
725 N->getOperand(0), DAG.getConstant(0, MVT::i32));
726 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
727 N->getOperand(0), DAG.getConstant(1, MVT::i32));
728 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
729 N->getOperand(1), DAG.getConstant(0, MVT::i32));
730 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
731 N->getOperand(1), DAG.getConstant(1, MVT::i32));
734 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
736 SDValue Zero = DAG.getConstant(0, MVT::i32);
737 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
739 SDValue Lo(Carry.getNode(), 1);
741 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
743 SDValue Hi(Ignored.getNode(), 1);
745 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
748 SDValue XCoreTargetLowering::
749 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
751 llvm_unreachable("unimplemented");
752 // FIX Arguments passed by reference need a extra dereference.
753 SDNode *Node = Op.getNode();
754 DebugLoc dl = Node->getDebugLoc();
755 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
756 EVT VT = Node->getValueType(0);
757 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
758 Node->getOperand(1), MachinePointerInfo(V),
760 // Increment the pointer, VAList, to the next vararg
761 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
762 DAG.getConstant(VT.getSizeInBits(),
764 // Store the incremented VAList to the legalized pointer
765 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1),
766 MachinePointerInfo(V), false, false, 0);
767 // Load the actual argument out of the pointer VAList
768 return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
772 SDValue XCoreTargetLowering::
773 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
775 DebugLoc dl = Op.getDebugLoc();
776 // vastart stores the address of the VarArgsFrameIndex slot into the
777 // memory location argument
778 MachineFunction &MF = DAG.getMachineFunction();
779 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
780 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
781 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
782 MachinePointerInfo(), false, false, 0);
785 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
786 SelectionDAG &DAG) const {
787 DebugLoc dl = Op.getDebugLoc();
788 // Depths > 0 not supported yet!
789 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
792 MachineFunction &MF = DAG.getMachineFunction();
793 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
794 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
795 RegInfo->getFrameRegister(MF), MVT::i32);
798 SDValue XCoreTargetLowering::
799 LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
800 SDValue Chain = Op.getOperand(0);
801 SDValue Trmp = Op.getOperand(1); // trampoline
802 SDValue FPtr = Op.getOperand(2); // nested function
803 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
805 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
808 // LDAPF_u10 r11, nest
809 // LDW_2rus r11, r11[0]
810 // STWSP_ru6 r11, sp[0]
811 // LDAPF_u10 r11, fptr
812 // LDW_2rus r11, r11[0]
818 SDValue OutChains[5];
822 DebugLoc dl = Op.getDebugLoc();
823 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
824 Addr, MachinePointerInfo(TrmpAddr), false, false,
827 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
828 DAG.getConstant(4, MVT::i32));
829 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
830 Addr, MachinePointerInfo(TrmpAddr, 4), false,
833 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
834 DAG.getConstant(8, MVT::i32));
835 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
836 Addr, MachinePointerInfo(TrmpAddr, 8), false,
839 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
840 DAG.getConstant(12, MVT::i32));
841 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
842 MachinePointerInfo(TrmpAddr, 12), false, false,
845 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
846 DAG.getConstant(16, MVT::i32));
847 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
848 MachinePointerInfo(TrmpAddr, 16), false, false,
852 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5) };
853 return DAG.getMergeValues(Ops, 2, dl);
856 //===----------------------------------------------------------------------===//
857 // Calling Convention Implementation
858 //===----------------------------------------------------------------------===//
860 #include "XCoreGenCallingConv.inc"
862 //===----------------------------------------------------------------------===//
863 // Call Calling Convention Implementation
864 //===----------------------------------------------------------------------===//
866 /// XCore call implementation
868 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
869 CallingConv::ID CallConv, bool isVarArg,
871 const SmallVectorImpl<ISD::OutputArg> &Outs,
872 const SmallVectorImpl<SDValue> &OutVals,
873 const SmallVectorImpl<ISD::InputArg> &Ins,
874 DebugLoc dl, SelectionDAG &DAG,
875 SmallVectorImpl<SDValue> &InVals) const {
876 // XCore target does not yet support tail call optimization.
879 // For now, only CallingConv::C implemented
883 llvm_unreachable("Unsupported calling convention");
884 case CallingConv::Fast:
886 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
887 Outs, OutVals, Ins, dl, DAG, InVals);
891 /// LowerCCCCallTo - functions arguments are copied from virtual
892 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
893 /// CALLSEQ_END are emitted.
894 /// TODO: isTailCall, sret.
896 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
897 CallingConv::ID CallConv, bool isVarArg,
899 const SmallVectorImpl<ISD::OutputArg> &Outs,
900 const SmallVectorImpl<SDValue> &OutVals,
901 const SmallVectorImpl<ISD::InputArg> &Ins,
902 DebugLoc dl, SelectionDAG &DAG,
903 SmallVectorImpl<SDValue> &InVals) const {
905 // Analyze operands of the call, assigning locations to each operand.
906 SmallVector<CCValAssign, 16> ArgLocs;
907 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
908 ArgLocs, *DAG.getContext());
910 // The ABI dictates there should be one stack slot available to the callee
911 // on function entry (for saving lr).
912 CCInfo.AllocateStack(4, 4);
914 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
916 // Get a count of how many bytes are to be pushed on the stack.
917 unsigned NumBytes = CCInfo.getNextStackOffset();
919 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
920 getPointerTy(), true));
922 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
923 SmallVector<SDValue, 12> MemOpChains;
925 // Walk the register/memloc assignments, inserting copies/loads.
926 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
927 CCValAssign &VA = ArgLocs[i];
928 SDValue Arg = OutVals[i];
930 // Promote the value if needed.
931 switch (VA.getLocInfo()) {
932 default: llvm_unreachable("Unknown loc info!");
933 case CCValAssign::Full: break;
934 case CCValAssign::SExt:
935 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
937 case CCValAssign::ZExt:
938 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
940 case CCValAssign::AExt:
941 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
945 // Arguments that can be passed on register must be kept at
948 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
950 assert(VA.isMemLoc());
952 int Offset = VA.getLocMemOffset();
954 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
956 DAG.getConstant(Offset/4, MVT::i32)));
960 // Transform all store nodes into one single node because
961 // all store nodes are independent of each other.
962 if (!MemOpChains.empty())
963 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
964 &MemOpChains[0], MemOpChains.size());
966 // Build a sequence of copy-to-reg nodes chained together with token
967 // chain and flag operands which copy the outgoing args into registers.
968 // The InFlag in necessary since all emitted instructions must be
971 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
972 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
973 RegsToPass[i].second, InFlag);
974 InFlag = Chain.getValue(1);
977 // If the callee is a GlobalAddress node (quite common, every direct call is)
978 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
979 // Likewise ExternalSymbol -> TargetExternalSymbol.
980 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
981 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
982 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
983 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
985 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
986 // = Chain, Callee, Reg#1, Reg#2, ...
988 // Returns a chain & a flag for retval copy to use.
989 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
990 SmallVector<SDValue, 8> Ops;
991 Ops.push_back(Chain);
992 Ops.push_back(Callee);
994 // Add argument registers to the end of the list so that they are
995 // known live into the call.
996 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
997 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
998 RegsToPass[i].second.getValueType()));
1000 if (InFlag.getNode())
1001 Ops.push_back(InFlag);
1003 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1004 InFlag = Chain.getValue(1);
1006 // Create the CALLSEQ_END node.
1007 Chain = DAG.getCALLSEQ_END(Chain,
1008 DAG.getConstant(NumBytes, getPointerTy(), true),
1009 DAG.getConstant(0, getPointerTy(), true),
1011 InFlag = Chain.getValue(1);
1013 // Handle result values, copying them out of physregs into vregs that we
1015 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1016 Ins, dl, DAG, InVals);
1019 /// LowerCallResult - Lower the result values of a call into the
1020 /// appropriate copies out of appropriate physical registers.
1022 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1023 CallingConv::ID CallConv, bool isVarArg,
1024 const SmallVectorImpl<ISD::InputArg> &Ins,
1025 DebugLoc dl, SelectionDAG &DAG,
1026 SmallVectorImpl<SDValue> &InVals) const {
1028 // Assign locations to each value returned by this call.
1029 SmallVector<CCValAssign, 16> RVLocs;
1030 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1031 RVLocs, *DAG.getContext());
1033 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1035 // Copy all of the result registers out of their specified physreg.
1036 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1037 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1038 RVLocs[i].getValVT(), InFlag).getValue(1);
1039 InFlag = Chain.getValue(2);
1040 InVals.push_back(Chain.getValue(0));
1046 //===----------------------------------------------------------------------===//
1047 // Formal Arguments Calling Convention Implementation
1048 //===----------------------------------------------------------------------===//
1050 /// XCore formal arguments implementation
1052 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1053 CallingConv::ID CallConv,
1055 const SmallVectorImpl<ISD::InputArg> &Ins,
1058 SmallVectorImpl<SDValue> &InVals)
1063 llvm_unreachable("Unsupported calling convention");
1064 case CallingConv::C:
1065 case CallingConv::Fast:
1066 return LowerCCCArguments(Chain, CallConv, isVarArg,
1067 Ins, dl, DAG, InVals);
1071 /// LowerCCCArguments - transform physical registers into
1072 /// virtual registers and generate load operations for
1073 /// arguments places on the stack.
1076 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1077 CallingConv::ID CallConv,
1079 const SmallVectorImpl<ISD::InputArg>
1083 SmallVectorImpl<SDValue> &InVals) const {
1084 MachineFunction &MF = DAG.getMachineFunction();
1085 MachineFrameInfo *MFI = MF.getFrameInfo();
1086 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1088 // Assign locations to all of the incoming arguments.
1089 SmallVector<CCValAssign, 16> ArgLocs;
1090 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1091 ArgLocs, *DAG.getContext());
1093 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1095 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1097 unsigned LRSaveSize = StackSlotSize;
1099 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1101 CCValAssign &VA = ArgLocs[i];
1103 if (VA.isRegLoc()) {
1104 // Arguments passed in registers
1105 EVT RegVT = VA.getLocVT();
1106 switch (RegVT.getSimpleVT().SimpleTy) {
1110 errs() << "LowerFormalArguments Unhandled argument type: "
1111 << RegVT.getSimpleVT().SimpleTy << "\n";
1113 llvm_unreachable(0);
1116 unsigned VReg = RegInfo.createVirtualRegister(
1117 XCore::GRRegsRegisterClass);
1118 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1119 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1123 assert(VA.isMemLoc());
1124 // Load the argument to a virtual register
1125 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1126 if (ObjSize > StackSlotSize) {
1127 errs() << "LowerFormalArguments Unhandled argument type: "
1128 << EVT(VA.getLocVT()).getEVTString()
1131 // Create the frame index object for this incoming parameter...
1132 int FI = MFI->CreateFixedObject(ObjSize,
1133 LRSaveSize + VA.getLocMemOffset(),
1136 // Create the SelectionDAG nodes corresponding to a load
1137 //from this parameter
1138 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1139 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1140 MachinePointerInfo::getFixedStack(FI),
1146 /* Argument registers */
1147 static const unsigned ArgRegs[] = {
1148 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1150 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1151 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1152 array_lengthof(ArgRegs));
1153 if (FirstVAReg < array_lengthof(ArgRegs)) {
1154 SmallVector<SDValue, 4> MemOps;
1156 // Save remaining registers, storing higher register numbers at a higher
1158 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
1159 // Create a stack slot
1160 int FI = MFI->CreateFixedObject(4, offset, true);
1161 if (i == FirstVAReg) {
1162 XFI->setVarArgsFrameIndex(FI);
1164 offset -= StackSlotSize;
1165 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1166 // Move argument from phys reg -> virt reg
1167 unsigned VReg = RegInfo.createVirtualRegister(
1168 XCore::GRRegsRegisterClass);
1169 RegInfo.addLiveIn(ArgRegs[i], VReg);
1170 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1171 // Move argument from virt reg -> stack
1172 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1173 MachinePointerInfo(), false, false, 0);
1174 MemOps.push_back(Store);
1176 if (!MemOps.empty())
1177 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1178 &MemOps[0], MemOps.size());
1180 // This will point to the next argument passed via stack.
1181 XFI->setVarArgsFrameIndex(
1182 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1190 //===----------------------------------------------------------------------===//
1191 // Return Value Calling Convention Implementation
1192 //===----------------------------------------------------------------------===//
1194 bool XCoreTargetLowering::
1195 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1196 const SmallVectorImpl<ISD::OutputArg> &Outs,
1197 LLVMContext &Context) const {
1198 SmallVector<CCValAssign, 16> RVLocs;
1199 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1201 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1205 XCoreTargetLowering::LowerReturn(SDValue Chain,
1206 CallingConv::ID CallConv, bool isVarArg,
1207 const SmallVectorImpl<ISD::OutputArg> &Outs,
1208 const SmallVectorImpl<SDValue> &OutVals,
1209 DebugLoc dl, SelectionDAG &DAG) const {
1211 // CCValAssign - represent the assignment of
1212 // the return value to a location
1213 SmallVector<CCValAssign, 16> RVLocs;
1215 // CCState - Info about the registers and stack slot.
1216 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1217 RVLocs, *DAG.getContext());
1219 // Analize return values.
1220 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1222 // If this is the first return lowered for this function, add
1223 // the regs to the liveout set for the function.
1224 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1225 for (unsigned i = 0; i != RVLocs.size(); ++i)
1226 if (RVLocs[i].isRegLoc())
1227 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1232 // Copy the result values into the output registers.
1233 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1234 CCValAssign &VA = RVLocs[i];
1235 assert(VA.isRegLoc() && "Can only return in registers!");
1237 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1240 // guarantee that all emitted copies are
1241 // stuck together, avoiding something bad
1242 Flag = Chain.getValue(1);
1245 // Return on XCore is always a "retsp 0"
1247 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1248 Chain, DAG.getConstant(0, MVT::i32), Flag);
1250 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1251 Chain, DAG.getConstant(0, MVT::i32));
1254 //===----------------------------------------------------------------------===//
1255 // Other Lowering Code
1256 //===----------------------------------------------------------------------===//
1259 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1260 MachineBasicBlock *BB) const {
1261 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1262 DebugLoc dl = MI->getDebugLoc();
1263 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1264 "Unexpected instr type to insert");
1266 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1267 // control-flow pattern. The incoming instruction knows the destination vreg
1268 // to set, the condition code register to branch on, the true/false values to
1269 // select between, and a branch opcode to use.
1270 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1271 MachineFunction::iterator It = BB;
1277 // cmpTY ccX, r1, r2
1279 // fallthrough --> copy0MBB
1280 MachineBasicBlock *thisMBB = BB;
1281 MachineFunction *F = BB->getParent();
1282 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1283 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1284 F->insert(It, copy0MBB);
1285 F->insert(It, sinkMBB);
1287 // Transfer the remainder of BB and its successor edges to sinkMBB.
1288 sinkMBB->splice(sinkMBB->begin(), BB,
1289 llvm::next(MachineBasicBlock::iterator(MI)),
1291 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1293 // Next, add the true and fallthrough blocks as its successors.
1294 BB->addSuccessor(copy0MBB);
1295 BB->addSuccessor(sinkMBB);
1297 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1298 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1301 // %FalseValue = ...
1302 // # fallthrough to sinkMBB
1305 // Update machine-CFG edges
1306 BB->addSuccessor(sinkMBB);
1309 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1312 BuildMI(*BB, BB->begin(), dl,
1313 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1314 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1315 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1317 MI->eraseFromParent(); // The pseudo instruction is gone now.
1321 //===----------------------------------------------------------------------===//
1322 // Target Optimization Hooks
1323 //===----------------------------------------------------------------------===//
1325 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1326 DAGCombinerInfo &DCI) const {
1327 SelectionDAG &DAG = DCI.DAG;
1328 DebugLoc dl = N->getDebugLoc();
1329 switch (N->getOpcode()) {
1331 case XCoreISD::LADD: {
1332 SDValue N0 = N->getOperand(0);
1333 SDValue N1 = N->getOperand(1);
1334 SDValue N2 = N->getOperand(2);
1335 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1336 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1337 EVT VT = N0.getValueType();
1339 // canonicalize constant to RHS
1341 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1343 // fold (ladd 0, 0, x) -> 0, x & 1
1344 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1345 SDValue Carry = DAG.getConstant(0, VT);
1346 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1347 DAG.getConstant(1, VT));
1348 SDValue Ops [] = { Carry, Result };
1349 return DAG.getMergeValues(Ops, 2, dl);
1352 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1354 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1355 APInt KnownZero, KnownOne;
1356 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1357 VT.getSizeInBits() - 1);
1358 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1359 if (KnownZero == Mask) {
1360 SDValue Carry = DAG.getConstant(0, VT);
1361 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1362 SDValue Ops [] = { Carry, Result };
1363 return DAG.getMergeValues(Ops, 2, dl);
1368 case XCoreISD::LSUB: {
1369 SDValue N0 = N->getOperand(0);
1370 SDValue N1 = N->getOperand(1);
1371 SDValue N2 = N->getOperand(2);
1372 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1373 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1374 EVT VT = N0.getValueType();
1376 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1377 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1378 APInt KnownZero, KnownOne;
1379 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1380 VT.getSizeInBits() - 1);
1381 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1382 if (KnownZero == Mask) {
1383 SDValue Borrow = N2;
1384 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1385 DAG.getConstant(0, VT), N2);
1386 SDValue Ops [] = { Borrow, Result };
1387 return DAG.getMergeValues(Ops, 2, dl);
1391 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1393 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1394 APInt KnownZero, KnownOne;
1395 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1396 VT.getSizeInBits() - 1);
1397 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1398 if (KnownZero == Mask) {
1399 SDValue Borrow = DAG.getConstant(0, VT);
1400 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1401 SDValue Ops [] = { Borrow, Result };
1402 return DAG.getMergeValues(Ops, 2, dl);
1407 case XCoreISD::LMUL: {
1408 SDValue N0 = N->getOperand(0);
1409 SDValue N1 = N->getOperand(1);
1410 SDValue N2 = N->getOperand(2);
1411 SDValue N3 = N->getOperand(3);
1412 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1413 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1414 EVT VT = N0.getValueType();
1415 // Canonicalize multiplicative constant to RHS. If both multiplicative
1416 // operands are constant canonicalize smallest to RHS.
1417 if ((N0C && !N1C) ||
1418 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1419 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT), N1, N0, N2, N3);
1422 if (N1C && N1C->isNullValue()) {
1423 // If the high result is unused fold to add(a, b)
1424 if (N->hasNUsesOfValue(0, 0)) {
1425 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1426 SDValue Ops [] = { Lo, Lo };
1427 return DAG.getMergeValues(Ops, 2, dl);
1429 // Otherwise fold to ladd(a, b, 0)
1430 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1435 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1436 // lmul(x, y, a, b). The high result of lmul will be ignored.
1437 // This is only profitable if the intermediate results are unused
1439 SDValue Mul0, Mul1, Addend0, Addend1;
1440 if (N->getValueType(0) == MVT::i32 &&
1441 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1442 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1443 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1444 Mul1, Addend0, Addend1);
1445 SDValue Result(Ignored.getNode(), 1);
1448 APInt HighMask = APInt::getHighBitsSet(64, 32);
1449 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1450 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1451 // before type legalization as it is messy to match the operands after
1453 if (N->getValueType(0) == MVT::i64 &&
1454 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1455 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1456 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1457 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1458 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1459 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1460 Mul0, DAG.getConstant(0, MVT::i32));
1461 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1462 Mul1, DAG.getConstant(0, MVT::i32));
1463 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1464 Addend0, DAG.getConstant(0, MVT::i32));
1465 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1466 Addend1, DAG.getConstant(0, MVT::i32));
1467 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1468 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1469 Addend0L, Addend1L);
1470 SDValue Lo(Hi.getNode(), 1);
1471 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1476 // Replace unaligned store of unaligned load with memmove.
1477 StoreSDNode *ST = cast<StoreSDNode>(N);
1478 if (!DCI.isBeforeLegalize() ||
1479 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1480 ST->isVolatile() || ST->isIndexed()) {
1483 SDValue Chain = ST->getChain();
1485 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1486 if (StoreBits % 8) {
1489 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1490 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1491 unsigned Alignment = ST->getAlignment();
1492 if (Alignment >= ABIAlignment) {
1496 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1497 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1498 LD->getAlignment() == Alignment &&
1499 !LD->isVolatile() && !LD->isIndexed() &&
1500 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1501 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1503 DAG.getConstant(StoreBits/8, MVT::i32),
1504 Alignment, false, ST->getPointerInfo(),
1505 LD->getPointerInfo());
1514 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1518 const SelectionDAG &DAG,
1519 unsigned Depth) const {
1520 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1521 switch (Op.getOpcode()) {
1523 case XCoreISD::LADD:
1524 case XCoreISD::LSUB:
1525 if (Op.getResNo() == 0) {
1526 // Top bits of carry / borrow are clear.
1527 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1528 Mask.getBitWidth() - 1);
1535 //===----------------------------------------------------------------------===//
1536 // Addressing mode description hooks
1537 //===----------------------------------------------------------------------===//
1539 static inline bool isImmUs(int64_t val)
1541 return (val >= 0 && val <= 11);
1544 static inline bool isImmUs2(int64_t val)
1546 return (val%2 == 0 && isImmUs(val/2));
1549 static inline bool isImmUs4(int64_t val)
1551 return (val%4 == 0 && isImmUs(val/4));
1554 /// isLegalAddressingMode - Return true if the addressing mode represented
1555 /// by AM is legal for this target, for a load/store of the specified type.
1557 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1558 const Type *Ty) const {
1559 if (Ty->getTypeID() == Type::VoidTyID)
1560 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1562 const TargetData *TD = TM.getTargetData();
1563 unsigned Size = TD->getTypeAllocSize(Ty);
1565 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1572 if (AM.Scale == 0) {
1573 return isImmUs(AM.BaseOffs);
1576 return AM.Scale == 1 && AM.BaseOffs == 0;
1580 if (AM.Scale == 0) {
1581 return isImmUs2(AM.BaseOffs);
1584 return AM.Scale == 2 && AM.BaseOffs == 0;
1587 if (AM.Scale == 0) {
1588 return isImmUs4(AM.BaseOffs);
1591 return AM.Scale == 4 && AM.BaseOffs == 0;
1597 //===----------------------------------------------------------------------===//
1598 // XCore Inline Assembly Support
1599 //===----------------------------------------------------------------------===//
1601 std::vector<unsigned> XCoreTargetLowering::
1602 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1605 if (Constraint.size() != 1)
1606 return std::vector<unsigned>();
1608 switch (Constraint[0]) {
1611 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1612 XCore::R3, XCore::R4, XCore::R5,
1613 XCore::R6, XCore::R7, XCore::R8,
1614 XCore::R9, XCore::R10, XCore::R11, 0);
1617 return std::vector<unsigned>();