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 #include "XCoreISelLowering.h"
16 #include "XCoreMachineFunctionInfo.h"
17 #include "XCoreSubtarget.h"
18 #include "XCoreTargetMachine.h"
19 #include "XCoreTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "xcore-lower"
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::LDWSP : return "XCoreISD::LDWSP";
54 case XCoreISD::STWSP : return "XCoreISD::STWSP";
55 case XCoreISD::RETSP : return "XCoreISD::RETSP";
56 case XCoreISD::LADD : return "XCoreISD::LADD";
57 case XCoreISD::LSUB : return "XCoreISD::LSUB";
58 case XCoreISD::LMUL : return "XCoreISD::LMUL";
59 case XCoreISD::MACCU : return "XCoreISD::MACCU";
60 case XCoreISD::MACCS : return "XCoreISD::MACCS";
61 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
62 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
63 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
64 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
65 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
66 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
67 default : return nullptr;
71 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
72 : TargetLowering(XTM, new XCoreTargetObjectFile()),
74 Subtarget(*XTM.getSubtargetImpl()) {
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
79 // Compute derived properties from the register classes
80 computeRegisterProperties();
82 // Division is expensive
83 setIntDivIsCheap(false);
85 setStackPointerRegisterToSaveRestore(XCore::SP);
87 setSchedulingPreference(Sched::Source);
89 // Use i32 for setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // XCore does not have the NodeTypes below.
94 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
95 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDC, MVT::i32, Expand);
97 setOperationAction(ISD::ADDE, MVT::i32, Expand);
98 setOperationAction(ISD::SUBC, MVT::i32, Expand);
99 setOperationAction(ISD::SUBE, MVT::i32, Expand);
101 // Stop the combiner recombining select and set_cc
102 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
105 setOperationAction(ISD::ADD, MVT::i64, Custom);
106 setOperationAction(ISD::SUB, MVT::i64, Custom);
107 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
108 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
109 setOperationAction(ISD::MULHS, MVT::i32, Expand);
110 setOperationAction(ISD::MULHU, MVT::i32, Expand);
111 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
112 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
113 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
116 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
117 setOperationAction(ISD::ROTL , MVT::i32, Expand);
118 setOperationAction(ISD::ROTR , MVT::i32, Expand);
119 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
120 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
122 setOperationAction(ISD::TRAP, MVT::Other, Legal);
125 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
127 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
130 // Conversion of i64 -> double produces constantpool nodes
131 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
134 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
136 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
138 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
139 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
141 // Custom expand misaligned loads / stores.
142 setOperationAction(ISD::LOAD, MVT::i32, Custom);
143 setOperationAction(ISD::STORE, MVT::i32, Custom);
146 setOperationAction(ISD::VAEND, MVT::Other, Expand);
147 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
148 setOperationAction(ISD::VAARG, MVT::Other, Custom);
149 setOperationAction(ISD::VASTART, MVT::Other, Custom);
152 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
153 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
154 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
156 // Exception handling
157 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
158 setExceptionPointerRegister(XCore::R0);
159 setExceptionSelectorRegister(XCore::R1);
160 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
163 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
164 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
165 setInsertFencesForAtomic(true);
166 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
167 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
168 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
170 // TRAMPOLINE is custom lowered.
171 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
172 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
174 // We want to custom lower some of our intrinsics.
175 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
177 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
178 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
179 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
181 // We have target-specific dag combine patterns for the following nodes:
182 setTargetDAGCombine(ISD::STORE);
183 setTargetDAGCombine(ISD::ADD);
184 setTargetDAGCombine(ISD::INTRINSIC_VOID);
185 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
187 setMinFunctionAlignment(1);
188 setPrefFunctionAlignment(2);
191 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
192 if (Val.getOpcode() != ISD::LOAD)
195 EVT VT1 = Val.getValueType();
196 if (!VT1.isSimple() || !VT1.isInteger() ||
197 !VT2.isSimple() || !VT2.isInteger())
200 switch (VT1.getSimpleVT().SimpleTy) {
209 SDValue XCoreTargetLowering::
210 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
211 switch (Op.getOpcode())
213 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
214 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
215 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
216 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
217 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
218 case ISD::LOAD: return LowerLOAD(Op, DAG);
219 case ISD::STORE: return LowerSTORE(Op, DAG);
220 case ISD::VAARG: return LowerVAARG(Op, DAG);
221 case ISD::VASTART: return LowerVASTART(Op, DAG);
222 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
223 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
224 // FIXME: Remove these when LegalizeDAGTypes lands.
226 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
227 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
228 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
229 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
230 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
231 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
232 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
233 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
234 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
235 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
237 llvm_unreachable("unimplemented operand");
241 /// ReplaceNodeResults - Replace the results of node with an illegal result
242 /// type with new values built out of custom code.
243 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
244 SmallVectorImpl<SDValue>&Results,
245 SelectionDAG &DAG) const {
246 switch (N->getOpcode()) {
248 llvm_unreachable("Don't know how to custom expand this!");
251 Results.push_back(ExpandADDSUB(N, DAG));
256 //===----------------------------------------------------------------------===//
257 // Misc Lower Operation implementation
258 //===----------------------------------------------------------------------===//
260 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
261 const GlobalValue *GV,
262 SelectionDAG &DAG) const {
263 // FIXME there is no actual debug info here
266 if (GV->getType()->getElementType()->isFunctionTy())
267 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
269 const auto *GVar = dyn_cast<GlobalVariable>(GV);
270 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
271 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
272 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
274 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
277 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
278 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
281 Type *ObjType = GV->getType()->getPointerElementType();
282 if (!ObjType->isSized())
285 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
286 return ObjSize < CodeModelLargeSize && ObjSize != 0;
289 SDValue XCoreTargetLowering::
290 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
292 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
293 const GlobalValue *GV = GN->getGlobal();
295 int64_t Offset = GN->getOffset();
296 if (IsSmallObject(GV, *this)) {
297 // We can only fold positive offsets that are a multiple of the word size.
298 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
299 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
300 GA = getGlobalAddressWrapper(GA, GV, DAG);
301 // Handle the rest of the offset.
302 if (Offset != FoldedOffset) {
303 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
304 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
308 // Ideally we would not fold in offset with an index <= 11.
309 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
310 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
311 Ty = Type::getInt32Ty(*DAG.getContext());
312 Constant *Idx = ConstantInt::get(Ty, Offset);
313 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
314 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
315 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
316 MachinePointerInfo(), false, false, false, 0);
320 SDValue XCoreTargetLowering::
321 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
325 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
326 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
328 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
331 SDValue XCoreTargetLowering::
332 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
334 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
335 // FIXME there isn't really debug info here
337 EVT PtrVT = Op.getValueType();
339 if (CP->isMachineConstantPoolEntry()) {
340 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
341 CP->getAlignment(), CP->getOffset());
343 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
344 CP->getAlignment(), CP->getOffset());
346 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
349 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
350 return MachineJumpTableInfo::EK_Inline;
353 SDValue XCoreTargetLowering::
354 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
356 SDValue Chain = Op.getOperand(0);
357 SDValue Table = Op.getOperand(1);
358 SDValue Index = Op.getOperand(2);
360 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
361 unsigned JTI = JT->getIndex();
362 MachineFunction &MF = DAG.getMachineFunction();
363 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
364 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
366 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
367 if (NumEntries <= 32) {
368 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
370 assert((NumEntries >> 31) == 0);
371 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
372 DAG.getConstant(1, MVT::i32));
373 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
377 SDValue XCoreTargetLowering::
378 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
379 int64_t Offset, SelectionDAG &DAG) const
381 if ((Offset & 0x3) == 0) {
382 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
383 false, false, false, 0);
385 // Lower to pair of consecutive word aligned loads plus some bit shifting.
386 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
387 int32_t LowOffset = HighOffset - 4;
388 SDValue LowAddr, HighAddr;
389 if (GlobalAddressSDNode *GASD =
390 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
391 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
393 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
396 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
397 DAG.getConstant(LowOffset, MVT::i32));
398 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
399 DAG.getConstant(HighOffset, MVT::i32));
401 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
402 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
404 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
405 LowAddr, MachinePointerInfo(),
406 false, false, false, 0);
407 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
408 HighAddr, MachinePointerInfo(),
409 false, false, false, 0);
410 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
411 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
412 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
413 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
415 SDValue Ops[] = { Result, Chain };
416 return DAG.getMergeValues(Ops, DL);
419 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
421 APInt KnownZero, KnownOne;
422 DAG.computeKnownBits(Value, KnownZero, KnownOne);
423 return KnownZero.countTrailingOnes() >= 2;
426 SDValue XCoreTargetLowering::
427 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
428 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
429 LoadSDNode *LD = cast<LoadSDNode>(Op);
430 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
431 "Unexpected extension type");
432 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
433 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
436 unsigned ABIAlignment = getDataLayout()->
437 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
438 // Leave aligned load alone.
439 if (LD->getAlignment() >= ABIAlignment)
442 SDValue Chain = LD->getChain();
443 SDValue BasePtr = LD->getBasePtr();
446 if (!LD->isVolatile()) {
447 const GlobalValue *GV;
449 if (DAG.isBaseWithConstantOffset(BasePtr) &&
450 isWordAligned(BasePtr->getOperand(0), DAG)) {
451 SDValue NewBasePtr = BasePtr->getOperand(0);
452 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
453 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
456 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
457 MinAlign(GV->getAlignment(), 4) == 4) {
458 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
459 BasePtr->getValueType(0));
460 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
465 if (LD->getAlignment() == 2) {
466 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
467 BasePtr, LD->getPointerInfo(), MVT::i16,
468 LD->isVolatile(), LD->isNonTemporal(), 2);
469 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
470 DAG.getConstant(2, MVT::i32));
471 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
473 LD->getPointerInfo().getWithOffset(2),
474 MVT::i16, LD->isVolatile(),
475 LD->isNonTemporal(), 2);
476 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
477 DAG.getConstant(16, MVT::i32));
478 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
479 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
481 SDValue Ops[] = { Result, Chain };
482 return DAG.getMergeValues(Ops, DL);
485 // Lower to a call to __misaligned_load(BasePtr).
486 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
487 TargetLowering::ArgListTy Args;
488 TargetLowering::ArgListEntry Entry;
491 Entry.Node = BasePtr;
492 Args.push_back(Entry);
494 TargetLowering::CallLoweringInfo CLI(DAG);
495 CLI.setDebugLoc(DL).setChain(Chain)
496 .setCallee(CallingConv::C, IntPtrTy,
497 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
500 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
501 SDValue Ops[] = { CallResult.first, CallResult.second };
502 return DAG.getMergeValues(Ops, DL);
505 SDValue XCoreTargetLowering::
506 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
508 StoreSDNode *ST = cast<StoreSDNode>(Op);
509 assert(!ST->isTruncatingStore() && "Unexpected store type");
510 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
511 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
514 unsigned ABIAlignment = getDataLayout()->
515 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
516 // Leave aligned store alone.
517 if (ST->getAlignment() >= ABIAlignment) {
520 SDValue Chain = ST->getChain();
521 SDValue BasePtr = ST->getBasePtr();
522 SDValue Value = ST->getValue();
525 if (ST->getAlignment() == 2) {
527 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
528 DAG.getConstant(16, MVT::i32));
529 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
530 ST->getPointerInfo(), MVT::i16,
531 ST->isVolatile(), ST->isNonTemporal(),
533 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
534 DAG.getConstant(2, MVT::i32));
535 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
536 ST->getPointerInfo().getWithOffset(2),
537 MVT::i16, ST->isVolatile(),
538 ST->isNonTemporal(), 2);
539 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
542 // Lower to a call to __misaligned_store(BasePtr, Value).
543 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
544 TargetLowering::ArgListTy Args;
545 TargetLowering::ArgListEntry Entry;
548 Entry.Node = BasePtr;
549 Args.push_back(Entry);
552 Args.push_back(Entry);
554 TargetLowering::CallLoweringInfo CLI(DAG);
555 CLI.setDebugLoc(dl).setChain(Chain)
556 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
557 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
560 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
561 return CallResult.second;
564 SDValue XCoreTargetLowering::
565 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
567 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
568 "Unexpected operand to lower!");
570 SDValue LHS = Op.getOperand(0);
571 SDValue RHS = Op.getOperand(1);
572 SDValue Zero = DAG.getConstant(0, MVT::i32);
573 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
574 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
576 SDValue Lo(Hi.getNode(), 1);
577 SDValue Ops[] = { Lo, Hi };
578 return DAG.getMergeValues(Ops, dl);
581 SDValue XCoreTargetLowering::
582 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
584 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
585 "Unexpected operand to lower!");
587 SDValue LHS = Op.getOperand(0);
588 SDValue RHS = Op.getOperand(1);
589 SDValue Zero = DAG.getConstant(0, MVT::i32);
590 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
591 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
593 SDValue Lo(Hi.getNode(), 1);
594 SDValue Ops[] = { Lo, Hi };
595 return DAG.getMergeValues(Ops, dl);
598 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
599 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
600 /// each intermediate result in the calculation must also have a single use.
601 /// If the Op is in the correct form the constituent parts are written to Mul0,
602 /// Mul1, Addend0 and Addend1.
604 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
605 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
607 if (Op.getOpcode() != ISD::ADD)
609 SDValue N0 = Op.getOperand(0);
610 SDValue N1 = Op.getOperand(1);
613 if (N0.getOpcode() == ISD::ADD) {
616 } else if (N1.getOpcode() == ISD::ADD) {
622 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
624 if (OtherOp.getOpcode() == ISD::MUL) {
625 // add(add(a,b),mul(x,y))
626 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
628 Mul0 = OtherOp.getOperand(0);
629 Mul1 = OtherOp.getOperand(1);
630 Addend0 = AddOp.getOperand(0);
631 Addend1 = AddOp.getOperand(1);
634 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
635 // add(add(mul(x,y),a),b)
636 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
638 Mul0 = AddOp.getOperand(0).getOperand(0);
639 Mul1 = AddOp.getOperand(0).getOperand(1);
640 Addend0 = AddOp.getOperand(1);
644 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
645 // add(add(a,mul(x,y)),b)
646 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
648 Mul0 = AddOp.getOperand(1).getOperand(0);
649 Mul1 = AddOp.getOperand(1).getOperand(1);
650 Addend0 = AddOp.getOperand(0);
657 SDValue XCoreTargetLowering::
658 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
662 if (N->getOperand(0).getOpcode() == ISD::MUL) {
663 Mul = N->getOperand(0);
664 Other = N->getOperand(1);
665 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
666 Mul = N->getOperand(1);
667 Other = N->getOperand(0);
672 SDValue LL, RL, AddendL, AddendH;
673 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
674 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
675 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
676 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
677 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
678 Other, DAG.getConstant(0, MVT::i32));
679 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
680 Other, DAG.getConstant(1, MVT::i32));
681 APInt HighMask = APInt::getHighBitsSet(64, 32);
682 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
683 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
684 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
685 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
686 // The inputs are both zero-extended.
687 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
688 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
690 SDValue Lo(Hi.getNode(), 1);
691 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
693 if (LHSSB > 32 && RHSSB > 32) {
694 // The inputs are both sign-extended.
695 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
696 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
698 SDValue Lo(Hi.getNode(), 1);
699 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
702 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
703 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
704 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
705 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
706 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
707 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
709 SDValue Lo(Hi.getNode(), 1);
710 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
711 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
712 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
713 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
714 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
717 SDValue XCoreTargetLowering::
718 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
720 assert(N->getValueType(0) == MVT::i64 &&
721 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
722 "Unknown operand to lower!");
724 if (N->getOpcode() == ISD::ADD) {
725 SDValue Result = TryExpandADDWithMul(N, DAG);
726 if (Result.getNode())
732 // Extract components
733 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
734 N->getOperand(0), DAG.getConstant(0, MVT::i32));
735 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
736 N->getOperand(0), DAG.getConstant(1, MVT::i32));
737 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
738 N->getOperand(1), DAG.getConstant(0, MVT::i32));
739 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
740 N->getOperand(1), DAG.getConstant(1, MVT::i32));
743 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
745 SDValue Zero = DAG.getConstant(0, MVT::i32);
746 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
748 SDValue Carry(Lo.getNode(), 1);
750 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
752 SDValue Ignored(Hi.getNode(), 1);
754 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
757 SDValue XCoreTargetLowering::
758 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
760 // Whist llvm does not support aggregate varargs we can ignore
761 // the possibility of the ValueType being an implicit byVal vararg.
762 SDNode *Node = Op.getNode();
763 EVT VT = Node->getValueType(0); // not an aggregate
764 SDValue InChain = Node->getOperand(0);
765 SDValue VAListPtr = Node->getOperand(1);
766 EVT PtrVT = VAListPtr.getValueType();
767 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
769 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
770 VAListPtr, MachinePointerInfo(SV),
771 false, false, false, 0);
772 // Increment the pointer, VAList, to the next vararg
773 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
774 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
775 // Store the incremented VAList to the legalized pointer
776 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
777 MachinePointerInfo(SV), false, false, 0);
778 // Load the actual argument out of the pointer VAList
779 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
780 false, false, false, 0);
783 SDValue XCoreTargetLowering::
784 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
787 // vastart stores the address of the VarArgsFrameIndex slot into the
788 // memory location argument
789 MachineFunction &MF = DAG.getMachineFunction();
790 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
791 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
792 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
793 MachinePointerInfo(), false, false, 0);
796 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
797 SelectionDAG &DAG) const {
798 // This nodes represent llvm.frameaddress on the DAG.
799 // It takes one operand, the index of the frame address to return.
800 // An index of zero corresponds to the current function's frame address.
801 // An index of one to the parent's frame address, and so on.
802 // Depths > 0 not supported yet!
803 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
806 MachineFunction &MF = DAG.getMachineFunction();
807 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
808 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
809 RegInfo->getFrameRegister(MF), MVT::i32);
812 SDValue XCoreTargetLowering::
813 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
814 // This nodes represent llvm.returnaddress on the DAG.
815 // It takes one operand, the index of the return address to return.
816 // An index of zero corresponds to the current function's return address.
817 // An index of one to the parent's return address, and so on.
818 // Depths > 0 not supported yet!
819 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
822 MachineFunction &MF = DAG.getMachineFunction();
823 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
824 int FI = XFI->createLRSpillSlot(MF);
825 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
826 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
827 MachinePointerInfo::getFixedStack(FI), false, false,
831 SDValue XCoreTargetLowering::
832 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
833 // This node represents offset from frame pointer to first on-stack argument.
834 // This is needed for correct stack adjustment during unwind.
835 // However, we don't know the offset until after the frame has be finalised.
836 // This is done during the XCoreFTAOElim pass.
837 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
840 SDValue XCoreTargetLowering::
841 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
842 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
843 // This node represents 'eh_return' gcc dwarf builtin, which is used to
844 // return from exception. The general meaning is: adjust stack by OFFSET and
845 // pass execution to HANDLER.
846 MachineFunction &MF = DAG.getMachineFunction();
847 SDValue Chain = Op.getOperand(0);
848 SDValue Offset = Op.getOperand(1);
849 SDValue Handler = Op.getOperand(2);
852 // Absolute SP = (FP + FrameToArgs) + Offset
853 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
854 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
855 RegInfo->getFrameRegister(MF), MVT::i32);
856 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
858 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
859 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
861 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
862 // which leaves 2 caller saved registers, R2 & R3 for us to use.
863 unsigned StackReg = XCore::R2;
864 unsigned HandlerReg = XCore::R3;
866 SDValue OutChains[] = {
867 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
868 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
873 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
874 DAG.getRegister(StackReg, MVT::i32),
875 DAG.getRegister(HandlerReg, MVT::i32));
879 SDValue XCoreTargetLowering::
880 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
881 return Op.getOperand(0);
884 SDValue XCoreTargetLowering::
885 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
886 SDValue Chain = Op.getOperand(0);
887 SDValue Trmp = Op.getOperand(1); // trampoline
888 SDValue FPtr = Op.getOperand(2); // nested function
889 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
891 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
894 // LDAPF_u10 r11, nest
895 // LDW_2rus r11, r11[0]
896 // STWSP_ru6 r11, sp[0]
897 // LDAPF_u10 r11, fptr
898 // LDW_2rus r11, r11[0]
904 SDValue OutChains[5];
909 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
910 Addr, MachinePointerInfo(TrmpAddr), false, false,
913 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
914 DAG.getConstant(4, MVT::i32));
915 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
916 Addr, MachinePointerInfo(TrmpAddr, 4), false,
919 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
920 DAG.getConstant(8, MVT::i32));
921 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
922 Addr, MachinePointerInfo(TrmpAddr, 8), false,
925 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
926 DAG.getConstant(12, MVT::i32));
927 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
928 MachinePointerInfo(TrmpAddr, 12), false, false,
931 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
932 DAG.getConstant(16, MVT::i32));
933 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
934 MachinePointerInfo(TrmpAddr, 16), false, false,
937 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
940 SDValue XCoreTargetLowering::
941 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
943 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
945 case Intrinsic::xcore_crc8:
946 EVT VT = Op.getValueType();
948 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
949 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
950 SDValue Crc(Data.getNode(), 1);
951 SDValue Results[] = { Crc, Data };
952 return DAG.getMergeValues(Results, DL);
957 SDValue XCoreTargetLowering::
958 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
960 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
963 SDValue XCoreTargetLowering::
964 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
965 AtomicSDNode *N = cast<AtomicSDNode>(Op);
966 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
967 assert(N->getOrdering() <= Monotonic &&
968 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
969 if (N->getMemoryVT() == MVT::i32) {
970 if (N->getAlignment() < 4)
971 report_fatal_error("atomic load must be aligned");
972 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
973 N->getBasePtr(), N->getPointerInfo(),
974 N->isVolatile(), N->isNonTemporal(),
975 N->isInvariant(), N->getAlignment(),
976 N->getTBAAInfo(), N->getRanges());
978 if (N->getMemoryVT() == MVT::i16) {
979 if (N->getAlignment() < 2)
980 report_fatal_error("atomic load must be aligned");
981 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
982 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
983 N->isVolatile(), N->isNonTemporal(),
984 N->getAlignment(), N->getTBAAInfo());
986 if (N->getMemoryVT() == MVT::i8)
987 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
988 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
989 N->isVolatile(), N->isNonTemporal(),
990 N->getAlignment(), N->getTBAAInfo());
994 SDValue XCoreTargetLowering::
995 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
996 AtomicSDNode *N = cast<AtomicSDNode>(Op);
997 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
998 assert(N->getOrdering() <= Monotonic &&
999 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1000 if (N->getMemoryVT() == MVT::i32) {
1001 if (N->getAlignment() < 4)
1002 report_fatal_error("atomic store must be aligned");
1003 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1004 N->getBasePtr(), N->getPointerInfo(),
1005 N->isVolatile(), N->isNonTemporal(),
1006 N->getAlignment(), N->getTBAAInfo());
1008 if (N->getMemoryVT() == MVT::i16) {
1009 if (N->getAlignment() < 2)
1010 report_fatal_error("atomic store must be aligned");
1011 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1012 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1013 N->isVolatile(), N->isNonTemporal(),
1014 N->getAlignment(), N->getTBAAInfo());
1016 if (N->getMemoryVT() == MVT::i8)
1017 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1018 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1019 N->isVolatile(), N->isNonTemporal(),
1020 N->getAlignment(), N->getTBAAInfo());
1024 //===----------------------------------------------------------------------===//
1025 // Calling Convention Implementation
1026 //===----------------------------------------------------------------------===//
1028 #include "XCoreGenCallingConv.inc"
1030 //===----------------------------------------------------------------------===//
1031 // Call Calling Convention Implementation
1032 //===----------------------------------------------------------------------===//
1034 /// XCore call implementation
1036 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1037 SmallVectorImpl<SDValue> &InVals) const {
1038 SelectionDAG &DAG = CLI.DAG;
1040 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1041 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1042 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1043 SDValue Chain = CLI.Chain;
1044 SDValue Callee = CLI.Callee;
1045 bool &isTailCall = CLI.IsTailCall;
1046 CallingConv::ID CallConv = CLI.CallConv;
1047 bool isVarArg = CLI.IsVarArg;
1049 // XCore target does not yet support tail call optimization.
1052 // For now, only CallingConv::C implemented
1056 llvm_unreachable("Unsupported calling convention");
1057 case CallingConv::Fast:
1058 case CallingConv::C:
1059 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1060 Outs, OutVals, Ins, dl, DAG, InVals);
1064 /// LowerCallResult - Lower the result values of a call into the
1065 /// appropriate copies out of appropriate physical registers / memory locations.
1067 LowerCallResult(SDValue Chain, SDValue InFlag,
1068 const SmallVectorImpl<CCValAssign> &RVLocs,
1069 SDLoc dl, SelectionDAG &DAG,
1070 SmallVectorImpl<SDValue> &InVals) {
1071 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1072 // Copy results out of physical registers.
1073 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1074 const CCValAssign &VA = RVLocs[i];
1075 if (VA.isRegLoc()) {
1076 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1077 InFlag).getValue(1);
1078 InFlag = Chain.getValue(2);
1079 InVals.push_back(Chain.getValue(0));
1081 assert(VA.isMemLoc());
1082 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1084 // Reserve space for this result.
1085 InVals.push_back(SDValue());
1089 // Copy results out of memory.
1090 SmallVector<SDValue, 4> MemOpChains;
1091 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1092 int offset = ResultMemLocs[i].first;
1093 unsigned index = ResultMemLocs[i].second;
1094 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1095 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, MVT::i32) };
1096 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1097 InVals[index] = load;
1098 MemOpChains.push_back(load.getValue(1));
1101 // Transform all loads nodes into one single node because
1102 // all load nodes are independent of each other.
1103 if (!MemOpChains.empty())
1104 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1109 /// LowerCCCCallTo - functions arguments are copied from virtual
1110 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1111 /// CALLSEQ_END are emitted.
1112 /// TODO: isTailCall, sret.
1114 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1115 CallingConv::ID CallConv, bool isVarArg,
1117 const SmallVectorImpl<ISD::OutputArg> &Outs,
1118 const SmallVectorImpl<SDValue> &OutVals,
1119 const SmallVectorImpl<ISD::InputArg> &Ins,
1120 SDLoc dl, SelectionDAG &DAG,
1121 SmallVectorImpl<SDValue> &InVals) const {
1123 // Analyze operands of the call, assigning locations to each operand.
1124 SmallVector<CCValAssign, 16> ArgLocs;
1125 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1126 getTargetMachine(), ArgLocs, *DAG.getContext());
1128 // The ABI dictates there should be one stack slot available to the callee
1129 // on function entry (for saving lr).
1130 CCInfo.AllocateStack(4, 4);
1132 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1134 SmallVector<CCValAssign, 16> RVLocs;
1135 // Analyze return values to determine the number of bytes of stack required.
1136 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1137 getTargetMachine(), RVLocs, *DAG.getContext());
1138 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1139 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1141 // Get a count of how many bytes are to be pushed on the stack.
1142 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1144 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1145 getPointerTy(), true), dl);
1147 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1148 SmallVector<SDValue, 12> MemOpChains;
1150 // Walk the register/memloc assignments, inserting copies/loads.
1151 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1152 CCValAssign &VA = ArgLocs[i];
1153 SDValue Arg = OutVals[i];
1155 // Promote the value if needed.
1156 switch (VA.getLocInfo()) {
1157 default: llvm_unreachable("Unknown loc info!");
1158 case CCValAssign::Full: break;
1159 case CCValAssign::SExt:
1160 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1162 case CCValAssign::ZExt:
1163 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1165 case CCValAssign::AExt:
1166 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1170 // Arguments that can be passed on register must be kept at
1171 // RegsToPass vector
1172 if (VA.isRegLoc()) {
1173 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1175 assert(VA.isMemLoc());
1177 int Offset = VA.getLocMemOffset();
1179 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1181 DAG.getConstant(Offset/4, MVT::i32)));
1185 // Transform all store nodes into one single node because
1186 // all store nodes are independent of each other.
1187 if (!MemOpChains.empty())
1188 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1190 // Build a sequence of copy-to-reg nodes chained together with token
1191 // chain and flag operands which copy the outgoing args into registers.
1192 // The InFlag in necessary since all emitted instructions must be
1195 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1196 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1197 RegsToPass[i].second, InFlag);
1198 InFlag = Chain.getValue(1);
1201 // If the callee is a GlobalAddress node (quite common, every direct call is)
1202 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1203 // Likewise ExternalSymbol -> TargetExternalSymbol.
1204 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1205 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1206 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1207 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1209 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1210 // = Chain, Callee, Reg#1, Reg#2, ...
1212 // Returns a chain & a flag for retval copy to use.
1213 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1214 SmallVector<SDValue, 8> Ops;
1215 Ops.push_back(Chain);
1216 Ops.push_back(Callee);
1218 // Add argument registers to the end of the list so that they are
1219 // known live into the call.
1220 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1221 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1222 RegsToPass[i].second.getValueType()));
1224 if (InFlag.getNode())
1225 Ops.push_back(InFlag);
1227 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1228 InFlag = Chain.getValue(1);
1230 // Create the CALLSEQ_END node.
1231 Chain = DAG.getCALLSEQ_END(Chain,
1232 DAG.getConstant(NumBytes, getPointerTy(), true),
1233 DAG.getConstant(0, getPointerTy(), true),
1235 InFlag = Chain.getValue(1);
1237 // Handle result values, copying them out of physregs into vregs that we
1239 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1242 //===----------------------------------------------------------------------===//
1243 // Formal Arguments Calling Convention Implementation
1244 //===----------------------------------------------------------------------===//
1247 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1250 /// XCore formal arguments implementation
1252 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1253 CallingConv::ID CallConv,
1255 const SmallVectorImpl<ISD::InputArg> &Ins,
1258 SmallVectorImpl<SDValue> &InVals)
1263 llvm_unreachable("Unsupported calling convention");
1264 case CallingConv::C:
1265 case CallingConv::Fast:
1266 return LowerCCCArguments(Chain, CallConv, isVarArg,
1267 Ins, dl, DAG, InVals);
1271 /// LowerCCCArguments - transform physical registers into
1272 /// virtual registers and generate load operations for
1273 /// arguments places on the stack.
1276 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1277 CallingConv::ID CallConv,
1279 const SmallVectorImpl<ISD::InputArg>
1283 SmallVectorImpl<SDValue> &InVals) const {
1284 MachineFunction &MF = DAG.getMachineFunction();
1285 MachineFrameInfo *MFI = MF.getFrameInfo();
1286 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1287 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1289 // Assign locations to all of the incoming arguments.
1290 SmallVector<CCValAssign, 16> ArgLocs;
1291 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1292 getTargetMachine(), ArgLocs, *DAG.getContext());
1294 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1296 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1298 unsigned LRSaveSize = StackSlotSize;
1301 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1303 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1304 // scheduler clobbering a register before it has been copied.
1306 // 1. CopyFromReg (and load) arg & vararg registers.
1307 // 2. Chain CopyFromReg nodes into a TokenFactor.
1308 // 3. Memcpy 'byVal' args & push final InVals.
1309 // 4. Chain mem ops nodes into a TokenFactor.
1310 SmallVector<SDValue, 4> CFRegNode;
1311 SmallVector<ArgDataPair, 4> ArgData;
1312 SmallVector<SDValue, 4> MemOps;
1314 // 1a. CopyFromReg (and load) arg registers.
1315 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1317 CCValAssign &VA = ArgLocs[i];
1320 if (VA.isRegLoc()) {
1321 // Arguments passed in registers
1322 EVT RegVT = VA.getLocVT();
1323 switch (RegVT.getSimpleVT().SimpleTy) {
1327 errs() << "LowerFormalArguments Unhandled argument type: "
1328 << RegVT.getSimpleVT().SimpleTy << "\n";
1330 llvm_unreachable(nullptr);
1333 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1334 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1335 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1336 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1340 assert(VA.isMemLoc());
1341 // Load the argument to a virtual register
1342 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1343 if (ObjSize > StackSlotSize) {
1344 errs() << "LowerFormalArguments Unhandled argument type: "
1345 << EVT(VA.getLocVT()).getEVTString()
1348 // Create the frame index object for this incoming parameter...
1349 int FI = MFI->CreateFixedObject(ObjSize,
1350 LRSaveSize + VA.getLocMemOffset(),
1353 // Create the SelectionDAG nodes corresponding to a load
1354 //from this parameter
1355 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1356 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1357 MachinePointerInfo::getFixedStack(FI),
1358 false, false, false, 0);
1360 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1361 ArgData.push_back(ADP);
1364 // 1b. CopyFromReg vararg registers.
1366 // Argument registers
1367 static const MCPhysReg ArgRegs[] = {
1368 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1370 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1371 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1372 array_lengthof(ArgRegs));
1373 if (FirstVAReg < array_lengthof(ArgRegs)) {
1375 // Save remaining registers, storing higher register numbers at a higher
1377 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1378 // Create a stack slot
1379 int FI = MFI->CreateFixedObject(4, offset, true);
1380 if (i == (int)FirstVAReg) {
1381 XFI->setVarArgsFrameIndex(FI);
1383 offset -= StackSlotSize;
1384 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1385 // Move argument from phys reg -> virt reg
1386 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1387 RegInfo.addLiveIn(ArgRegs[i], VReg);
1388 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1389 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1390 // Move argument from virt reg -> stack
1391 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1392 MachinePointerInfo(), false, false, 0);
1393 MemOps.push_back(Store);
1396 // This will point to the next argument passed via stack.
1397 XFI->setVarArgsFrameIndex(
1398 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1403 // 2. chain CopyFromReg nodes into a TokenFactor.
1404 if (!CFRegNode.empty())
1405 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1407 // 3. Memcpy 'byVal' args & push final InVals.
1408 // Aggregates passed "byVal" need to be copied by the callee.
1409 // The callee will use a pointer to this copy, rather than the original
1411 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1412 ArgDE = ArgData.end();
1413 ArgDI != ArgDE; ++ArgDI) {
1414 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1415 unsigned Size = ArgDI->Flags.getByValSize();
1416 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1417 // Create a new object on the stack and copy the pointee into it.
1418 int FI = MFI->CreateStackObject(Size, Align, false);
1419 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1420 InVals.push_back(FIN);
1421 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1422 DAG.getConstant(Size, MVT::i32),
1423 Align, false, false,
1424 MachinePointerInfo(),
1425 MachinePointerInfo()));
1427 InVals.push_back(ArgDI->SDV);
1431 // 4, chain mem ops nodes into a TokenFactor.
1432 if (!MemOps.empty()) {
1433 MemOps.push_back(Chain);
1434 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1440 //===----------------------------------------------------------------------===//
1441 // Return Value Calling Convention Implementation
1442 //===----------------------------------------------------------------------===//
1444 bool XCoreTargetLowering::
1445 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1447 const SmallVectorImpl<ISD::OutputArg> &Outs,
1448 LLVMContext &Context) const {
1449 SmallVector<CCValAssign, 16> RVLocs;
1450 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1451 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1453 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1459 XCoreTargetLowering::LowerReturn(SDValue Chain,
1460 CallingConv::ID CallConv, bool isVarArg,
1461 const SmallVectorImpl<ISD::OutputArg> &Outs,
1462 const SmallVectorImpl<SDValue> &OutVals,
1463 SDLoc dl, SelectionDAG &DAG) const {
1465 XCoreFunctionInfo *XFI =
1466 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1467 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1469 // CCValAssign - represent the assignment of
1470 // the return value to a location
1471 SmallVector<CCValAssign, 16> RVLocs;
1473 // CCState - Info about the registers and stack slot.
1474 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1475 getTargetMachine(), RVLocs, *DAG.getContext());
1477 // Analyze return values.
1479 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1481 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1484 SmallVector<SDValue, 4> RetOps(1, Chain);
1486 // Return on XCore is always a "retsp 0"
1487 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1489 SmallVector<SDValue, 4> MemOpChains;
1490 // Handle return values that must be copied to memory.
1491 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1492 CCValAssign &VA = RVLocs[i];
1495 assert(VA.isMemLoc());
1497 report_fatal_error("Can't return value from vararg function in memory");
1500 int Offset = VA.getLocMemOffset();
1501 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1502 // Create the frame index object for the memory location.
1503 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1505 // Create a SelectionDAG node corresponding to a store
1506 // to this memory location.
1507 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1508 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1509 MachinePointerInfo::getFixedStack(FI), false, false,
1513 // Transform all store nodes into one single node because
1514 // all stores are independent of each other.
1515 if (!MemOpChains.empty())
1516 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1518 // Now handle return values copied to registers.
1519 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1520 CCValAssign &VA = RVLocs[i];
1523 // Copy the result values into the output registers.
1524 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1526 // guarantee that all emitted copies are
1527 // stuck together, avoiding something bad
1528 Flag = Chain.getValue(1);
1529 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1532 RetOps[0] = Chain; // Update chain.
1534 // Add the flag if we have it.
1536 RetOps.push_back(Flag);
1538 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1541 //===----------------------------------------------------------------------===//
1542 // Other Lowering Code
1543 //===----------------------------------------------------------------------===//
1546 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1547 MachineBasicBlock *BB) const {
1548 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1549 DebugLoc dl = MI->getDebugLoc();
1550 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1551 "Unexpected instr type to insert");
1553 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1554 // control-flow pattern. The incoming instruction knows the destination vreg
1555 // to set, the condition code register to branch on, the true/false values to
1556 // select between, and a branch opcode to use.
1557 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1558 MachineFunction::iterator It = BB;
1564 // cmpTY ccX, r1, r2
1566 // fallthrough --> copy0MBB
1567 MachineBasicBlock *thisMBB = BB;
1568 MachineFunction *F = BB->getParent();
1569 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1570 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1571 F->insert(It, copy0MBB);
1572 F->insert(It, sinkMBB);
1574 // Transfer the remainder of BB and its successor edges to sinkMBB.
1575 sinkMBB->splice(sinkMBB->begin(), BB,
1576 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1577 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1579 // Next, add the true and fallthrough blocks as its successors.
1580 BB->addSuccessor(copy0MBB);
1581 BB->addSuccessor(sinkMBB);
1583 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1584 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1587 // %FalseValue = ...
1588 // # fallthrough to sinkMBB
1591 // Update machine-CFG edges
1592 BB->addSuccessor(sinkMBB);
1595 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1598 BuildMI(*BB, BB->begin(), dl,
1599 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1600 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1601 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1603 MI->eraseFromParent(); // The pseudo instruction is gone now.
1607 //===----------------------------------------------------------------------===//
1608 // Target Optimization Hooks
1609 //===----------------------------------------------------------------------===//
1611 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1612 DAGCombinerInfo &DCI) const {
1613 SelectionDAG &DAG = DCI.DAG;
1615 switch (N->getOpcode()) {
1617 case ISD::INTRINSIC_VOID:
1618 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1619 case Intrinsic::xcore_outt:
1620 case Intrinsic::xcore_outct:
1621 case Intrinsic::xcore_chkct: {
1622 SDValue OutVal = N->getOperand(3);
1623 // These instructions ignore the high bits.
1624 if (OutVal.hasOneUse()) {
1625 unsigned BitWidth = OutVal.getValueSizeInBits();
1626 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1627 APInt KnownZero, KnownOne;
1628 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1629 !DCI.isBeforeLegalizeOps());
1630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1631 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1632 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1634 DCI.CommitTargetLoweringOpt(TLO);
1638 case Intrinsic::xcore_setpt: {
1639 SDValue Time = N->getOperand(3);
1640 // This instruction ignores the high bits.
1641 if (Time.hasOneUse()) {
1642 unsigned BitWidth = Time.getValueSizeInBits();
1643 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1644 APInt KnownZero, KnownOne;
1645 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1646 !DCI.isBeforeLegalizeOps());
1647 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1648 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1649 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1651 DCI.CommitTargetLoweringOpt(TLO);
1657 case XCoreISD::LADD: {
1658 SDValue N0 = N->getOperand(0);
1659 SDValue N1 = N->getOperand(1);
1660 SDValue N2 = N->getOperand(2);
1661 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1662 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1663 EVT VT = N0.getValueType();
1665 // canonicalize constant to RHS
1667 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1669 // fold (ladd 0, 0, x) -> 0, x & 1
1670 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1671 SDValue Carry = DAG.getConstant(0, VT);
1672 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1673 DAG.getConstant(1, VT));
1674 SDValue Ops[] = { Result, Carry };
1675 return DAG.getMergeValues(Ops, dl);
1678 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1680 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1681 APInt KnownZero, KnownOne;
1682 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1683 VT.getSizeInBits() - 1);
1684 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1685 if ((KnownZero & Mask) == Mask) {
1686 SDValue Carry = DAG.getConstant(0, VT);
1687 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1688 SDValue Ops[] = { Result, Carry };
1689 return DAG.getMergeValues(Ops, dl);
1694 case XCoreISD::LSUB: {
1695 SDValue N0 = N->getOperand(0);
1696 SDValue N1 = N->getOperand(1);
1697 SDValue N2 = N->getOperand(2);
1698 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1699 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1700 EVT VT = N0.getValueType();
1702 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1703 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1704 APInt KnownZero, KnownOne;
1705 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1706 VT.getSizeInBits() - 1);
1707 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1708 if ((KnownZero & Mask) == Mask) {
1709 SDValue Borrow = N2;
1710 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1711 DAG.getConstant(0, VT), N2);
1712 SDValue Ops[] = { Result, Borrow };
1713 return DAG.getMergeValues(Ops, dl);
1717 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1719 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1720 APInt KnownZero, KnownOne;
1721 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1722 VT.getSizeInBits() - 1);
1723 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1724 if ((KnownZero & Mask) == Mask) {
1725 SDValue Borrow = DAG.getConstant(0, VT);
1726 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1727 SDValue Ops[] = { Result, Borrow };
1728 return DAG.getMergeValues(Ops, dl);
1733 case XCoreISD::LMUL: {
1734 SDValue N0 = N->getOperand(0);
1735 SDValue N1 = N->getOperand(1);
1736 SDValue N2 = N->getOperand(2);
1737 SDValue N3 = N->getOperand(3);
1738 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1739 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1740 EVT VT = N0.getValueType();
1741 // Canonicalize multiplicative constant to RHS. If both multiplicative
1742 // operands are constant canonicalize smallest to RHS.
1743 if ((N0C && !N1C) ||
1744 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1745 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1749 if (N1C && N1C->isNullValue()) {
1750 // If the high result is unused fold to add(a, b)
1751 if (N->hasNUsesOfValue(0, 0)) {
1752 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1753 SDValue Ops[] = { Lo, Lo };
1754 return DAG.getMergeValues(Ops, dl);
1756 // Otherwise fold to ladd(a, b, 0)
1758 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1759 SDValue Carry(Result.getNode(), 1);
1760 SDValue Ops[] = { Carry, Result };
1761 return DAG.getMergeValues(Ops, dl);
1766 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1767 // lmul(x, y, a, b). The high result of lmul will be ignored.
1768 // This is only profitable if the intermediate results are unused
1770 SDValue Mul0, Mul1, Addend0, Addend1;
1771 if (N->getValueType(0) == MVT::i32 &&
1772 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1773 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1774 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1775 Mul1, Addend0, Addend1);
1776 SDValue Result(Ignored.getNode(), 1);
1779 APInt HighMask = APInt::getHighBitsSet(64, 32);
1780 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1781 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1782 // before type legalization as it is messy to match the operands after
1784 if (N->getValueType(0) == MVT::i64 &&
1785 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1786 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1787 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1788 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1789 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1790 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1791 Mul0, DAG.getConstant(0, MVT::i32));
1792 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1793 Mul1, DAG.getConstant(0, MVT::i32));
1794 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1795 Addend0, DAG.getConstant(0, MVT::i32));
1796 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1797 Addend1, DAG.getConstant(0, MVT::i32));
1798 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1799 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1800 Addend0L, Addend1L);
1801 SDValue Lo(Hi.getNode(), 1);
1802 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1807 // Replace unaligned store of unaligned load with memmove.
1808 StoreSDNode *ST = cast<StoreSDNode>(N);
1809 if (!DCI.isBeforeLegalize() ||
1810 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1811 ST->isVolatile() || ST->isIndexed()) {
1814 SDValue Chain = ST->getChain();
1816 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1817 if (StoreBits % 8) {
1820 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1821 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1822 unsigned Alignment = ST->getAlignment();
1823 if (Alignment >= ABIAlignment) {
1827 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1828 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1829 LD->getAlignment() == Alignment &&
1830 !LD->isVolatile() && !LD->isIndexed() &&
1831 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1832 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1834 DAG.getConstant(StoreBits/8, MVT::i32),
1835 Alignment, false, ST->getPointerInfo(),
1836 LD->getPointerInfo());
1845 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1848 const SelectionDAG &DAG,
1849 unsigned Depth) const {
1850 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1851 switch (Op.getOpcode()) {
1853 case XCoreISD::LADD:
1854 case XCoreISD::LSUB:
1855 if (Op.getResNo() == 1) {
1856 // Top bits of carry / borrow are clear.
1857 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1858 KnownZero.getBitWidth() - 1);
1861 case ISD::INTRINSIC_W_CHAIN:
1863 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1865 case Intrinsic::xcore_getts:
1866 // High bits are known to be zero.
1867 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1868 KnownZero.getBitWidth() - 16);
1870 case Intrinsic::xcore_int:
1871 case Intrinsic::xcore_inct:
1872 // High bits are known to be zero.
1873 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1874 KnownZero.getBitWidth() - 8);
1876 case Intrinsic::xcore_testct:
1877 // Result is either 0 or 1.
1878 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1879 KnownZero.getBitWidth() - 1);
1881 case Intrinsic::xcore_testwct:
1882 // Result is in the range 0 - 4.
1883 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1884 KnownZero.getBitWidth() - 3);
1892 //===----------------------------------------------------------------------===//
1893 // Addressing mode description hooks
1894 //===----------------------------------------------------------------------===//
1896 static inline bool isImmUs(int64_t val)
1898 return (val >= 0 && val <= 11);
1901 static inline bool isImmUs2(int64_t val)
1903 return (val%2 == 0 && isImmUs(val/2));
1906 static inline bool isImmUs4(int64_t val)
1908 return (val%4 == 0 && isImmUs(val/4));
1911 /// isLegalAddressingMode - Return true if the addressing mode represented
1912 /// by AM is legal for this target, for a load/store of the specified type.
1914 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1916 if (Ty->getTypeID() == Type::VoidTyID)
1917 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1919 const DataLayout *TD = TM.getDataLayout();
1920 unsigned Size = TD->getTypeAllocSize(Ty);
1922 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1929 if (AM.Scale == 0) {
1930 return isImmUs(AM.BaseOffs);
1933 return AM.Scale == 1 && AM.BaseOffs == 0;
1937 if (AM.Scale == 0) {
1938 return isImmUs2(AM.BaseOffs);
1941 return AM.Scale == 2 && AM.BaseOffs == 0;
1944 if (AM.Scale == 0) {
1945 return isImmUs4(AM.BaseOffs);
1948 return AM.Scale == 4 && AM.BaseOffs == 0;
1952 //===----------------------------------------------------------------------===//
1953 // XCore Inline Assembly Support
1954 //===----------------------------------------------------------------------===//
1956 std::pair<unsigned, const TargetRegisterClass*>
1957 XCoreTargetLowering::
1958 getRegForInlineAsmConstraint(const std::string &Constraint,
1960 if (Constraint.size() == 1) {
1961 switch (Constraint[0]) {
1964 return std::make_pair(0U, &XCore::GRRegsRegClass);
1967 // Use the default implementation in TargetLowering to convert the register
1968 // constraint into a member of a register class.
1969 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);