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"
44 const char *XCoreTargetLowering::
45 getTargetNodeName(unsigned Opcode) const
49 case XCoreISD::BL : return "XCoreISD::BL";
50 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
51 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
52 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
53 case XCoreISD::STWSP : return "XCoreISD::STWSP";
54 case XCoreISD::RETSP : return "XCoreISD::RETSP";
55 case XCoreISD::LADD : return "XCoreISD::LADD";
56 case XCoreISD::LSUB : return "XCoreISD::LSUB";
57 case XCoreISD::LMUL : return "XCoreISD::LMUL";
58 case XCoreISD::MACCU : return "XCoreISD::MACCU";
59 case XCoreISD::MACCS : return "XCoreISD::MACCS";
60 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
61 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
62 default : return NULL;
66 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
67 : TargetLowering(XTM, new XCoreTargetObjectFile()),
69 Subtarget(*XTM.getSubtargetImpl()) {
71 // Set up the register classes.
72 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
74 // Compute derived properties from the register classes
75 computeRegisterProperties();
77 // Division is expensive
78 setIntDivIsCheap(false);
80 setShiftAmountType(MVT::i32);
81 setStackPointerRegisterToSaveRestore(XCore::SP);
83 setSchedulingPreference(SchedulingForRegPressure);
85 // Use i32 for setcc operations results (slt, sgt, ...).
86 setBooleanContents(ZeroOrOneBooleanContent);
88 // XCore does not have the NodeTypes below.
89 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
90 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 setOperationAction(ISD::ADDC, MVT::i32, Expand);
92 setOperationAction(ISD::ADDE, MVT::i32, Expand);
93 setOperationAction(ISD::SUBC, MVT::i32, Expand);
94 setOperationAction(ISD::SUBE, MVT::i32, Expand);
96 // Stop the combiner recombining select and set_cc
97 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
100 setOperationAction(ISD::ADD, MVT::i64, Custom);
101 setOperationAction(ISD::SUB, MVT::i64, Custom);
102 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
103 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
104 setOperationAction(ISD::MULHS, MVT::i32, Expand);
105 setOperationAction(ISD::MULHU, MVT::i32, Expand);
106 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
112 setOperationAction(ISD::ROTL , MVT::i32, Expand);
113 setOperationAction(ISD::ROTR , MVT::i32, Expand);
115 setOperationAction(ISD::TRAP, MVT::Other, Legal);
118 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
120 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
121 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
123 // Thread Local Storage
124 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
126 // Conversion of i64 -> double produces constantpool nodes
127 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
130 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
131 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
132 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
135 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
137 // Custom expand misaligned loads / stores.
138 setOperationAction(ISD::LOAD, MVT::i32, Custom);
139 setOperationAction(ISD::STORE, MVT::i32, Custom);
142 setOperationAction(ISD::VAEND, MVT::Other, Expand);
143 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
144 setOperationAction(ISD::VAARG, MVT::Other, Custom);
145 setOperationAction(ISD::VASTART, MVT::Other, Custom);
148 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
149 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
150 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
152 maxStoresPerMemset = 4;
153 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
155 // We have target-specific dag combine patterns for the following nodes:
156 setTargetDAGCombine(ISD::STORE);
157 setTargetDAGCombine(ISD::ADD);
160 SDValue XCoreTargetLowering::
161 LowerOperation(SDValue Op, SelectionDAG &DAG) {
162 switch (Op.getOpcode())
164 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
165 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
166 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
167 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
168 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
169 case ISD::LOAD: return LowerLOAD(Op, DAG);
170 case ISD::STORE: return LowerSTORE(Op, DAG);
171 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
172 case ISD::VAARG: return LowerVAARG(Op, DAG);
173 case ISD::VASTART: return LowerVASTART(Op, DAG);
174 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
175 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(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);
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);
240 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
243 SDValue XCoreTargetLowering::
244 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
246 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
247 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
248 // If it's a debug information descriptor, don't mess with it.
249 if (DAG.isVerifiedDebugInfoDesc(Op))
251 return getGlobalAddressWrapper(GA, GV, DAG);
254 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
255 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
256 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
259 static inline bool isZeroLengthArray(const Type *Ty) {
260 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
261 return AT && (AT->getNumElements() == 0);
264 SDValue XCoreTargetLowering::
265 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
267 // FIXME there isn't really debug info here
268 DebugLoc dl = Op.getDebugLoc();
269 // transform to label + getid() * size
270 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
271 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
272 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
274 // If GV is an alias then use the aliasee to determine size
275 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
276 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
279 llvm_unreachable("Thread local object not a GlobalVariable?");
282 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
283 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
285 errs() << "Size of thread local object " << GVar->getName()
290 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
291 const TargetData *TD = TM.getTargetData();
292 unsigned Size = TD->getTypeAllocSize(Ty);
293 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
294 DAG.getConstant(Size, MVT::i32));
295 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
298 SDValue XCoreTargetLowering::
299 LowerBlockAddress(SDValue Op, SelectionDAG &DAG)
301 DebugLoc DL = Op.getDebugLoc();
303 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
304 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
306 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
309 SDValue XCoreTargetLowering::
310 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
312 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
313 // FIXME there isn't really debug info here
314 DebugLoc dl = CP->getDebugLoc();
315 EVT PtrVT = Op.getValueType();
317 if (CP->isMachineConstantPoolEntry()) {
318 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
321 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
324 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
327 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
328 return MachineJumpTableInfo::EK_Inline;
331 SDValue XCoreTargetLowering::
332 LowerBR_JT(SDValue Op, SelectionDAG &DAG)
334 SDValue Chain = Op.getOperand(0);
335 SDValue Table = Op.getOperand(1);
336 SDValue Index = Op.getOperand(2);
337 DebugLoc dl = Op.getDebugLoc();
338 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
339 unsigned JTI = JT->getIndex();
340 MachineFunction &MF = DAG.getMachineFunction();
341 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
342 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
344 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
345 if (NumEntries <= 32) {
346 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
348 assert((NumEntries >> 31) == 0);
349 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
350 DAG.getConstant(1, MVT::i32));
351 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
356 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
359 if (Addr.getOpcode() != ISD::ADD) {
362 ConstantSDNode *CN = 0;
363 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
366 int64_t off = CN->getSExtValue();
367 const SDValue &Base = Addr.getOperand(0);
368 const SDValue *Root = &Base;
369 if (Base.getOpcode() == ISD::ADD &&
370 Base.getOperand(1).getOpcode() == ISD::SHL) {
371 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
373 if (CN && (CN->getSExtValue() >= 2)) {
374 Root = &Base.getOperand(0);
377 if (isa<FrameIndexSDNode>(*Root)) {
378 // All frame indicies are word aligned
383 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
384 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
385 // All dp / cp relative addresses are word aligned
393 SDValue XCoreTargetLowering::
394 LowerLOAD(SDValue Op, SelectionDAG &DAG)
396 LoadSDNode *LD = cast<LoadSDNode>(Op);
397 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
398 "Unexpected extension type");
399 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
400 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
403 unsigned ABIAlignment = getTargetData()->
404 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
405 // Leave aligned load alone.
406 if (LD->getAlignment() >= ABIAlignment) {
409 SDValue Chain = LD->getChain();
410 SDValue BasePtr = LD->getBasePtr();
411 DebugLoc dl = Op.getDebugLoc();
415 if (!LD->isVolatile() &&
416 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
417 if (Offset % 4 == 0) {
418 // We've managed to infer better alignment information than the load
419 // already has. Use an aligned load.
421 // FIXME: No new alignment information is actually passed here.
422 // Should the offset really be 4?
424 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4,
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, NULL, 4, false, false, 0);
443 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
444 HighAddr, NULL, 4, 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 int SVOffset = LD->getSrcValueOffset();
456 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
457 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
458 LD->isVolatile(), LD->isNonTemporal(), 2);
459 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
460 DAG.getConstant(2, MVT::i32));
461 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
462 HighAddr, LD->getSrcValue(), SVOffset + 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)
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) {
517 int SVOffset = ST->getSrcValueOffset();
519 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
520 DAG.getConstant(16, MVT::i32));
521 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
522 ST->getSrcValue(), SVOffset, MVT::i16,
523 ST->isVolatile(), ST->isNonTemporal(),
525 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
526 DAG.getConstant(2, MVT::i32));
527 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
528 ST->getSrcValue(), SVOffset + 2,
529 MVT::i16, ST->isVolatile(),
530 ST->isNonTemporal(), 2);
531 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
534 // Lower to a call to __misaligned_store(BasePtr, Value).
535 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
536 TargetLowering::ArgListTy Args;
537 TargetLowering::ArgListEntry Entry;
540 Entry.Node = BasePtr;
541 Args.push_back(Entry);
544 Args.push_back(Entry);
546 std::pair<SDValue, SDValue> CallResult =
547 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
548 false, false, 0, CallingConv::C, false,
549 /*isReturnValueUsed=*/true,
550 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
553 return CallResult.second;
556 SDValue XCoreTargetLowering::
557 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG)
559 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
560 "Unexpected operand to lower!");
561 DebugLoc dl = Op.getDebugLoc();
562 SDValue LHS = Op.getOperand(0);
563 SDValue RHS = Op.getOperand(1);
564 SDValue Zero = DAG.getConstant(0, MVT::i32);
565 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
566 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
568 SDValue Lo(Hi.getNode(), 1);
569 SDValue Ops[] = { Lo, Hi };
570 return DAG.getMergeValues(Ops, 2, dl);
573 SDValue XCoreTargetLowering::
574 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG)
576 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
577 "Unexpected operand to lower!");
578 DebugLoc dl = Op.getDebugLoc();
579 SDValue LHS = Op.getOperand(0);
580 SDValue RHS = Op.getOperand(1);
581 SDValue Zero = DAG.getConstant(0, MVT::i32);
582 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
583 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
585 SDValue Lo(Hi.getNode(), 1);
586 SDValue Ops[] = { Lo, Hi };
587 return DAG.getMergeValues(Ops, 2, dl);
590 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
591 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
592 /// each intermediate result in the calculation must also have a single use.
593 /// If the Op is in the correct form the constituent parts are written to Mul0,
594 /// Mul1, Addend0 and Addend1.
596 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
597 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
599 if (Op.getOpcode() != ISD::ADD)
601 SDValue N0 = Op.getOperand(0);
602 SDValue N1 = Op.getOperand(1);
605 if (N0.getOpcode() == ISD::ADD) {
608 } else if (N1.getOpcode() == ISD::ADD) {
614 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
616 if (OtherOp.getOpcode() == ISD::MUL) {
617 // add(add(a,b),mul(x,y))
618 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
620 Mul0 = OtherOp.getOperand(0);
621 Mul1 = OtherOp.getOperand(1);
622 Addend0 = AddOp.getOperand(0);
623 Addend1 = AddOp.getOperand(1);
626 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
627 // add(add(mul(x,y),a),b)
628 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
630 Mul0 = AddOp.getOperand(0).getOperand(0);
631 Mul1 = AddOp.getOperand(0).getOperand(1);
632 Addend0 = AddOp.getOperand(1);
636 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
637 // add(add(a,mul(x,y)),b)
638 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
640 Mul0 = AddOp.getOperand(1).getOperand(0);
641 Mul1 = AddOp.getOperand(1).getOperand(1);
642 Addend0 = AddOp.getOperand(0);
649 SDValue XCoreTargetLowering::
650 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG)
654 if (N->getOperand(0).getOpcode() == ISD::MUL) {
655 Mul = N->getOperand(0);
656 Other = N->getOperand(1);
657 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
658 Mul = N->getOperand(1);
659 Other = N->getOperand(0);
663 DebugLoc dl = N->getDebugLoc();
664 SDValue LL, RL, AddendL, AddendH;
665 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
666 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
667 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
668 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
669 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
670 Other, DAG.getConstant(0, MVT::i32));
671 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
672 Other, DAG.getConstant(1, MVT::i32));
673 APInt HighMask = APInt::getHighBitsSet(64, 32);
674 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
675 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
676 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
677 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
678 // The inputs are both zero-extended.
679 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
680 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
682 SDValue Lo(Hi.getNode(), 1);
683 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
685 if (LHSSB > 32 && RHSSB > 32) {
686 // The inputs are both sign-extended.
687 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
688 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
690 SDValue Lo(Hi.getNode(), 1);
691 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
694 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
695 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
696 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
697 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
698 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
699 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
701 SDValue Lo(Hi.getNode(), 1);
702 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
703 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
704 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
705 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
706 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
709 SDValue XCoreTargetLowering::
710 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
712 assert(N->getValueType(0) == MVT::i64 &&
713 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
714 "Unknown operand to lower!");
716 if (N->getOpcode() == ISD::ADD) {
717 SDValue Result = TryExpandADDWithMul(N, DAG);
718 if (Result.getNode() != 0)
722 DebugLoc dl = N->getDebugLoc();
724 // Extract components
725 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
726 N->getOperand(0), DAG.getConstant(0, MVT::i32));
727 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
728 N->getOperand(0), DAG.getConstant(1, MVT::i32));
729 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
730 N->getOperand(1), DAG.getConstant(0, MVT::i32));
731 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
732 N->getOperand(1), DAG.getConstant(1, MVT::i32));
735 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
737 SDValue Zero = DAG.getConstant(0, MVT::i32);
738 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
740 SDValue Lo(Carry.getNode(), 1);
742 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
744 SDValue Hi(Ignored.getNode(), 1);
746 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
749 SDValue XCoreTargetLowering::
750 LowerVAARG(SDValue Op, SelectionDAG &DAG)
752 llvm_unreachable("unimplemented");
753 // FIX Arguments passed by reference need a extra dereference.
754 SDNode *Node = Op.getNode();
755 DebugLoc dl = Node->getDebugLoc();
756 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
757 EVT VT = Node->getValueType(0);
758 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
759 Node->getOperand(1), V, 0, false, false, 0);
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), V, 0,
767 // Load the actual argument out of the pointer VAList
768 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0, false, false, 0);
771 SDValue XCoreTargetLowering::
772 LowerVASTART(SDValue Op, SelectionDAG &DAG)
774 DebugLoc dl = Op.getDebugLoc();
775 // vastart stores the address of the VarArgsFrameIndex slot into the
776 // memory location argument
777 MachineFunction &MF = DAG.getMachineFunction();
778 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
779 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
780 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
781 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0,
785 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
786 DebugLoc dl = Op.getDebugLoc();
787 // Depths > 0 not supported yet!
788 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
791 MachineFunction &MF = DAG.getMachineFunction();
792 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
793 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
794 RegInfo->getFrameRegister(MF), MVT::i32);
797 //===----------------------------------------------------------------------===//
798 // Calling Convention Implementation
799 //===----------------------------------------------------------------------===//
801 #include "XCoreGenCallingConv.inc"
803 //===----------------------------------------------------------------------===//
804 // Call Calling Convention Implementation
805 //===----------------------------------------------------------------------===//
807 /// XCore call implementation
809 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
810 CallingConv::ID CallConv, bool isVarArg,
812 const SmallVectorImpl<ISD::OutputArg> &Outs,
813 const SmallVectorImpl<ISD::InputArg> &Ins,
814 DebugLoc dl, SelectionDAG &DAG,
815 SmallVectorImpl<SDValue> &InVals) {
816 // XCore target does not yet support tail call optimization.
819 // For now, only CallingConv::C implemented
823 llvm_unreachable("Unsupported calling convention");
824 case CallingConv::Fast:
826 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
827 Outs, Ins, dl, DAG, InVals);
831 /// LowerCCCCallTo - functions arguments are copied from virtual
832 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
833 /// CALLSEQ_END are emitted.
834 /// TODO: isTailCall, sret.
836 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
837 CallingConv::ID CallConv, bool isVarArg,
839 const SmallVectorImpl<ISD::OutputArg> &Outs,
840 const SmallVectorImpl<ISD::InputArg> &Ins,
841 DebugLoc dl, SelectionDAG &DAG,
842 SmallVectorImpl<SDValue> &InVals) {
844 // Analyze operands of the call, assigning locations to each operand.
845 SmallVector<CCValAssign, 16> ArgLocs;
846 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
847 ArgLocs, *DAG.getContext());
849 // The ABI dictates there should be one stack slot available to the callee
850 // on function entry (for saving lr).
851 CCInfo.AllocateStack(4, 4);
853 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
855 // Get a count of how many bytes are to be pushed on the stack.
856 unsigned NumBytes = CCInfo.getNextStackOffset();
858 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
859 getPointerTy(), true));
861 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
862 SmallVector<SDValue, 12> MemOpChains;
864 // Walk the register/memloc assignments, inserting copies/loads.
865 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
866 CCValAssign &VA = ArgLocs[i];
867 SDValue Arg = Outs[i].Val;
869 // Promote the value if needed.
870 switch (VA.getLocInfo()) {
871 default: llvm_unreachable("Unknown loc info!");
872 case CCValAssign::Full: break;
873 case CCValAssign::SExt:
874 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
876 case CCValAssign::ZExt:
877 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
879 case CCValAssign::AExt:
880 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
884 // Arguments that can be passed on register must be kept at
887 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
889 assert(VA.isMemLoc());
891 int Offset = VA.getLocMemOffset();
893 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
895 DAG.getConstant(Offset/4, MVT::i32)));
899 // Transform all store nodes into one single node because
900 // all store nodes are independent of each other.
901 if (!MemOpChains.empty())
902 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
903 &MemOpChains[0], MemOpChains.size());
905 // Build a sequence of copy-to-reg nodes chained together with token
906 // chain and flag operands which copy the outgoing args into registers.
907 // The InFlag in necessary since all emited instructions must be
910 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
911 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
912 RegsToPass[i].second, InFlag);
913 InFlag = Chain.getValue(1);
916 // If the callee is a GlobalAddress node (quite common, every direct call is)
917 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
918 // Likewise ExternalSymbol -> TargetExternalSymbol.
919 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
920 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
921 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
922 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
924 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
925 // = Chain, Callee, Reg#1, Reg#2, ...
927 // Returns a chain & a flag for retval copy to use.
928 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
929 SmallVector<SDValue, 8> Ops;
930 Ops.push_back(Chain);
931 Ops.push_back(Callee);
933 // Add argument registers to the end of the list so that they are
934 // known live into the call.
935 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
936 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
937 RegsToPass[i].second.getValueType()));
939 if (InFlag.getNode())
940 Ops.push_back(InFlag);
942 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
943 InFlag = Chain.getValue(1);
945 // Create the CALLSEQ_END node.
946 Chain = DAG.getCALLSEQ_END(Chain,
947 DAG.getConstant(NumBytes, getPointerTy(), true),
948 DAG.getConstant(0, getPointerTy(), true),
950 InFlag = Chain.getValue(1);
952 // Handle result values, copying them out of physregs into vregs that we
954 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
955 Ins, dl, DAG, InVals);
958 /// LowerCallResult - Lower the result values of a call into the
959 /// appropriate copies out of appropriate physical registers.
961 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
962 CallingConv::ID CallConv, bool isVarArg,
963 const SmallVectorImpl<ISD::InputArg> &Ins,
964 DebugLoc dl, SelectionDAG &DAG,
965 SmallVectorImpl<SDValue> &InVals) {
967 // Assign locations to each value returned by this call.
968 SmallVector<CCValAssign, 16> RVLocs;
969 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
970 RVLocs, *DAG.getContext());
972 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
974 // Copy all of the result registers out of their specified physreg.
975 for (unsigned i = 0; i != RVLocs.size(); ++i) {
976 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
977 RVLocs[i].getValVT(), InFlag).getValue(1);
978 InFlag = Chain.getValue(2);
979 InVals.push_back(Chain.getValue(0));
985 //===----------------------------------------------------------------------===//
986 // Formal Arguments Calling Convention Implementation
987 //===----------------------------------------------------------------------===//
989 /// XCore formal arguments implementation
991 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
992 CallingConv::ID CallConv,
994 const SmallVectorImpl<ISD::InputArg> &Ins,
997 SmallVectorImpl<SDValue> &InVals) {
1001 llvm_unreachable("Unsupported calling convention");
1002 case CallingConv::C:
1003 case CallingConv::Fast:
1004 return LowerCCCArguments(Chain, CallConv, isVarArg,
1005 Ins, dl, DAG, InVals);
1009 /// LowerCCCArguments - transform physical registers into
1010 /// virtual registers and generate load operations for
1011 /// arguments places on the stack.
1014 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1015 CallingConv::ID CallConv,
1017 const SmallVectorImpl<ISD::InputArg>
1021 SmallVectorImpl<SDValue> &InVals) {
1022 MachineFunction &MF = DAG.getMachineFunction();
1023 MachineFrameInfo *MFI = MF.getFrameInfo();
1024 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1026 // Assign locations to all of the incoming arguments.
1027 SmallVector<CCValAssign, 16> ArgLocs;
1028 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1029 ArgLocs, *DAG.getContext());
1031 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1033 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
1035 unsigned LRSaveSize = StackSlotSize;
1037 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1039 CCValAssign &VA = ArgLocs[i];
1041 if (VA.isRegLoc()) {
1042 // Arguments passed in registers
1043 EVT RegVT = VA.getLocVT();
1044 switch (RegVT.getSimpleVT().SimpleTy) {
1048 errs() << "LowerFormalArguments Unhandled argument type: "
1049 << RegVT.getSimpleVT().SimpleTy << "\n";
1051 llvm_unreachable(0);
1054 unsigned VReg = RegInfo.createVirtualRegister(
1055 XCore::GRRegsRegisterClass);
1056 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1057 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1061 assert(VA.isMemLoc());
1062 // Load the argument to a virtual register
1063 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1064 if (ObjSize > StackSlotSize) {
1065 errs() << "LowerFormalArguments Unhandled argument type: "
1066 << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
1069 // Create the frame index object for this incoming parameter...
1070 int FI = MFI->CreateFixedObject(ObjSize,
1071 LRSaveSize + VA.getLocMemOffset(),
1074 // Create the SelectionDAG nodes corresponding to a load
1075 //from this parameter
1076 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1077 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0,
1083 /* Argument registers */
1084 static const unsigned ArgRegs[] = {
1085 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1087 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1088 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1089 array_lengthof(ArgRegs));
1090 if (FirstVAReg < array_lengthof(ArgRegs)) {
1091 SmallVector<SDValue, 4> MemOps;
1093 // Save remaining registers, storing higher register numbers at a higher
1095 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
1096 // Create a stack slot
1097 int FI = MFI->CreateFixedObject(4, offset, true, false);
1098 if (i == FirstVAReg) {
1099 XFI->setVarArgsFrameIndex(FI);
1101 offset -= StackSlotSize;
1102 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1103 // Move argument from phys reg -> virt reg
1104 unsigned VReg = RegInfo.createVirtualRegister(
1105 XCore::GRRegsRegisterClass);
1106 RegInfo.addLiveIn(ArgRegs[i], VReg);
1107 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1108 // Move argument from virt reg -> stack
1109 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0,
1111 MemOps.push_back(Store);
1113 if (!MemOps.empty())
1114 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1115 &MemOps[0], MemOps.size());
1117 // This will point to the next argument passed via stack.
1118 XFI->setVarArgsFrameIndex(
1119 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1127 //===----------------------------------------------------------------------===//
1128 // Return Value Calling Convention Implementation
1129 //===----------------------------------------------------------------------===//
1131 bool XCoreTargetLowering::
1132 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1133 const SmallVectorImpl<EVT> &OutTys,
1134 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1135 SelectionDAG &DAG) {
1136 SmallVector<CCValAssign, 16> RVLocs;
1137 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1138 RVLocs, *DAG.getContext());
1139 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_XCore);
1143 XCoreTargetLowering::LowerReturn(SDValue Chain,
1144 CallingConv::ID CallConv, bool isVarArg,
1145 const SmallVectorImpl<ISD::OutputArg> &Outs,
1146 DebugLoc dl, SelectionDAG &DAG) {
1148 // CCValAssign - represent the assignment of
1149 // the return value to a location
1150 SmallVector<CCValAssign, 16> RVLocs;
1152 // CCState - Info about the registers and stack slot.
1153 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1154 RVLocs, *DAG.getContext());
1156 // Analize return values.
1157 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1159 // If this is the first return lowered for this function, add
1160 // the regs to the liveout set for the function.
1161 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1162 for (unsigned i = 0; i != RVLocs.size(); ++i)
1163 if (RVLocs[i].isRegLoc())
1164 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1169 // Copy the result values into the output registers.
1170 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1171 CCValAssign &VA = RVLocs[i];
1172 assert(VA.isRegLoc() && "Can only return in registers!");
1174 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1177 // guarantee that all emitted copies are
1178 // stuck together, avoiding something bad
1179 Flag = Chain.getValue(1);
1182 // Return on XCore is always a "retsp 0"
1184 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1185 Chain, DAG.getConstant(0, MVT::i32), Flag);
1187 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1188 Chain, DAG.getConstant(0, MVT::i32));
1191 //===----------------------------------------------------------------------===//
1192 // Other Lowering Code
1193 //===----------------------------------------------------------------------===//
1196 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1197 MachineBasicBlock *BB,
1198 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
1199 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1200 DebugLoc dl = MI->getDebugLoc();
1201 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1202 "Unexpected instr type to insert");
1204 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1205 // control-flow pattern. The incoming instruction knows the destination vreg
1206 // to set, the condition code register to branch on, the true/false values to
1207 // select between, and a branch opcode to use.
1208 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1209 MachineFunction::iterator It = BB;
1215 // cmpTY ccX, r1, r2
1217 // fallthrough --> copy0MBB
1218 MachineBasicBlock *thisMBB = BB;
1219 MachineFunction *F = BB->getParent();
1220 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1221 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1222 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1223 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1224 F->insert(It, copy0MBB);
1225 F->insert(It, sinkMBB);
1226 // Update machine-CFG edges by first adding all successors of the current
1227 // block to the new block which will contain the Phi node for the select.
1228 // Also inform sdisel of the edge changes.
1229 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1230 E = BB->succ_end(); I != E; ++I) {
1231 EM->insert(std::make_pair(*I, sinkMBB));
1232 sinkMBB->addSuccessor(*I);
1234 // Next, remove all successors of the current block, and add the true
1235 // and fallthrough blocks as its successors.
1236 while (!BB->succ_empty())
1237 BB->removeSuccessor(BB->succ_begin());
1238 // Next, add the true and fallthrough blocks as its successors.
1239 BB->addSuccessor(copy0MBB);
1240 BB->addSuccessor(sinkMBB);
1243 // %FalseValue = ...
1244 // # fallthrough to sinkMBB
1247 // Update machine-CFG edges
1248 BB->addSuccessor(sinkMBB);
1251 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1254 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1255 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1256 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1258 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1262 //===----------------------------------------------------------------------===//
1263 // Target Optimization Hooks
1264 //===----------------------------------------------------------------------===//
1266 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1267 DAGCombinerInfo &DCI) const {
1268 SelectionDAG &DAG = DCI.DAG;
1269 DebugLoc dl = N->getDebugLoc();
1270 switch (N->getOpcode()) {
1272 case XCoreISD::LADD: {
1273 SDValue N0 = N->getOperand(0);
1274 SDValue N1 = N->getOperand(1);
1275 SDValue N2 = N->getOperand(2);
1276 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1277 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1278 EVT VT = N0.getValueType();
1280 // canonicalize constant to RHS
1282 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1284 // fold (ladd 0, 0, x) -> 0, x & 1
1285 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1286 SDValue Carry = DAG.getConstant(0, VT);
1287 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1288 DAG.getConstant(1, VT));
1289 SDValue Ops [] = { Carry, Result };
1290 return DAG.getMergeValues(Ops, 2, dl);
1293 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1295 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1296 APInt KnownZero, KnownOne;
1297 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1298 VT.getSizeInBits() - 1);
1299 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1300 if (KnownZero == Mask) {
1301 SDValue Carry = DAG.getConstant(0, VT);
1302 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1303 SDValue Ops [] = { Carry, Result };
1304 return DAG.getMergeValues(Ops, 2, dl);
1309 case XCoreISD::LSUB: {
1310 SDValue N0 = N->getOperand(0);
1311 SDValue N1 = N->getOperand(1);
1312 SDValue N2 = N->getOperand(2);
1313 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1315 EVT VT = N0.getValueType();
1317 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1318 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1319 APInt KnownZero, KnownOne;
1320 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1321 VT.getSizeInBits() - 1);
1322 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1323 if (KnownZero == Mask) {
1324 SDValue Borrow = N2;
1325 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1326 DAG.getConstant(0, VT), N2);
1327 SDValue Ops [] = { Borrow, Result };
1328 return DAG.getMergeValues(Ops, 2, dl);
1332 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1334 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1335 APInt KnownZero, KnownOne;
1336 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1337 VT.getSizeInBits() - 1);
1338 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1339 if (KnownZero == Mask) {
1340 SDValue Borrow = DAG.getConstant(0, VT);
1341 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1342 SDValue Ops [] = { Borrow, Result };
1343 return DAG.getMergeValues(Ops, 2, dl);
1349 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1350 // lmul(x, y, a, b). The high result of lmul will be ignored.
1351 // This is only profitable if the intermediate results are unused
1353 SDValue Mul0, Mul1, Addend0, Addend1;
1354 if (N->getValueType(0) == MVT::i32 &&
1355 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1356 SDValue Zero = DAG.getConstant(0, MVT::i32);
1357 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1358 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1359 Mul1, Addend0, Addend1);
1360 SDValue Result(Ignored.getNode(), 1);
1363 APInt HighMask = APInt::getHighBitsSet(64, 32);
1364 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1365 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1366 // before type legalization as it is messy to match the operands after
1368 if (N->getValueType(0) == MVT::i64 &&
1369 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1370 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1371 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1372 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1373 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1374 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1375 Mul0, DAG.getConstant(0, MVT::i32));
1376 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1377 Mul1, DAG.getConstant(0, MVT::i32));
1378 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1379 Addend0, DAG.getConstant(0, MVT::i32));
1380 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1381 Addend1, DAG.getConstant(0, MVT::i32));
1382 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1383 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1384 Addend0L, Addend1L);
1385 SDValue Lo(Hi.getNode(), 1);
1386 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1391 // Replace unaligned store of unaligned load with memmove.
1392 StoreSDNode *ST = cast<StoreSDNode>(N);
1393 if (!DCI.isBeforeLegalize() ||
1394 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1395 ST->isVolatile() || ST->isIndexed()) {
1398 SDValue Chain = ST->getChain();
1400 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1401 if (StoreBits % 8) {
1404 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1405 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1406 unsigned Alignment = ST->getAlignment();
1407 if (Alignment >= ABIAlignment) {
1411 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1412 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1413 LD->getAlignment() == Alignment &&
1414 !LD->isVolatile() && !LD->isIndexed() &&
1415 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1416 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1418 DAG.getConstant(StoreBits/8, MVT::i32),
1419 Alignment, ST->getSrcValue(),
1420 ST->getSrcValueOffset(), LD->getSrcValue(),
1421 LD->getSrcValueOffset());
1430 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1434 const SelectionDAG &DAG,
1435 unsigned Depth) const {
1436 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1437 switch (Op.getOpcode()) {
1439 case XCoreISD::LADD:
1440 case XCoreISD::LSUB:
1441 if (Op.getResNo() == 0) {
1442 // Top bits of carry / borrow are clear.
1443 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1444 Mask.getBitWidth() - 1);
1451 //===----------------------------------------------------------------------===//
1452 // Addressing mode description hooks
1453 //===----------------------------------------------------------------------===//
1455 static inline bool isImmUs(int64_t val)
1457 return (val >= 0 && val <= 11);
1460 static inline bool isImmUs2(int64_t val)
1462 return (val%2 == 0 && isImmUs(val/2));
1465 static inline bool isImmUs4(int64_t val)
1467 return (val%4 == 0 && isImmUs(val/4));
1470 /// isLegalAddressingMode - Return true if the addressing mode represented
1471 /// by AM is legal for this target, for a load/store of the specified type.
1473 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1474 const Type *Ty) const {
1475 if (Ty->getTypeID() == Type::VoidTyID)
1476 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1478 const TargetData *TD = TM.getTargetData();
1479 unsigned Size = TD->getTypeAllocSize(Ty);
1481 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1488 if (AM.Scale == 0) {
1489 return isImmUs(AM.BaseOffs);
1492 return AM.Scale == 1 && AM.BaseOffs == 0;
1496 if (AM.Scale == 0) {
1497 return isImmUs2(AM.BaseOffs);
1500 return AM.Scale == 2 && AM.BaseOffs == 0;
1503 if (AM.Scale == 0) {
1504 return isImmUs4(AM.BaseOffs);
1507 return AM.Scale == 4 && AM.BaseOffs == 0;
1513 //===----------------------------------------------------------------------===//
1514 // XCore Inline Assembly Support
1515 //===----------------------------------------------------------------------===//
1517 std::vector<unsigned> XCoreTargetLowering::
1518 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1521 if (Constraint.size() != 1)
1522 return std::vector<unsigned>();
1524 switch (Constraint[0]) {
1527 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1528 XCore::R3, XCore::R4, XCore::R5,
1529 XCore::R6, XCore::R7, XCore::R8,
1530 XCore::R9, XCore::R10, XCore::R11, 0);
1533 return std::vector<unsigned>();