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"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreTargetObjectFile.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.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::CRC8 : return "XCoreISD::CRC8";
61 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
62 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
63 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
64 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
65 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
66 default : return NULL;
70 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
71 : TargetLowering(XTM, new XCoreTargetObjectFile()),
73 Subtarget(*XTM.getSubtargetImpl()) {
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78 // Compute derived properties from the register classes
79 computeRegisterProperties();
81 // Division is expensive
82 setIntDivIsCheap(false);
84 setStackPointerRegisterToSaveRestore(XCore::SP);
86 setSchedulingPreference(Sched::Source);
88 // Use i32 for setcc operations results (slt, sgt, ...).
89 setBooleanContents(ZeroOrOneBooleanContent);
90 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
92 // XCore does not have the NodeTypes below.
93 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
94 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
95 setOperationAction(ISD::ADDC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDE, MVT::i32, Expand);
97 setOperationAction(ISD::SUBC, MVT::i32, Expand);
98 setOperationAction(ISD::SUBE, MVT::i32, Expand);
100 // Stop the combiner recombining select and set_cc
101 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
104 setOperationAction(ISD::ADD, MVT::i64, Custom);
105 setOperationAction(ISD::SUB, MVT::i64, Custom);
106 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
107 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
108 setOperationAction(ISD::MULHS, MVT::i32, Expand);
109 setOperationAction(ISD::MULHU, MVT::i32, Expand);
110 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
112 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
115 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
116 setOperationAction(ISD::ROTL , MVT::i32, Expand);
117 setOperationAction(ISD::ROTR , MVT::i32, Expand);
118 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
121 setOperationAction(ISD::TRAP, MVT::Other, Legal);
124 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
126 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
127 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
129 // Conversion of i64 -> double produces constantpool nodes
130 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
133 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
137 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
138 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
140 // Custom expand misaligned loads / stores.
141 setOperationAction(ISD::LOAD, MVT::i32, Custom);
142 setOperationAction(ISD::STORE, MVT::i32, Custom);
145 setOperationAction(ISD::VAEND, MVT::Other, Expand);
146 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
147 setOperationAction(ISD::VAARG, MVT::Other, Custom);
148 setOperationAction(ISD::VASTART, MVT::Other, Custom);
151 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
152 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
153 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
155 // Exception handling
156 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
157 setExceptionPointerRegister(XCore::R0);
158 setExceptionSelectorRegister(XCore::R1);
159 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
162 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
163 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
164 setInsertFencesForAtomic(true);
165 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
166 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
167 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
169 // TRAMPOLINE is custom lowered.
170 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
171 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
173 // We want to custom lower some of our intrinsics.
174 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
176 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
177 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
178 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
180 // We have target-specific dag combine patterns for the following nodes:
181 setTargetDAGCombine(ISD::STORE);
182 setTargetDAGCombine(ISD::ADD);
184 setMinFunctionAlignment(1);
185 setPrefFunctionAlignment(2);
188 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
189 if (Val.getOpcode() != ISD::LOAD)
192 EVT VT1 = Val.getValueType();
193 if (!VT1.isSimple() || !VT1.isInteger() ||
194 !VT2.isSimple() || !VT2.isInteger())
197 switch (VT1.getSimpleVT().SimpleTy) {
206 SDValue XCoreTargetLowering::
207 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
208 switch (Op.getOpcode())
210 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
211 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
212 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
213 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
214 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
215 case ISD::LOAD: return LowerLOAD(Op, DAG);
216 case ISD::STORE: return LowerSTORE(Op, DAG);
217 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
218 case ISD::VAARG: return LowerVAARG(Op, DAG);
219 case ISD::VASTART: return LowerVASTART(Op, DAG);
220 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
221 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
222 // FIXME: Remove these when LegalizeDAGTypes lands.
224 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
225 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
226 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
227 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
228 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
229 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
230 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
231 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
232 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
233 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
235 llvm_unreachable("unimplemented operand");
239 /// ReplaceNodeResults - Replace the results of node with an illegal result
240 /// type with new values built out of custom code.
241 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
242 SmallVectorImpl<SDValue>&Results,
243 SelectionDAG &DAG) const {
244 switch (N->getOpcode()) {
246 llvm_unreachable("Don't know how to custom expand this!");
249 Results.push_back(ExpandADDSUB(N, DAG));
254 //===----------------------------------------------------------------------===//
255 // Misc Lower Operation implementation
256 //===----------------------------------------------------------------------===//
258 SDValue XCoreTargetLowering::
259 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
262 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
263 Op.getOperand(3), Op.getOperand(4));
264 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
268 SDValue XCoreTargetLowering::
269 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
270 SelectionDAG &DAG) const
272 // FIXME there is no actual debug info here
274 const GlobalValue *UnderlyingGV = GV;
275 // If GV is an alias then use the aliasee to determine the wrapper type
276 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
277 UnderlyingGV = GA->resolveAliasedGlobal();
278 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
279 if ( ( GVar->isConstant() &&
280 UnderlyingGV->isLocalLinkage(GV->getLinkage()) )
281 || ( GVar->hasSection() &&
282 StringRef(GVar->getSection()).startswith(".cp.") ) )
283 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
284 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
286 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
289 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
290 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
293 Type *ObjType = GV->getType()->getPointerElementType();
294 if (!ObjType->isSized())
297 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
298 return ObjSize < CodeModelLargeSize && ObjSize != 0;
301 SDValue XCoreTargetLowering::
302 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
304 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
305 const GlobalValue *GV = GN->getGlobal();
307 int64_t Offset = GN->getOffset();
308 if (IsSmallObject(GV, *this)) {
309 // We can only fold positive offsets that are a multiple of the word size.
310 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
311 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
312 GA = getGlobalAddressWrapper(GA, GV, DAG);
313 // Handle the rest of the offset.
314 if (Offset != FoldedOffset) {
315 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
316 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
320 // Ideally we would not fold in offset with an index <= 11.
321 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
322 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
323 Ty = Type::getInt32Ty(*DAG.getContext());
324 Constant *Idx = ConstantInt::get(Ty, Offset);
325 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
326 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
327 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
328 MachinePointerInfo(), false, false, false, 0);
332 SDValue XCoreTargetLowering::
333 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
337 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
338 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
340 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
343 SDValue XCoreTargetLowering::
344 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
346 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
347 // FIXME there isn't really debug info here
349 EVT PtrVT = Op.getValueType();
351 if (CP->isMachineConstantPoolEntry()) {
352 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
353 CP->getAlignment(), CP->getOffset());
355 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
356 CP->getAlignment(), CP->getOffset());
358 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
361 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
362 return MachineJumpTableInfo::EK_Inline;
365 SDValue XCoreTargetLowering::
366 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
368 SDValue Chain = Op.getOperand(0);
369 SDValue Table = Op.getOperand(1);
370 SDValue Index = Op.getOperand(2);
372 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
373 unsigned JTI = JT->getIndex();
374 MachineFunction &MF = DAG.getMachineFunction();
375 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
376 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
378 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
379 if (NumEntries <= 32) {
380 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
382 assert((NumEntries >> 31) == 0);
383 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
384 DAG.getConstant(1, MVT::i32));
385 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
389 SDValue XCoreTargetLowering::
390 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
391 int64_t Offset, SelectionDAG &DAG) const
393 if ((Offset & 0x3) == 0) {
394 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
395 false, false, false, 0);
397 // Lower to pair of consecutive word aligned loads plus some bit shifting.
398 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
399 int32_t LowOffset = HighOffset - 4;
400 SDValue LowAddr, HighAddr;
401 if (GlobalAddressSDNode *GASD =
402 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
403 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
405 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
408 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
409 DAG.getConstant(LowOffset, MVT::i32));
410 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
411 DAG.getConstant(HighOffset, MVT::i32));
413 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
414 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
416 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
417 LowAddr, MachinePointerInfo(),
418 false, false, false, 0);
419 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
420 HighAddr, MachinePointerInfo(),
421 false, false, false, 0);
422 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
423 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
424 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
425 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
427 SDValue Ops[] = { Result, Chain };
428 return DAG.getMergeValues(Ops, 2, DL);
431 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
433 APInt KnownZero, KnownOne;
434 DAG.ComputeMaskedBits(Value, KnownZero, KnownOne);
435 return KnownZero.countTrailingOnes() >= 2;
438 SDValue XCoreTargetLowering::
439 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
440 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
441 LoadSDNode *LD = cast<LoadSDNode>(Op);
442 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
443 "Unexpected extension type");
444 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
445 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
448 unsigned ABIAlignment = getDataLayout()->
449 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
450 // Leave aligned load alone.
451 if (LD->getAlignment() >= ABIAlignment)
454 SDValue Chain = LD->getChain();
455 SDValue BasePtr = LD->getBasePtr();
458 if (!LD->isVolatile()) {
459 const GlobalValue *GV;
461 if (DAG.isBaseWithConstantOffset(BasePtr) &&
462 isWordAligned(BasePtr->getOperand(0), DAG)) {
463 SDValue NewBasePtr = BasePtr->getOperand(0);
464 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
465 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
468 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
469 MinAlign(GV->getAlignment(), 4) == 4) {
470 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
471 BasePtr->getValueType(0));
472 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
477 if (LD->getAlignment() == 2) {
478 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
479 BasePtr, LD->getPointerInfo(), MVT::i16,
480 LD->isVolatile(), LD->isNonTemporal(), 2);
481 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
482 DAG.getConstant(2, MVT::i32));
483 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
485 LD->getPointerInfo().getWithOffset(2),
486 MVT::i16, LD->isVolatile(),
487 LD->isNonTemporal(), 2);
488 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
489 DAG.getConstant(16, MVT::i32));
490 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
491 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
493 SDValue Ops[] = { Result, Chain };
494 return DAG.getMergeValues(Ops, 2, DL);
497 // Lower to a call to __misaligned_load(BasePtr).
498 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
499 TargetLowering::ArgListTy Args;
500 TargetLowering::ArgListEntry Entry;
503 Entry.Node = BasePtr;
504 Args.push_back(Entry);
506 TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
507 false, false, 0, CallingConv::C, /*isTailCall=*/false,
508 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
509 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
511 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
514 { CallResult.first, CallResult.second };
516 return DAG.getMergeValues(Ops, 2, DL);
519 SDValue XCoreTargetLowering::
520 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
522 StoreSDNode *ST = cast<StoreSDNode>(Op);
523 assert(!ST->isTruncatingStore() && "Unexpected store type");
524 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
525 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
528 unsigned ABIAlignment = getDataLayout()->
529 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
530 // Leave aligned store alone.
531 if (ST->getAlignment() >= ABIAlignment) {
534 SDValue Chain = ST->getChain();
535 SDValue BasePtr = ST->getBasePtr();
536 SDValue Value = ST->getValue();
539 if (ST->getAlignment() == 2) {
541 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
542 DAG.getConstant(16, MVT::i32));
543 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
544 ST->getPointerInfo(), MVT::i16,
545 ST->isVolatile(), ST->isNonTemporal(),
547 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
548 DAG.getConstant(2, MVT::i32));
549 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
550 ST->getPointerInfo().getWithOffset(2),
551 MVT::i16, ST->isVolatile(),
552 ST->isNonTemporal(), 2);
553 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
556 // Lower to a call to __misaligned_store(BasePtr, Value).
557 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
558 TargetLowering::ArgListTy Args;
559 TargetLowering::ArgListEntry Entry;
562 Entry.Node = BasePtr;
563 Args.push_back(Entry);
566 Args.push_back(Entry);
568 TargetLowering::CallLoweringInfo CLI(Chain,
569 Type::getVoidTy(*DAG.getContext()), false, false,
570 false, false, 0, CallingConv::C, /*isTailCall=*/false,
571 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
572 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
574 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
576 return CallResult.second;
579 SDValue XCoreTargetLowering::
580 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
582 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
583 "Unexpected operand to lower!");
585 SDValue LHS = Op.getOperand(0);
586 SDValue RHS = Op.getOperand(1);
587 SDValue Zero = DAG.getConstant(0, MVT::i32);
588 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
589 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
591 SDValue Lo(Hi.getNode(), 1);
592 SDValue Ops[] = { Lo, Hi };
593 return DAG.getMergeValues(Ops, 2, dl);
596 SDValue XCoreTargetLowering::
597 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
599 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
600 "Unexpected operand to lower!");
602 SDValue LHS = Op.getOperand(0);
603 SDValue RHS = Op.getOperand(1);
604 SDValue Zero = DAG.getConstant(0, MVT::i32);
605 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
606 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
608 SDValue Lo(Hi.getNode(), 1);
609 SDValue Ops[] = { Lo, Hi };
610 return DAG.getMergeValues(Ops, 2, dl);
613 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
614 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
615 /// each intermediate result in the calculation must also have a single use.
616 /// If the Op is in the correct form the constituent parts are written to Mul0,
617 /// Mul1, Addend0 and Addend1.
619 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
620 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
622 if (Op.getOpcode() != ISD::ADD)
624 SDValue N0 = Op.getOperand(0);
625 SDValue N1 = Op.getOperand(1);
628 if (N0.getOpcode() == ISD::ADD) {
631 } else if (N1.getOpcode() == ISD::ADD) {
637 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
639 if (OtherOp.getOpcode() == ISD::MUL) {
640 // add(add(a,b),mul(x,y))
641 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
643 Mul0 = OtherOp.getOperand(0);
644 Mul1 = OtherOp.getOperand(1);
645 Addend0 = AddOp.getOperand(0);
646 Addend1 = AddOp.getOperand(1);
649 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
650 // add(add(mul(x,y),a),b)
651 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
653 Mul0 = AddOp.getOperand(0).getOperand(0);
654 Mul1 = AddOp.getOperand(0).getOperand(1);
655 Addend0 = AddOp.getOperand(1);
659 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
660 // add(add(a,mul(x,y)),b)
661 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
663 Mul0 = AddOp.getOperand(1).getOperand(0);
664 Mul1 = AddOp.getOperand(1).getOperand(1);
665 Addend0 = AddOp.getOperand(0);
672 SDValue XCoreTargetLowering::
673 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
677 if (N->getOperand(0).getOpcode() == ISD::MUL) {
678 Mul = N->getOperand(0);
679 Other = N->getOperand(1);
680 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
681 Mul = N->getOperand(1);
682 Other = N->getOperand(0);
687 SDValue LL, RL, AddendL, AddendH;
688 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
689 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
690 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
692 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
693 Other, DAG.getConstant(0, MVT::i32));
694 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
695 Other, DAG.getConstant(1, MVT::i32));
696 APInt HighMask = APInt::getHighBitsSet(64, 32);
697 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
698 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
699 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
700 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
701 // The inputs are both zero-extended.
702 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
703 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
705 SDValue Lo(Hi.getNode(), 1);
706 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
708 if (LHSSB > 32 && RHSSB > 32) {
709 // The inputs are both sign-extended.
710 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
711 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
713 SDValue Lo(Hi.getNode(), 1);
714 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
717 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
718 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
719 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
720 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
721 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
722 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
724 SDValue Lo(Hi.getNode(), 1);
725 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
726 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
727 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
728 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
729 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
732 SDValue XCoreTargetLowering::
733 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
735 assert(N->getValueType(0) == MVT::i64 &&
736 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
737 "Unknown operand to lower!");
739 if (N->getOpcode() == ISD::ADD) {
740 SDValue Result = TryExpandADDWithMul(N, DAG);
741 if (Result.getNode() != 0)
747 // Extract components
748 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
749 N->getOperand(0), DAG.getConstant(0, MVT::i32));
750 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751 N->getOperand(0), DAG.getConstant(1, MVT::i32));
752 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
753 N->getOperand(1), DAG.getConstant(0, MVT::i32));
754 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
755 N->getOperand(1), DAG.getConstant(1, MVT::i32));
758 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
760 SDValue Zero = DAG.getConstant(0, MVT::i32);
761 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
763 SDValue Carry(Lo.getNode(), 1);
765 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
767 SDValue Ignored(Hi.getNode(), 1);
769 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
772 SDValue XCoreTargetLowering::
773 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
775 // Whist llvm does not support aggregate varargs we can ignore
776 // the possibility of the ValueType being an implicit byVal vararg.
777 SDNode *Node = Op.getNode();
778 EVT VT = Node->getValueType(0); // not an aggregate
779 SDValue InChain = Node->getOperand(0);
780 SDValue VAListPtr = Node->getOperand(1);
781 EVT PtrVT = VAListPtr.getValueType();
782 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
784 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
785 VAListPtr, MachinePointerInfo(SV),
786 false, false, false, 0);
787 // Increment the pointer, VAList, to the next vararg
788 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
789 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
790 // Store the incremented VAList to the legalized pointer
791 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
792 MachinePointerInfo(SV), false, false, 0);
793 // Load the actual argument out of the pointer VAList
794 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
795 false, false, false, 0);
798 SDValue XCoreTargetLowering::
799 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
802 // vastart stores the address of the VarArgsFrameIndex slot into the
803 // memory location argument
804 MachineFunction &MF = DAG.getMachineFunction();
805 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
806 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
807 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
808 MachinePointerInfo(), false, false, 0);
811 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
812 SelectionDAG &DAG) const {
813 // This nodes represent llvm.frameaddress on the DAG.
814 // It takes one operand, the index of the frame address to return.
815 // An index of zero corresponds to the current function's frame address.
816 // An index of one to the parent's frame address, and so on.
817 // Depths > 0 not supported yet!
818 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
821 MachineFunction &MF = DAG.getMachineFunction();
822 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
823 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
824 RegInfo->getFrameRegister(MF), MVT::i32);
827 SDValue XCoreTargetLowering::
828 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
829 // This nodes represent llvm.returnaddress on the DAG.
830 // It takes one operand, the index of the return address to return.
831 // An index of zero corresponds to the current function's return address.
832 // An index of one to the parent's return address, and so on.
833 // Depths > 0 not supported yet!
834 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
837 MachineFunction &MF = DAG.getMachineFunction();
838 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
839 int FI = XFI->createLRSpillSlot(MF);
840 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
841 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
842 MachinePointerInfo::getFixedStack(FI), false, false,
846 SDValue XCoreTargetLowering::
847 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
848 // This node represents offset from frame pointer to first on-stack argument.
849 // This is needed for correct stack adjustment during unwind.
850 // However, we don't know the offset until after the frame has be finalised.
851 // This is done during the XCoreFTAOElim pass.
852 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
855 SDValue XCoreTargetLowering::
856 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
857 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
858 // This node represents 'eh_return' gcc dwarf builtin, which is used to
859 // return from exception. The general meaning is: adjust stack by OFFSET and
860 // pass execution to HANDLER.
861 MachineFunction &MF = DAG.getMachineFunction();
862 SDValue Chain = Op.getOperand(0);
863 SDValue Offset = Op.getOperand(1);
864 SDValue Handler = Op.getOperand(2);
867 // Absolute SP = (FP + FrameToArgs) + Offset
868 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
869 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
870 RegInfo->getFrameRegister(MF), MVT::i32);
871 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
873 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
874 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
876 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
877 // which leaves 2 caller saved registers, R2 & R3 for us to use.
878 unsigned StackReg = XCore::R2;
879 unsigned HandlerReg = XCore::R3;
881 SDValue OutChains[] = {
882 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
883 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
886 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 2);
888 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
889 DAG.getRegister(StackReg, MVT::i32),
890 DAG.getRegister(HandlerReg, MVT::i32));
894 SDValue XCoreTargetLowering::
895 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
896 return Op.getOperand(0);
899 SDValue XCoreTargetLowering::
900 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
901 SDValue Chain = Op.getOperand(0);
902 SDValue Trmp = Op.getOperand(1); // trampoline
903 SDValue FPtr = Op.getOperand(2); // nested function
904 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
906 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
909 // LDAPF_u10 r11, nest
910 // LDW_2rus r11, r11[0]
911 // STWSP_ru6 r11, sp[0]
912 // LDAPF_u10 r11, fptr
913 // LDW_2rus r11, r11[0]
919 SDValue OutChains[5];
924 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
925 Addr, MachinePointerInfo(TrmpAddr), false, false,
928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
929 DAG.getConstant(4, MVT::i32));
930 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
931 Addr, MachinePointerInfo(TrmpAddr, 4), false,
934 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
935 DAG.getConstant(8, MVT::i32));
936 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
937 Addr, MachinePointerInfo(TrmpAddr, 8), false,
940 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
941 DAG.getConstant(12, MVT::i32));
942 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
943 MachinePointerInfo(TrmpAddr, 12), false, false,
946 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
947 DAG.getConstant(16, MVT::i32));
948 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
949 MachinePointerInfo(TrmpAddr, 16), false, false,
952 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
955 SDValue XCoreTargetLowering::
956 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
958 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
960 case Intrinsic::xcore_crc8:
961 EVT VT = Op.getValueType();
963 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
964 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
965 SDValue Crc(Data.getNode(), 1);
966 SDValue Results[] = { Crc, Data };
967 return DAG.getMergeValues(Results, 2, DL);
972 SDValue XCoreTargetLowering::
973 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
975 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
978 SDValue XCoreTargetLowering::
979 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
980 AtomicSDNode *N = cast<AtomicSDNode>(Op);
981 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
982 assert(N->getOrdering() <= Monotonic &&
983 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
984 if (N->getMemoryVT() == MVT::i32) {
985 if (N->getAlignment() < 4)
986 report_fatal_error("atomic load must be aligned");
987 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
988 N->getBasePtr(), N->getPointerInfo(),
989 N->isVolatile(), N->isNonTemporal(),
990 N->isInvariant(), N->getAlignment(),
991 N->getTBAAInfo(), N->getRanges());
993 if (N->getMemoryVT() == MVT::i16) {
994 if (N->getAlignment() < 2)
995 report_fatal_error("atomic load must be aligned");
996 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
997 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
998 N->isVolatile(), N->isNonTemporal(),
999 N->getAlignment(), N->getTBAAInfo());
1001 if (N->getMemoryVT() == MVT::i8)
1002 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
1003 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1004 N->isVolatile(), N->isNonTemporal(),
1005 N->getAlignment(), N->getTBAAInfo());
1009 SDValue XCoreTargetLowering::
1010 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1011 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1012 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1013 assert(N->getOrdering() <= Monotonic &&
1014 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1015 if (N->getMemoryVT() == MVT::i32) {
1016 if (N->getAlignment() < 4)
1017 report_fatal_error("atomic store must be aligned");
1018 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1019 N->getBasePtr(), N->getPointerInfo(),
1020 N->isVolatile(), N->isNonTemporal(),
1021 N->getAlignment(), N->getTBAAInfo());
1023 if (N->getMemoryVT() == MVT::i16) {
1024 if (N->getAlignment() < 2)
1025 report_fatal_error("atomic store must be aligned");
1026 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1027 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1028 N->isVolatile(), N->isNonTemporal(),
1029 N->getAlignment(), N->getTBAAInfo());
1031 if (N->getMemoryVT() == MVT::i8)
1032 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1033 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1034 N->isVolatile(), N->isNonTemporal(),
1035 N->getAlignment(), N->getTBAAInfo());
1039 //===----------------------------------------------------------------------===//
1040 // Calling Convention Implementation
1041 //===----------------------------------------------------------------------===//
1043 #include "XCoreGenCallingConv.inc"
1045 //===----------------------------------------------------------------------===//
1046 // Call Calling Convention Implementation
1047 //===----------------------------------------------------------------------===//
1049 /// XCore call implementation
1051 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1052 SmallVectorImpl<SDValue> &InVals) const {
1053 SelectionDAG &DAG = CLI.DAG;
1055 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1056 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1057 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1058 SDValue Chain = CLI.Chain;
1059 SDValue Callee = CLI.Callee;
1060 bool &isTailCall = CLI.IsTailCall;
1061 CallingConv::ID CallConv = CLI.CallConv;
1062 bool isVarArg = CLI.IsVarArg;
1064 // XCore target does not yet support tail call optimization.
1067 // For now, only CallingConv::C implemented
1071 llvm_unreachable("Unsupported calling convention");
1072 case CallingConv::Fast:
1073 case CallingConv::C:
1074 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1075 Outs, OutVals, Ins, dl, DAG, InVals);
1079 /// LowerCCCCallTo - functions arguments are copied from virtual
1080 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1081 /// CALLSEQ_END are emitted.
1082 /// TODO: isTailCall, sret.
1084 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1085 CallingConv::ID CallConv, bool isVarArg,
1087 const SmallVectorImpl<ISD::OutputArg> &Outs,
1088 const SmallVectorImpl<SDValue> &OutVals,
1089 const SmallVectorImpl<ISD::InputArg> &Ins,
1090 SDLoc dl, SelectionDAG &DAG,
1091 SmallVectorImpl<SDValue> &InVals) const {
1093 // Analyze operands of the call, assigning locations to each operand.
1094 SmallVector<CCValAssign, 16> ArgLocs;
1095 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1096 getTargetMachine(), ArgLocs, *DAG.getContext());
1098 // The ABI dictates there should be one stack slot available to the callee
1099 // on function entry (for saving lr).
1100 CCInfo.AllocateStack(4, 4);
1102 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1104 // Get a count of how many bytes are to be pushed on the stack.
1105 unsigned NumBytes = CCInfo.getNextStackOffset();
1107 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1108 getPointerTy(), true), dl);
1110 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1111 SmallVector<SDValue, 12> MemOpChains;
1113 // Walk the register/memloc assignments, inserting copies/loads.
1114 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1115 CCValAssign &VA = ArgLocs[i];
1116 SDValue Arg = OutVals[i];
1118 // Promote the value if needed.
1119 switch (VA.getLocInfo()) {
1120 default: llvm_unreachable("Unknown loc info!");
1121 case CCValAssign::Full: break;
1122 case CCValAssign::SExt:
1123 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1125 case CCValAssign::ZExt:
1126 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1128 case CCValAssign::AExt:
1129 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1133 // Arguments that can be passed on register must be kept at
1134 // RegsToPass vector
1135 if (VA.isRegLoc()) {
1136 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1138 assert(VA.isMemLoc());
1140 int Offset = VA.getLocMemOffset();
1142 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1144 DAG.getConstant(Offset/4, MVT::i32)));
1148 // Transform all store nodes into one single node because
1149 // all store nodes are independent of each other.
1150 if (!MemOpChains.empty())
1151 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1152 &MemOpChains[0], MemOpChains.size());
1154 // Build a sequence of copy-to-reg nodes chained together with token
1155 // chain and flag operands which copy the outgoing args into registers.
1156 // The InFlag in necessary since all emitted instructions must be
1159 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1160 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1161 RegsToPass[i].second, InFlag);
1162 InFlag = Chain.getValue(1);
1165 // If the callee is a GlobalAddress node (quite common, every direct call is)
1166 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1167 // Likewise ExternalSymbol -> TargetExternalSymbol.
1168 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1169 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1170 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1171 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1173 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1174 // = Chain, Callee, Reg#1, Reg#2, ...
1176 // Returns a chain & a flag for retval copy to use.
1177 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1178 SmallVector<SDValue, 8> Ops;
1179 Ops.push_back(Chain);
1180 Ops.push_back(Callee);
1182 // Add argument registers to the end of the list so that they are
1183 // known live into the call.
1184 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1185 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1186 RegsToPass[i].second.getValueType()));
1188 if (InFlag.getNode())
1189 Ops.push_back(InFlag);
1191 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1192 InFlag = Chain.getValue(1);
1194 // Create the CALLSEQ_END node.
1195 Chain = DAG.getCALLSEQ_END(Chain,
1196 DAG.getConstant(NumBytes, getPointerTy(), true),
1197 DAG.getConstant(0, getPointerTy(), true),
1199 InFlag = Chain.getValue(1);
1201 // Handle result values, copying them out of physregs into vregs that we
1203 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1204 Ins, dl, DAG, InVals);
1207 /// LowerCallResult - Lower the result values of a call into the
1208 /// appropriate copies out of appropriate physical registers.
1210 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1211 CallingConv::ID CallConv, bool isVarArg,
1212 const SmallVectorImpl<ISD::InputArg> &Ins,
1213 SDLoc dl, SelectionDAG &DAG,
1214 SmallVectorImpl<SDValue> &InVals) const {
1216 // Assign locations to each value returned by this call.
1217 SmallVector<CCValAssign, 16> RVLocs;
1218 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1219 getTargetMachine(), RVLocs, *DAG.getContext());
1221 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1223 // Copy all of the result registers out of their specified physreg.
1224 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1225 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1226 RVLocs[i].getValVT(), InFlag).getValue(1);
1227 InFlag = Chain.getValue(2);
1228 InVals.push_back(Chain.getValue(0));
1234 //===----------------------------------------------------------------------===//
1235 // Formal Arguments Calling Convention Implementation
1236 //===----------------------------------------------------------------------===//
1239 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1242 /// XCore formal arguments implementation
1244 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1245 CallingConv::ID CallConv,
1247 const SmallVectorImpl<ISD::InputArg> &Ins,
1250 SmallVectorImpl<SDValue> &InVals)
1255 llvm_unreachable("Unsupported calling convention");
1256 case CallingConv::C:
1257 case CallingConv::Fast:
1258 return LowerCCCArguments(Chain, CallConv, isVarArg,
1259 Ins, dl, DAG, InVals);
1263 /// LowerCCCArguments - transform physical registers into
1264 /// virtual registers and generate load operations for
1265 /// arguments places on the stack.
1268 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1269 CallingConv::ID CallConv,
1271 const SmallVectorImpl<ISD::InputArg>
1275 SmallVectorImpl<SDValue> &InVals) const {
1276 MachineFunction &MF = DAG.getMachineFunction();
1277 MachineFrameInfo *MFI = MF.getFrameInfo();
1278 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1280 // Assign locations to all of the incoming arguments.
1281 SmallVector<CCValAssign, 16> ArgLocs;
1282 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1283 getTargetMachine(), ArgLocs, *DAG.getContext());
1285 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1287 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1289 unsigned LRSaveSize = StackSlotSize;
1291 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1292 // scheduler clobbering a register before it has been copied.
1294 // 1. CopyFromReg (and load) arg & vararg registers.
1295 // 2. Chain CopyFromReg nodes into a TokenFactor.
1296 // 3. Memcpy 'byVal' args & push final InVals.
1297 // 4. Chain mem ops nodes into a TokenFactor.
1298 SmallVector<SDValue, 4> CFRegNode;
1299 SmallVector<ArgDataPair, 4> ArgData;
1300 SmallVector<SDValue, 4> MemOps;
1302 // 1a. CopyFromReg (and load) arg registers.
1303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1305 CCValAssign &VA = ArgLocs[i];
1308 if (VA.isRegLoc()) {
1309 // Arguments passed in registers
1310 EVT RegVT = VA.getLocVT();
1311 switch (RegVT.getSimpleVT().SimpleTy) {
1315 errs() << "LowerFormalArguments Unhandled argument type: "
1316 << RegVT.getSimpleVT().SimpleTy << "\n";
1318 llvm_unreachable(0);
1321 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1322 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1323 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1324 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1328 assert(VA.isMemLoc());
1329 // Load the argument to a virtual register
1330 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1331 if (ObjSize > StackSlotSize) {
1332 errs() << "LowerFormalArguments Unhandled argument type: "
1333 << EVT(VA.getLocVT()).getEVTString()
1336 // Create the frame index object for this incoming parameter...
1337 int FI = MFI->CreateFixedObject(ObjSize,
1338 LRSaveSize + VA.getLocMemOffset(),
1341 // Create the SelectionDAG nodes corresponding to a load
1342 //from this parameter
1343 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1344 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1345 MachinePointerInfo::getFixedStack(FI),
1346 false, false, false, 0);
1348 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1349 ArgData.push_back(ADP);
1352 // 1b. CopyFromReg vararg registers.
1354 // Argument registers
1355 static const uint16_t ArgRegs[] = {
1356 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1358 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1359 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1360 array_lengthof(ArgRegs));
1361 if (FirstVAReg < array_lengthof(ArgRegs)) {
1363 // Save remaining registers, storing higher register numbers at a higher
1365 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1366 // Create a stack slot
1367 int FI = MFI->CreateFixedObject(4, offset, true);
1368 if (i == (int)FirstVAReg) {
1369 XFI->setVarArgsFrameIndex(FI);
1371 offset -= StackSlotSize;
1372 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1373 // Move argument from phys reg -> virt reg
1374 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1375 RegInfo.addLiveIn(ArgRegs[i], VReg);
1376 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1377 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1378 // Move argument from virt reg -> stack
1379 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1380 MachinePointerInfo(), false, false, 0);
1381 MemOps.push_back(Store);
1384 // This will point to the next argument passed via stack.
1385 XFI->setVarArgsFrameIndex(
1386 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1391 // 2. chain CopyFromReg nodes into a TokenFactor.
1392 if (!CFRegNode.empty())
1393 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &CFRegNode[0],
1396 // 3. Memcpy 'byVal' args & push final InVals.
1397 // Aggregates passed "byVal" need to be copied by the callee.
1398 // The callee will use a pointer to this copy, rather than the original
1400 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1401 ArgDE = ArgData.end();
1402 ArgDI != ArgDE; ++ArgDI) {
1403 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1404 unsigned Size = ArgDI->Flags.getByValSize();
1405 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1406 // Create a new object on the stack and copy the pointee into it.
1407 int FI = MFI->CreateStackObject(Size, Align, false);
1408 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1409 InVals.push_back(FIN);
1410 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1411 DAG.getConstant(Size, MVT::i32),
1412 Align, false, false,
1413 MachinePointerInfo(),
1414 MachinePointerInfo()));
1416 InVals.push_back(ArgDI->SDV);
1420 // 4, chain mem ops nodes into a TokenFactor.
1421 if (!MemOps.empty()) {
1422 MemOps.push_back(Chain);
1423 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
1430 //===----------------------------------------------------------------------===//
1431 // Return Value Calling Convention Implementation
1432 //===----------------------------------------------------------------------===//
1434 bool XCoreTargetLowering::
1435 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1437 const SmallVectorImpl<ISD::OutputArg> &Outs,
1438 LLVMContext &Context) const {
1439 SmallVector<CCValAssign, 16> RVLocs;
1440 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1441 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1445 XCoreTargetLowering::LowerReturn(SDValue Chain,
1446 CallingConv::ID CallConv, bool isVarArg,
1447 const SmallVectorImpl<ISD::OutputArg> &Outs,
1448 const SmallVectorImpl<SDValue> &OutVals,
1449 SDLoc dl, SelectionDAG &DAG) const {
1451 // CCValAssign - represent the assignment of
1452 // the return value to a location
1453 SmallVector<CCValAssign, 16> RVLocs;
1455 // CCState - Info about the registers and stack slot.
1456 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1457 getTargetMachine(), RVLocs, *DAG.getContext());
1459 // Analyze return values.
1460 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1463 SmallVector<SDValue, 4> RetOps(1, Chain);
1465 // Return on XCore is always a "retsp 0"
1466 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1468 // Copy the result values into the output registers.
1469 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1470 CCValAssign &VA = RVLocs[i];
1471 assert(VA.isRegLoc() && "Can only return in registers!");
1473 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1476 // guarantee that all emitted copies are
1477 // stuck together, avoiding something bad
1478 Flag = Chain.getValue(1);
1479 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1482 RetOps[0] = Chain; // Update chain.
1484 // Add the flag if we have it.
1486 RetOps.push_back(Flag);
1488 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1489 &RetOps[0], RetOps.size());
1492 //===----------------------------------------------------------------------===//
1493 // Other Lowering Code
1494 //===----------------------------------------------------------------------===//
1497 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1498 MachineBasicBlock *BB) const {
1499 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1500 DebugLoc dl = MI->getDebugLoc();
1501 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1502 "Unexpected instr type to insert");
1504 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1505 // control-flow pattern. The incoming instruction knows the destination vreg
1506 // to set, the condition code register to branch on, the true/false values to
1507 // select between, and a branch opcode to use.
1508 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1509 MachineFunction::iterator It = BB;
1515 // cmpTY ccX, r1, r2
1517 // fallthrough --> copy0MBB
1518 MachineBasicBlock *thisMBB = BB;
1519 MachineFunction *F = BB->getParent();
1520 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1521 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1522 F->insert(It, copy0MBB);
1523 F->insert(It, sinkMBB);
1525 // Transfer the remainder of BB and its successor edges to sinkMBB.
1526 sinkMBB->splice(sinkMBB->begin(), BB,
1527 llvm::next(MachineBasicBlock::iterator(MI)),
1529 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1531 // Next, add the true and fallthrough blocks as its successors.
1532 BB->addSuccessor(copy0MBB);
1533 BB->addSuccessor(sinkMBB);
1535 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1536 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1539 // %FalseValue = ...
1540 // # fallthrough to sinkMBB
1543 // Update machine-CFG edges
1544 BB->addSuccessor(sinkMBB);
1547 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1550 BuildMI(*BB, BB->begin(), dl,
1551 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1552 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1553 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1555 MI->eraseFromParent(); // The pseudo instruction is gone now.
1559 //===----------------------------------------------------------------------===//
1560 // Target Optimization Hooks
1561 //===----------------------------------------------------------------------===//
1563 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1564 DAGCombinerInfo &DCI) const {
1565 SelectionDAG &DAG = DCI.DAG;
1567 switch (N->getOpcode()) {
1569 case XCoreISD::LADD: {
1570 SDValue N0 = N->getOperand(0);
1571 SDValue N1 = N->getOperand(1);
1572 SDValue N2 = N->getOperand(2);
1573 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1575 EVT VT = N0.getValueType();
1577 // canonicalize constant to RHS
1579 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1581 // fold (ladd 0, 0, x) -> 0, x & 1
1582 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1583 SDValue Carry = DAG.getConstant(0, VT);
1584 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1585 DAG.getConstant(1, VT));
1586 SDValue Ops[] = { Result, Carry };
1587 return DAG.getMergeValues(Ops, 2, dl);
1590 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1592 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1593 APInt KnownZero, KnownOne;
1594 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1595 VT.getSizeInBits() - 1);
1596 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1597 if ((KnownZero & Mask) == Mask) {
1598 SDValue Carry = DAG.getConstant(0, VT);
1599 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1600 SDValue Ops[] = { Result, Carry };
1601 return DAG.getMergeValues(Ops, 2, dl);
1606 case XCoreISD::LSUB: {
1607 SDValue N0 = N->getOperand(0);
1608 SDValue N1 = N->getOperand(1);
1609 SDValue N2 = N->getOperand(2);
1610 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1611 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1612 EVT VT = N0.getValueType();
1614 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1615 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1616 APInt KnownZero, KnownOne;
1617 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1618 VT.getSizeInBits() - 1);
1619 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1620 if ((KnownZero & Mask) == Mask) {
1621 SDValue Borrow = N2;
1622 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1623 DAG.getConstant(0, VT), N2);
1624 SDValue Ops[] = { Result, Borrow };
1625 return DAG.getMergeValues(Ops, 2, dl);
1629 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1631 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1632 APInt KnownZero, KnownOne;
1633 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1634 VT.getSizeInBits() - 1);
1635 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1636 if ((KnownZero & Mask) == Mask) {
1637 SDValue Borrow = DAG.getConstant(0, VT);
1638 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1639 SDValue Ops[] = { Result, Borrow };
1640 return DAG.getMergeValues(Ops, 2, dl);
1645 case XCoreISD::LMUL: {
1646 SDValue N0 = N->getOperand(0);
1647 SDValue N1 = N->getOperand(1);
1648 SDValue N2 = N->getOperand(2);
1649 SDValue N3 = N->getOperand(3);
1650 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1651 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1652 EVT VT = N0.getValueType();
1653 // Canonicalize multiplicative constant to RHS. If both multiplicative
1654 // operands are constant canonicalize smallest to RHS.
1655 if ((N0C && !N1C) ||
1656 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1657 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1661 if (N1C && N1C->isNullValue()) {
1662 // If the high result is unused fold to add(a, b)
1663 if (N->hasNUsesOfValue(0, 0)) {
1664 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1665 SDValue Ops[] = { Lo, Lo };
1666 return DAG.getMergeValues(Ops, 2, dl);
1668 // Otherwise fold to ladd(a, b, 0)
1670 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1671 SDValue Carry(Result.getNode(), 1);
1672 SDValue Ops[] = { Carry, Result };
1673 return DAG.getMergeValues(Ops, 2, dl);
1678 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1679 // lmul(x, y, a, b). The high result of lmul will be ignored.
1680 // This is only profitable if the intermediate results are unused
1682 SDValue Mul0, Mul1, Addend0, Addend1;
1683 if (N->getValueType(0) == MVT::i32 &&
1684 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1685 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1686 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1687 Mul1, Addend0, Addend1);
1688 SDValue Result(Ignored.getNode(), 1);
1691 APInt HighMask = APInt::getHighBitsSet(64, 32);
1692 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1693 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1694 // before type legalization as it is messy to match the operands after
1696 if (N->getValueType(0) == MVT::i64 &&
1697 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1698 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1699 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1700 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1701 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1702 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1703 Mul0, DAG.getConstant(0, MVT::i32));
1704 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1705 Mul1, DAG.getConstant(0, MVT::i32));
1706 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1707 Addend0, DAG.getConstant(0, MVT::i32));
1708 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1709 Addend1, DAG.getConstant(0, MVT::i32));
1710 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1711 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1712 Addend0L, Addend1L);
1713 SDValue Lo(Hi.getNode(), 1);
1714 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1719 // Replace unaligned store of unaligned load with memmove.
1720 StoreSDNode *ST = cast<StoreSDNode>(N);
1721 if (!DCI.isBeforeLegalize() ||
1722 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1723 ST->isVolatile() || ST->isIndexed()) {
1726 SDValue Chain = ST->getChain();
1728 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1729 if (StoreBits % 8) {
1732 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1733 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1734 unsigned Alignment = ST->getAlignment();
1735 if (Alignment >= ABIAlignment) {
1739 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1740 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1741 LD->getAlignment() == Alignment &&
1742 !LD->isVolatile() && !LD->isIndexed() &&
1743 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1744 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1746 DAG.getConstant(StoreBits/8, MVT::i32),
1747 Alignment, false, ST->getPointerInfo(),
1748 LD->getPointerInfo());
1757 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1760 const SelectionDAG &DAG,
1761 unsigned Depth) const {
1762 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1763 switch (Op.getOpcode()) {
1765 case XCoreISD::LADD:
1766 case XCoreISD::LSUB:
1767 if (Op.getResNo() == 1) {
1768 // Top bits of carry / borrow are clear.
1769 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1770 KnownZero.getBitWidth() - 1);
1773 case ISD::INTRINSIC_W_CHAIN:
1775 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1777 case Intrinsic::xcore_getts:
1778 // High bits are known to be zero.
1779 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1780 KnownZero.getBitWidth() - 16);
1782 case Intrinsic::xcore_int:
1783 case Intrinsic::xcore_inct:
1784 // High bits are known to be zero.
1785 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1786 KnownZero.getBitWidth() - 8);
1788 case Intrinsic::xcore_testct:
1789 // Result is either 0 or 1.
1790 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1791 KnownZero.getBitWidth() - 1);
1793 case Intrinsic::xcore_testwct:
1794 // Result is in the range 0 - 4.
1795 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1796 KnownZero.getBitWidth() - 3);
1804 //===----------------------------------------------------------------------===//
1805 // Addressing mode description hooks
1806 //===----------------------------------------------------------------------===//
1808 static inline bool isImmUs(int64_t val)
1810 return (val >= 0 && val <= 11);
1813 static inline bool isImmUs2(int64_t val)
1815 return (val%2 == 0 && isImmUs(val/2));
1818 static inline bool isImmUs4(int64_t val)
1820 return (val%4 == 0 && isImmUs(val/4));
1823 /// isLegalAddressingMode - Return true if the addressing mode represented
1824 /// by AM is legal for this target, for a load/store of the specified type.
1826 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1828 if (Ty->getTypeID() == Type::VoidTyID)
1829 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1831 const DataLayout *TD = TM.getDataLayout();
1832 unsigned Size = TD->getTypeAllocSize(Ty);
1834 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1841 if (AM.Scale == 0) {
1842 return isImmUs(AM.BaseOffs);
1845 return AM.Scale == 1 && AM.BaseOffs == 0;
1849 if (AM.Scale == 0) {
1850 return isImmUs2(AM.BaseOffs);
1853 return AM.Scale == 2 && AM.BaseOffs == 0;
1856 if (AM.Scale == 0) {
1857 return isImmUs4(AM.BaseOffs);
1860 return AM.Scale == 4 && AM.BaseOffs == 0;
1864 //===----------------------------------------------------------------------===//
1865 // XCore Inline Assembly Support
1866 //===----------------------------------------------------------------------===//
1868 std::pair<unsigned, const TargetRegisterClass*>
1869 XCoreTargetLowering::
1870 getRegForInlineAsmConstraint(const std::string &Constraint,
1872 if (Constraint.size() == 1) {
1873 switch (Constraint[0]) {
1876 return std::make_pair(0U, &XCore::GRRegsRegClass);
1879 // Use the default implementation in TargetLowering to convert the register
1880 // constraint into a member of a register class.
1881 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);