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::MACCU : return "XCoreISD::MACCU";
58 case XCoreISD::MACCS : return "XCoreISD::MACCS";
59 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
60 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
61 default : return NULL;
65 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
66 : TargetLowering(XTM, new XCoreTargetObjectFile()),
68 Subtarget(*XTM.getSubtargetImpl()) {
70 // Set up the register classes.
71 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
73 // Compute derived properties from the register classes
74 computeRegisterProperties();
76 // Division is expensive
77 setIntDivIsCheap(false);
79 setShiftAmountType(MVT::i32);
80 setStackPointerRegisterToSaveRestore(XCore::SP);
82 setSchedulingPreference(SchedulingForRegPressure);
84 // Use i32 for setcc operations results (slt, sgt, ...).
85 setBooleanContents(ZeroOrOneBooleanContent);
87 // XCore does not have the NodeTypes below.
88 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
89 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
90 setOperationAction(ISD::ADDC, MVT::i32, Expand);
91 setOperationAction(ISD::ADDE, MVT::i32, Expand);
92 setOperationAction(ISD::SUBC, MVT::i32, Expand);
93 setOperationAction(ISD::SUBE, MVT::i32, Expand);
95 // Stop the combiner recombining select and set_cc
96 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
99 setOperationAction(ISD::ADD, MVT::i64, Custom);
100 setOperationAction(ISD::SUB, MVT::i64, 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 maxStoresPerMemset = 4;
150 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
152 // We have target-specific dag combine patterns for the following nodes:
153 setTargetDAGCombine(ISD::STORE);
156 SDValue XCoreTargetLowering::
157 LowerOperation(SDValue Op, SelectionDAG &DAG) {
158 switch (Op.getOpcode())
160 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
161 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
162 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
163 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
164 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
165 case ISD::LOAD: return LowerLOAD(Op, DAG);
166 case ISD::STORE: return LowerSTORE(Op, DAG);
167 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
168 case ISD::VAARG: return LowerVAARG(Op, DAG);
169 case ISD::VASTART: return LowerVASTART(Op, DAG);
170 // FIXME: Remove these when LegalizeDAGTypes lands.
172 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
173 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
175 llvm_unreachable("unimplemented operand");
180 /// ReplaceNodeResults - Replace the results of node with an illegal result
181 /// type with new values built out of custom code.
182 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
183 SmallVectorImpl<SDValue>&Results,
185 switch (N->getOpcode()) {
187 llvm_unreachable("Don't know how to custom expand this!");
191 Results.push_back(ExpandADDSUB(N, DAG));
196 /// getFunctionAlignment - Return the Log2 alignment of this function.
197 unsigned XCoreTargetLowering::
198 getFunctionAlignment(const Function *) const {
202 //===----------------------------------------------------------------------===//
203 // Misc Lower Operation implementation
204 //===----------------------------------------------------------------------===//
206 SDValue XCoreTargetLowering::
207 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
209 DebugLoc dl = Op.getDebugLoc();
210 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
211 Op.getOperand(3), Op.getOperand(4));
212 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
216 SDValue XCoreTargetLowering::
217 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
219 // FIXME there is no actual debug info here
220 DebugLoc dl = GA.getDebugLoc();
221 if (isa<Function>(GV)) {
222 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
224 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
226 // If GV is an alias then use the aliasee to determine constness
227 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
228 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
230 bool isConst = GVar && GVar->isConstant();
232 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
234 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
237 SDValue XCoreTargetLowering::
238 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
240 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
241 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
242 // If it's a debug information descriptor, don't mess with it.
243 if (DAG.isVerifiedDebugInfoDesc(Op))
245 return getGlobalAddressWrapper(GA, GV, DAG);
248 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
249 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
250 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
253 static inline bool isZeroLengthArray(const Type *Ty) {
254 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
255 return AT && (AT->getNumElements() == 0);
258 SDValue XCoreTargetLowering::
259 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
261 // FIXME there isn't really debug info here
262 DebugLoc dl = Op.getDebugLoc();
263 // transform to label + getid() * size
264 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
265 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
266 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
268 // If GV is an alias then use the aliasee to determine size
269 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
270 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
273 llvm_unreachable("Thread local object not a GlobalVariable?");
276 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
277 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
279 errs() << "Size of thread local object " << GVar->getName()
284 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
285 const TargetData *TD = TM.getTargetData();
286 unsigned Size = TD->getTypeAllocSize(Ty);
287 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
288 DAG.getConstant(Size, MVT::i32));
289 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
292 SDValue XCoreTargetLowering::
293 LowerBlockAddress(SDValue Op, SelectionDAG &DAG)
295 DebugLoc DL = Op.getDebugLoc();
297 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
298 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
300 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
303 SDValue XCoreTargetLowering::
304 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
306 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
307 // FIXME there isn't really debug info here
308 DebugLoc dl = CP->getDebugLoc();
309 EVT PtrVT = Op.getValueType();
311 if (CP->isMachineConstantPoolEntry()) {
312 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
315 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
318 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
321 SDValue XCoreTargetLowering::
322 LowerBR_JT(SDValue Op, SelectionDAG &DAG)
324 SDValue Chain = Op.getOperand(0);
325 SDValue Table = Op.getOperand(1);
326 SDValue Index = Op.getOperand(2);
327 DebugLoc dl = Op.getDebugLoc();
328 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
329 unsigned JTI = JT->getIndex();
330 MachineFunction &MF = DAG.getMachineFunction();
331 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
332 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
334 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
335 if (NumEntries <= 32) {
336 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
338 assert((NumEntries >> 31) == 0);
339 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
340 DAG.getConstant(1, MVT::i32));
341 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
346 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
349 if (Addr.getOpcode() != ISD::ADD) {
352 ConstantSDNode *CN = 0;
353 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
356 int64_t off = CN->getSExtValue();
357 const SDValue &Base = Addr.getOperand(0);
358 const SDValue *Root = &Base;
359 if (Base.getOpcode() == ISD::ADD &&
360 Base.getOperand(1).getOpcode() == ISD::SHL) {
361 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
363 if (CN && (CN->getSExtValue() >= 2)) {
364 Root = &Base.getOperand(0);
367 if (isa<FrameIndexSDNode>(*Root)) {
368 // All frame indicies are word aligned
373 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
374 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
375 // All dp / cp relative addresses are word aligned
383 SDValue XCoreTargetLowering::
384 LowerLOAD(SDValue Op, SelectionDAG &DAG)
386 LoadSDNode *LD = cast<LoadSDNode>(Op);
387 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
388 "Unexpected extension type");
389 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
390 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
393 unsigned ABIAlignment = getTargetData()->
394 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
395 // Leave aligned load alone.
396 if (LD->getAlignment() >= ABIAlignment) {
399 SDValue Chain = LD->getChain();
400 SDValue BasePtr = LD->getBasePtr();
401 DebugLoc dl = Op.getDebugLoc();
405 if (!LD->isVolatile() &&
406 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
407 if (Offset % 4 == 0) {
408 // We've managed to infer better alignment information than the load
409 // already has. Use an aligned load.
411 // FIXME: No new alignment information is actually passed here.
412 // Should the offset really be 4?
414 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4,
418 // ldw low, base[offset >> 2]
419 // ldw high, base[(offset >> 2) + 1]
420 // shr low_shifted, low, (offset & 0x3) * 8
421 // shl high_shifted, high, 32 - (offset & 0x3) * 8
422 // or result, low_shifted, high_shifted
423 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
424 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
425 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
426 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
428 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
429 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
431 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
432 LowAddr, NULL, 4, false, false, 0);
433 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
434 HighAddr, NULL, 4, false, false, 0);
435 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
436 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
437 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
438 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
440 SDValue Ops[] = { Result, Chain };
441 return DAG.getMergeValues(Ops, 2, dl);
444 if (LD->getAlignment() == 2) {
445 int SVOffset = LD->getSrcValueOffset();
446 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
447 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
448 LD->isVolatile(), LD->isNonTemporal(), 2);
449 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
450 DAG.getConstant(2, MVT::i32));
451 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
452 HighAddr, LD->getSrcValue(), SVOffset + 2,
453 MVT::i16, LD->isVolatile(),
454 LD->isNonTemporal(), 2);
455 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
456 DAG.getConstant(16, MVT::i32));
457 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
458 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
460 SDValue Ops[] = { Result, Chain };
461 return DAG.getMergeValues(Ops, 2, dl);
464 // Lower to a call to __misaligned_load(BasePtr).
465 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
466 TargetLowering::ArgListTy Args;
467 TargetLowering::ArgListEntry Entry;
470 Entry.Node = BasePtr;
471 Args.push_back(Entry);
473 std::pair<SDValue, SDValue> CallResult =
474 LowerCallTo(Chain, IntPtrTy, false, false,
475 false, false, 0, CallingConv::C, false,
476 /*isReturnValueUsed=*/true,
477 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
481 { CallResult.first, CallResult.second };
483 return DAG.getMergeValues(Ops, 2, dl);
486 SDValue XCoreTargetLowering::
487 LowerSTORE(SDValue Op, SelectionDAG &DAG)
489 StoreSDNode *ST = cast<StoreSDNode>(Op);
490 assert(!ST->isTruncatingStore() && "Unexpected store type");
491 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
492 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
495 unsigned ABIAlignment = getTargetData()->
496 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
497 // Leave aligned store alone.
498 if (ST->getAlignment() >= ABIAlignment) {
501 SDValue Chain = ST->getChain();
502 SDValue BasePtr = ST->getBasePtr();
503 SDValue Value = ST->getValue();
504 DebugLoc dl = Op.getDebugLoc();
506 if (ST->getAlignment() == 2) {
507 int SVOffset = ST->getSrcValueOffset();
509 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
510 DAG.getConstant(16, MVT::i32));
511 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
512 ST->getSrcValue(), SVOffset, MVT::i16,
513 ST->isVolatile(), ST->isNonTemporal(),
515 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
516 DAG.getConstant(2, MVT::i32));
517 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
518 ST->getSrcValue(), SVOffset + 2,
519 MVT::i16, ST->isVolatile(),
520 ST->isNonTemporal(), 2);
521 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
524 // Lower to a call to __misaligned_store(BasePtr, Value).
525 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
526 TargetLowering::ArgListTy Args;
527 TargetLowering::ArgListEntry Entry;
530 Entry.Node = BasePtr;
531 Args.push_back(Entry);
534 Args.push_back(Entry);
536 std::pair<SDValue, SDValue> CallResult =
537 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
538 false, false, 0, CallingConv::C, false,
539 /*isReturnValueUsed=*/true,
540 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
543 return CallResult.second;
546 SDValue XCoreTargetLowering::
547 TryExpandADDSUBWithMul(SDNode *N, SelectionDAG &DAG)
551 if (N->getOperand(0).getOpcode() == ISD::MUL) {
552 Mul = N->getOperand(0);
553 Other = N->getOperand(1);
554 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
555 Mul = N->getOperand(1);
556 Other = N->getOperand(0);
560 DebugLoc dl = N->getDebugLoc();
561 SDValue LL, RL, AddendL, AddendH;
562 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
563 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
564 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
565 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
566 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
567 Other, DAG.getConstant(0, MVT::i32));
568 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
569 Other, DAG.getConstant(1, MVT::i32));
570 APInt HighMask = APInt::getHighBitsSet(64, 32);
571 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
572 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
573 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
574 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
575 // The inputs are both zero-extended.
576 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
577 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
579 SDValue Lo(Hi.getNode(), 1);
580 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
582 if (LHSSB > 32 && RHSSB > 32) {
583 // The inputs are both sign-extended.
584 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
585 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
587 SDValue Lo(Hi.getNode(), 1);
588 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
591 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
592 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
593 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
594 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
595 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
596 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
598 SDValue Lo(Hi.getNode(), 1);
599 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
600 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
601 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
602 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
603 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
606 SDValue XCoreTargetLowering::
607 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
609 assert(N->getValueType(0) == MVT::i64 &&
610 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
611 "Unknown operand to lower!");
613 SDValue Result = TryExpandADDSUBWithMul(N, DAG);
614 if (Result.getNode() != 0)
617 DebugLoc dl = N->getDebugLoc();
619 // Extract components
620 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
621 N->getOperand(0), DAG.getConstant(0, MVT::i32));
622 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
623 N->getOperand(0), DAG.getConstant(1, MVT::i32));
624 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
625 N->getOperand(1), DAG.getConstant(0, MVT::i32));
626 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
627 N->getOperand(1), DAG.getConstant(1, MVT::i32));
630 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
632 SDValue Zero = DAG.getConstant(0, MVT::i32);
633 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
635 SDValue Lo(Carry.getNode(), 1);
637 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
639 SDValue Hi(Ignored.getNode(), 1);
641 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
644 SDValue XCoreTargetLowering::
645 LowerVAARG(SDValue Op, SelectionDAG &DAG)
647 llvm_unreachable("unimplemented");
648 // FIX Arguments passed by reference need a extra dereference.
649 SDNode *Node = Op.getNode();
650 DebugLoc dl = Node->getDebugLoc();
651 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
652 EVT VT = Node->getValueType(0);
653 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
654 Node->getOperand(1), V, 0, false, false, 0);
655 // Increment the pointer, VAList, to the next vararg
656 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
657 DAG.getConstant(VT.getSizeInBits(),
659 // Store the incremented VAList to the legalized pointer
660 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0,
662 // Load the actual argument out of the pointer VAList
663 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0, false, false, 0);
666 SDValue XCoreTargetLowering::
667 LowerVASTART(SDValue Op, SelectionDAG &DAG)
669 DebugLoc dl = Op.getDebugLoc();
670 // vastart stores the address of the VarArgsFrameIndex slot into the
671 // memory location argument
672 MachineFunction &MF = DAG.getMachineFunction();
673 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
674 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
675 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
676 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0,
680 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
681 DebugLoc dl = Op.getDebugLoc();
682 // Depths > 0 not supported yet!
683 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
686 MachineFunction &MF = DAG.getMachineFunction();
687 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
688 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
689 RegInfo->getFrameRegister(MF), MVT::i32);
692 //===----------------------------------------------------------------------===//
693 // Calling Convention Implementation
694 //===----------------------------------------------------------------------===//
696 #include "XCoreGenCallingConv.inc"
698 //===----------------------------------------------------------------------===//
699 // Call Calling Convention Implementation
700 //===----------------------------------------------------------------------===//
702 /// XCore call implementation
704 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
705 CallingConv::ID CallConv, bool isVarArg,
707 const SmallVectorImpl<ISD::OutputArg> &Outs,
708 const SmallVectorImpl<ISD::InputArg> &Ins,
709 DebugLoc dl, SelectionDAG &DAG,
710 SmallVectorImpl<SDValue> &InVals) {
711 // XCore target does not yet support tail call optimization.
714 // For now, only CallingConv::C implemented
718 llvm_unreachable("Unsupported calling convention");
719 case CallingConv::Fast:
721 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
722 Outs, Ins, dl, DAG, InVals);
726 /// LowerCCCCallTo - functions arguments are copied from virtual
727 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
728 /// CALLSEQ_END are emitted.
729 /// TODO: isTailCall, sret.
731 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
732 CallingConv::ID CallConv, bool isVarArg,
734 const SmallVectorImpl<ISD::OutputArg> &Outs,
735 const SmallVectorImpl<ISD::InputArg> &Ins,
736 DebugLoc dl, SelectionDAG &DAG,
737 SmallVectorImpl<SDValue> &InVals) {
739 // Analyze operands of the call, assigning locations to each operand.
740 SmallVector<CCValAssign, 16> ArgLocs;
741 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
742 ArgLocs, *DAG.getContext());
744 // The ABI dictates there should be one stack slot available to the callee
745 // on function entry (for saving lr).
746 CCInfo.AllocateStack(4, 4);
748 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
750 // Get a count of how many bytes are to be pushed on the stack.
751 unsigned NumBytes = CCInfo.getNextStackOffset();
753 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
754 getPointerTy(), true));
756 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
757 SmallVector<SDValue, 12> MemOpChains;
759 // Walk the register/memloc assignments, inserting copies/loads.
760 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
761 CCValAssign &VA = ArgLocs[i];
762 SDValue Arg = Outs[i].Val;
764 // Promote the value if needed.
765 switch (VA.getLocInfo()) {
766 default: llvm_unreachable("Unknown loc info!");
767 case CCValAssign::Full: break;
768 case CCValAssign::SExt:
769 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
771 case CCValAssign::ZExt:
772 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
774 case CCValAssign::AExt:
775 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
779 // Arguments that can be passed on register must be kept at
782 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
784 assert(VA.isMemLoc());
786 int Offset = VA.getLocMemOffset();
788 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
790 DAG.getConstant(Offset/4, MVT::i32)));
794 // Transform all store nodes into one single node because
795 // all store nodes are independent of each other.
796 if (!MemOpChains.empty())
797 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
798 &MemOpChains[0], MemOpChains.size());
800 // Build a sequence of copy-to-reg nodes chained together with token
801 // chain and flag operands which copy the outgoing args into registers.
802 // The InFlag in necessary since all emited instructions must be
805 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
806 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
807 RegsToPass[i].second, InFlag);
808 InFlag = Chain.getValue(1);
811 // If the callee is a GlobalAddress node (quite common, every direct call is)
812 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
813 // Likewise ExternalSymbol -> TargetExternalSymbol.
814 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
815 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
816 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
817 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
819 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
820 // = Chain, Callee, Reg#1, Reg#2, ...
822 // Returns a chain & a flag for retval copy to use.
823 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
824 SmallVector<SDValue, 8> Ops;
825 Ops.push_back(Chain);
826 Ops.push_back(Callee);
828 // Add argument registers to the end of the list so that they are
829 // known live into the call.
830 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
831 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
832 RegsToPass[i].second.getValueType()));
834 if (InFlag.getNode())
835 Ops.push_back(InFlag);
837 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
838 InFlag = Chain.getValue(1);
840 // Create the CALLSEQ_END node.
841 Chain = DAG.getCALLSEQ_END(Chain,
842 DAG.getConstant(NumBytes, getPointerTy(), true),
843 DAG.getConstant(0, getPointerTy(), true),
845 InFlag = Chain.getValue(1);
847 // Handle result values, copying them out of physregs into vregs that we
849 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
850 Ins, dl, DAG, InVals);
853 /// LowerCallResult - Lower the result values of a call into the
854 /// appropriate copies out of appropriate physical registers.
856 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
857 CallingConv::ID CallConv, bool isVarArg,
858 const SmallVectorImpl<ISD::InputArg> &Ins,
859 DebugLoc dl, SelectionDAG &DAG,
860 SmallVectorImpl<SDValue> &InVals) {
862 // Assign locations to each value returned by this call.
863 SmallVector<CCValAssign, 16> RVLocs;
864 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
865 RVLocs, *DAG.getContext());
867 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
869 // Copy all of the result registers out of their specified physreg.
870 for (unsigned i = 0; i != RVLocs.size(); ++i) {
871 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
872 RVLocs[i].getValVT(), InFlag).getValue(1);
873 InFlag = Chain.getValue(2);
874 InVals.push_back(Chain.getValue(0));
880 //===----------------------------------------------------------------------===//
881 // Formal Arguments Calling Convention Implementation
882 //===----------------------------------------------------------------------===//
884 /// XCore formal arguments implementation
886 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
887 CallingConv::ID CallConv,
889 const SmallVectorImpl<ISD::InputArg> &Ins,
892 SmallVectorImpl<SDValue> &InVals) {
896 llvm_unreachable("Unsupported calling convention");
898 case CallingConv::Fast:
899 return LowerCCCArguments(Chain, CallConv, isVarArg,
900 Ins, dl, DAG, InVals);
904 /// LowerCCCArguments - transform physical registers into
905 /// virtual registers and generate load operations for
906 /// arguments places on the stack.
909 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
910 CallingConv::ID CallConv,
912 const SmallVectorImpl<ISD::InputArg>
916 SmallVectorImpl<SDValue> &InVals) {
917 MachineFunction &MF = DAG.getMachineFunction();
918 MachineFrameInfo *MFI = MF.getFrameInfo();
919 MachineRegisterInfo &RegInfo = MF.getRegInfo();
921 // Assign locations to all of the incoming arguments.
922 SmallVector<CCValAssign, 16> ArgLocs;
923 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
924 ArgLocs, *DAG.getContext());
926 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
928 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
930 unsigned LRSaveSize = StackSlotSize;
932 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
934 CCValAssign &VA = ArgLocs[i];
937 // Arguments passed in registers
938 EVT RegVT = VA.getLocVT();
939 switch (RegVT.getSimpleVT().SimpleTy) {
943 errs() << "LowerFormalArguments Unhandled argument type: "
944 << RegVT.getSimpleVT().SimpleTy << "\n";
949 unsigned VReg = RegInfo.createVirtualRegister(
950 XCore::GRRegsRegisterClass);
951 RegInfo.addLiveIn(VA.getLocReg(), VReg);
952 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
956 assert(VA.isMemLoc());
957 // Load the argument to a virtual register
958 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
959 if (ObjSize > StackSlotSize) {
960 errs() << "LowerFormalArguments Unhandled argument type: "
961 << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
964 // Create the frame index object for this incoming parameter...
965 int FI = MFI->CreateFixedObject(ObjSize,
966 LRSaveSize + VA.getLocMemOffset(),
969 // Create the SelectionDAG nodes corresponding to a load
970 //from this parameter
971 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
972 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0,
978 /* Argument registers */
979 static const unsigned ArgRegs[] = {
980 XCore::R0, XCore::R1, XCore::R2, XCore::R3
982 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
983 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
984 array_lengthof(ArgRegs));
985 if (FirstVAReg < array_lengthof(ArgRegs)) {
986 SmallVector<SDValue, 4> MemOps;
988 // Save remaining registers, storing higher register numbers at a higher
990 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
991 // Create a stack slot
992 int FI = MFI->CreateFixedObject(4, offset, true, false);
993 if (i == FirstVAReg) {
994 XFI->setVarArgsFrameIndex(FI);
996 offset -= StackSlotSize;
997 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
998 // Move argument from phys reg -> virt reg
999 unsigned VReg = RegInfo.createVirtualRegister(
1000 XCore::GRRegsRegisterClass);
1001 RegInfo.addLiveIn(ArgRegs[i], VReg);
1002 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1003 // Move argument from virt reg -> stack
1004 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0,
1006 MemOps.push_back(Store);
1008 if (!MemOps.empty())
1009 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1010 &MemOps[0], MemOps.size());
1012 // This will point to the next argument passed via stack.
1013 XFI->setVarArgsFrameIndex(
1014 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1022 //===----------------------------------------------------------------------===//
1023 // Return Value Calling Convention Implementation
1024 //===----------------------------------------------------------------------===//
1026 bool XCoreTargetLowering::
1027 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1028 const SmallVectorImpl<EVT> &OutTys,
1029 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1030 SelectionDAG &DAG) {
1031 SmallVector<CCValAssign, 16> RVLocs;
1032 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1033 RVLocs, *DAG.getContext());
1034 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_XCore);
1038 XCoreTargetLowering::LowerReturn(SDValue Chain,
1039 CallingConv::ID CallConv, bool isVarArg,
1040 const SmallVectorImpl<ISD::OutputArg> &Outs,
1041 DebugLoc dl, SelectionDAG &DAG) {
1043 // CCValAssign - represent the assignment of
1044 // the return value to a location
1045 SmallVector<CCValAssign, 16> RVLocs;
1047 // CCState - Info about the registers and stack slot.
1048 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1049 RVLocs, *DAG.getContext());
1051 // Analize return values.
1052 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1054 // If this is the first return lowered for this function, add
1055 // the regs to the liveout set for the function.
1056 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1057 for (unsigned i = 0; i != RVLocs.size(); ++i)
1058 if (RVLocs[i].isRegLoc())
1059 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1064 // Copy the result values into the output registers.
1065 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1066 CCValAssign &VA = RVLocs[i];
1067 assert(VA.isRegLoc() && "Can only return in registers!");
1069 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1072 // guarantee that all emitted copies are
1073 // stuck together, avoiding something bad
1074 Flag = Chain.getValue(1);
1077 // Return on XCore is always a "retsp 0"
1079 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1080 Chain, DAG.getConstant(0, MVT::i32), Flag);
1082 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1083 Chain, DAG.getConstant(0, MVT::i32));
1086 //===----------------------------------------------------------------------===//
1087 // Other Lowering Code
1088 //===----------------------------------------------------------------------===//
1091 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1092 MachineBasicBlock *BB,
1093 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
1094 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1095 DebugLoc dl = MI->getDebugLoc();
1096 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1097 "Unexpected instr type to insert");
1099 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1100 // control-flow pattern. The incoming instruction knows the destination vreg
1101 // to set, the condition code register to branch on, the true/false values to
1102 // select between, and a branch opcode to use.
1103 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1104 MachineFunction::iterator It = BB;
1110 // cmpTY ccX, r1, r2
1112 // fallthrough --> copy0MBB
1113 MachineBasicBlock *thisMBB = BB;
1114 MachineFunction *F = BB->getParent();
1115 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1116 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1117 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1118 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1119 F->insert(It, copy0MBB);
1120 F->insert(It, sinkMBB);
1121 // Update machine-CFG edges by first adding all successors of the current
1122 // block to the new block which will contain the Phi node for the select.
1123 // Also inform sdisel of the edge changes.
1124 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1125 E = BB->succ_end(); I != E; ++I) {
1126 EM->insert(std::make_pair(*I, sinkMBB));
1127 sinkMBB->addSuccessor(*I);
1129 // Next, remove all successors of the current block, and add the true
1130 // and fallthrough blocks as its successors.
1131 while (!BB->succ_empty())
1132 BB->removeSuccessor(BB->succ_begin());
1133 // Next, add the true and fallthrough blocks as its successors.
1134 BB->addSuccessor(copy0MBB);
1135 BB->addSuccessor(sinkMBB);
1138 // %FalseValue = ...
1139 // # fallthrough to sinkMBB
1142 // Update machine-CFG edges
1143 BB->addSuccessor(sinkMBB);
1146 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1149 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1150 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1151 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1153 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1157 //===----------------------------------------------------------------------===//
1158 // Target Optimization Hooks
1159 //===----------------------------------------------------------------------===//
1161 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1162 DAGCombinerInfo &DCI) const {
1163 SelectionDAG &DAG = DCI.DAG;
1164 DebugLoc dl = N->getDebugLoc();
1165 switch (N->getOpcode()) {
1167 case XCoreISD::LADD: {
1168 SDValue N0 = N->getOperand(0);
1169 SDValue N1 = N->getOperand(1);
1170 SDValue N2 = N->getOperand(2);
1171 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1172 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1173 EVT VT = N0.getValueType();
1175 // canonicalize constant to RHS
1177 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1179 // fold (ladd 0, 0, x) -> 0, x & 1
1180 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1181 SDValue Carry = DAG.getConstant(0, VT);
1182 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1183 DAG.getConstant(1, VT));
1184 SDValue Ops [] = { Carry, Result };
1185 return DAG.getMergeValues(Ops, 2, dl);
1188 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1190 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1191 APInt KnownZero, KnownOne;
1192 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1193 VT.getSizeInBits() - 1);
1194 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1195 if (KnownZero == Mask) {
1196 SDValue Carry = DAG.getConstant(0, VT);
1197 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1198 SDValue Ops [] = { Carry, Result };
1199 return DAG.getMergeValues(Ops, 2, dl);
1204 case XCoreISD::LSUB: {
1205 SDValue N0 = N->getOperand(0);
1206 SDValue N1 = N->getOperand(1);
1207 SDValue N2 = N->getOperand(2);
1208 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1209 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1210 EVT VT = N0.getValueType();
1212 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1213 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1214 APInt KnownZero, KnownOne;
1215 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1216 VT.getSizeInBits() - 1);
1217 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1218 if (KnownZero == Mask) {
1219 SDValue Borrow = N2;
1220 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1221 DAG.getConstant(0, VT), N2);
1222 SDValue Ops [] = { Borrow, Result };
1223 return DAG.getMergeValues(Ops, 2, dl);
1227 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1229 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1230 APInt KnownZero, KnownOne;
1231 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1232 VT.getSizeInBits() - 1);
1233 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1234 if (KnownZero == Mask) {
1235 SDValue Borrow = DAG.getConstant(0, VT);
1236 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1237 SDValue Ops [] = { Borrow, Result };
1238 return DAG.getMergeValues(Ops, 2, dl);
1244 // Replace unaligned store of unaligned load with memmove.
1245 StoreSDNode *ST = cast<StoreSDNode>(N);
1246 if (!DCI.isBeforeLegalize() ||
1247 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1248 ST->isVolatile() || ST->isIndexed()) {
1251 SDValue Chain = ST->getChain();
1253 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1254 if (StoreBits % 8) {
1257 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1258 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1259 unsigned Alignment = ST->getAlignment();
1260 if (Alignment >= ABIAlignment) {
1264 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1265 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1266 LD->getAlignment() == Alignment &&
1267 !LD->isVolatile() && !LD->isIndexed() &&
1268 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1269 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1271 DAG.getConstant(StoreBits/8, MVT::i32),
1272 Alignment, ST->getSrcValue(),
1273 ST->getSrcValueOffset(), LD->getSrcValue(),
1274 LD->getSrcValueOffset());
1283 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1287 const SelectionDAG &DAG,
1288 unsigned Depth) const {
1289 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1290 switch (Op.getOpcode()) {
1292 case XCoreISD::LADD:
1293 case XCoreISD::LSUB:
1294 if (Op.getResNo() == 0) {
1295 // Top bits of carry / borrow are clear.
1296 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1297 Mask.getBitWidth() - 1);
1304 //===----------------------------------------------------------------------===//
1305 // Addressing mode description hooks
1306 //===----------------------------------------------------------------------===//
1308 static inline bool isImmUs(int64_t val)
1310 return (val >= 0 && val <= 11);
1313 static inline bool isImmUs2(int64_t val)
1315 return (val%2 == 0 && isImmUs(val/2));
1318 static inline bool isImmUs4(int64_t val)
1320 return (val%4 == 0 && isImmUs(val/4));
1323 /// isLegalAddressingMode - Return true if the addressing mode represented
1324 /// by AM is legal for this target, for a load/store of the specified type.
1326 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1327 const Type *Ty) const {
1328 if (Ty->getTypeID() == Type::VoidTyID)
1329 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1331 const TargetData *TD = TM.getTargetData();
1332 unsigned Size = TD->getTypeAllocSize(Ty);
1334 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1341 if (AM.Scale == 0) {
1342 return isImmUs(AM.BaseOffs);
1345 return AM.Scale == 1 && AM.BaseOffs == 0;
1349 if (AM.Scale == 0) {
1350 return isImmUs2(AM.BaseOffs);
1353 return AM.Scale == 2 && AM.BaseOffs == 0;
1356 if (AM.Scale == 0) {
1357 return isImmUs4(AM.BaseOffs);
1360 return AM.Scale == 4 && AM.BaseOffs == 0;
1366 //===----------------------------------------------------------------------===//
1367 // XCore Inline Assembly Support
1368 //===----------------------------------------------------------------------===//
1370 std::vector<unsigned> XCoreTargetLowering::
1371 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1374 if (Constraint.size() != 1)
1375 return std::vector<unsigned>();
1377 switch (Constraint[0]) {
1380 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1381 XCore::R3, XCore::R4, XCore::R5,
1382 XCore::R6, XCore::R7, XCore::R8,
1383 XCore::R9, XCore::R10, XCore::R11, 0);
1386 return std::vector<unsigned>();