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
47 switch ((XCoreISD::NodeType)Opcode)
49 case XCoreISD::FIRST_NUMBER : break;
50 case XCoreISD::BL : return "XCoreISD::BL";
51 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
52 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
53 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
54 case XCoreISD::LDWSP : return "XCoreISD::LDWSP";
55 case XCoreISD::STWSP : return "XCoreISD::STWSP";
56 case XCoreISD::RETSP : return "XCoreISD::RETSP";
57 case XCoreISD::LADD : return "XCoreISD::LADD";
58 case XCoreISD::LSUB : return "XCoreISD::LSUB";
59 case XCoreISD::LMUL : return "XCoreISD::LMUL";
60 case XCoreISD::MACCU : return "XCoreISD::MACCU";
61 case XCoreISD::MACCS : return "XCoreISD::MACCS";
62 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
63 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
64 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
65 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
66 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
67 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
72 XCoreTargetLowering::XCoreTargetLowering(const TargetMachine &TM,
73 const XCoreSubtarget &Subtarget)
74 : TargetLowering(TM), TM(TM), Subtarget(Subtarget) {
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
79 // Compute derived properties from the register classes
80 computeRegisterProperties(Subtarget.getRegisterInfo());
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);
102 setOperationAction(ISD::ADD, MVT::i64, Custom);
103 setOperationAction(ISD::SUB, MVT::i64, Custom);
104 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
105 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
106 setOperationAction(ISD::MULHS, MVT::i32, Expand);
107 setOperationAction(ISD::MULHU, MVT::i32, Expand);
108 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
113 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
114 setOperationAction(ISD::ROTL , MVT::i32, Expand);
115 setOperationAction(ISD::ROTR , MVT::i32, Expand);
116 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
117 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::TRAP, MVT::Other, Legal);
122 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
124 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
125 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
127 // Conversion of i64 -> double produces constantpool nodes
128 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
131 for (MVT VT : MVT::integer_valuetypes()) {
132 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
133 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
137 setLoadExtAction(ISD::ZEXTLOAD, VT, 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);
183 setTargetDAGCombine(ISD::INTRINSIC_VOID);
184 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
186 setMinFunctionAlignment(1);
187 setPrefFunctionAlignment(2);
190 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
191 if (Val.getOpcode() != ISD::LOAD)
194 EVT VT1 = Val.getValueType();
195 if (!VT1.isSimple() || !VT1.isInteger() ||
196 !VT2.isSimple() || !VT2.isInteger())
199 switch (VT1.getSimpleVT().SimpleTy) {
208 SDValue XCoreTargetLowering::
209 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
210 switch (Op.getOpcode())
212 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
213 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
214 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
215 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
216 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
217 case ISD::LOAD: return LowerLOAD(Op, DAG);
218 case ISD::STORE: return LowerSTORE(Op, DAG);
219 case ISD::VAARG: return LowerVAARG(Op, DAG);
220 case ISD::VASTART: return LowerVASTART(Op, DAG);
221 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
222 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
223 // FIXME: Remove these when LegalizeDAGTypes lands.
225 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
226 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
227 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
228 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
229 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
230 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
231 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
232 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
233 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
234 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
236 llvm_unreachable("unimplemented operand");
240 /// ReplaceNodeResults - Replace the results of node with an illegal result
241 /// type with new values built out of custom code.
242 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
243 SmallVectorImpl<SDValue>&Results,
244 SelectionDAG &DAG) const {
245 switch (N->getOpcode()) {
247 llvm_unreachable("Don't know how to custom expand this!");
250 Results.push_back(ExpandADDSUB(N, DAG));
255 //===----------------------------------------------------------------------===//
256 // Misc Lower Operation implementation
257 //===----------------------------------------------------------------------===//
259 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
260 const GlobalValue *GV,
261 SelectionDAG &DAG) const {
262 // FIXME there is no actual debug info here
265 if (GV->getType()->getElementType()->isFunctionTy())
266 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
268 const auto *GVar = dyn_cast<GlobalVariable>(GV);
269 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
270 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
271 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
273 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
276 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
277 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
280 Type *ObjType = GV->getType()->getPointerElementType();
281 if (!ObjType->isSized())
284 auto &DL = GV->getParent()->getDataLayout();
285 unsigned ObjSize = DL.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, DL, 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(
314 Type::getInt8Ty(*DAG.getContext()), GA, Idx);
315 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
316 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL,
317 DAG.getEntryNode(), CP, MachinePointerInfo(), false,
322 SDValue XCoreTargetLowering::
323 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
326 auto PtrVT = getPointerTy(DAG.getDataLayout());
327 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
328 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
330 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, PtrVT, Result);
333 SDValue XCoreTargetLowering::
334 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
336 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
337 // FIXME there isn't really debug info here
339 EVT PtrVT = Op.getValueType();
341 if (CP->isMachineConstantPoolEntry()) {
342 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
343 CP->getAlignment(), CP->getOffset());
345 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
346 CP->getAlignment(), CP->getOffset());
348 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
351 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
352 return MachineJumpTableInfo::EK_Inline;
355 SDValue XCoreTargetLowering::
356 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
358 SDValue Chain = Op.getOperand(0);
359 SDValue Table = Op.getOperand(1);
360 SDValue Index = Op.getOperand(2);
362 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
363 unsigned JTI = JT->getIndex();
364 MachineFunction &MF = DAG.getMachineFunction();
365 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
366 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
368 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
369 if (NumEntries <= 32) {
370 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
372 assert((NumEntries >> 31) == 0);
373 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
374 DAG.getConstant(1, dl, MVT::i32));
375 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
379 SDValue XCoreTargetLowering::
380 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
381 int64_t Offset, SelectionDAG &DAG) const
383 auto PtrVT = getPointerTy(DAG.getDataLayout());
384 if ((Offset & 0x3) == 0) {
385 return DAG.getLoad(PtrVT, DL, Chain, Base, MachinePointerInfo(), false,
388 // Lower to pair of consecutive word aligned loads plus some bit shifting.
389 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
390 int32_t LowOffset = HighOffset - 4;
391 SDValue LowAddr, HighAddr;
392 if (GlobalAddressSDNode *GASD =
393 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
394 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
396 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
399 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
400 DAG.getConstant(LowOffset, DL, MVT::i32));
401 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
402 DAG.getConstant(HighOffset, DL, MVT::i32));
404 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
405 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
407 SDValue Low = DAG.getLoad(PtrVT, DL, Chain, LowAddr, MachinePointerInfo(),
408 false, false, false, 0);
409 SDValue High = DAG.getLoad(PtrVT, DL, Chain, HighAddr, MachinePointerInfo(),
410 false, false, false, 0);
411 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
412 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
413 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
414 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
416 SDValue Ops[] = { Result, Chain };
417 return DAG.getMergeValues(Ops, DL);
420 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
422 APInt KnownZero, KnownOne;
423 DAG.computeKnownBits(Value, KnownZero, KnownOne);
424 return KnownZero.countTrailingOnes() >= 2;
427 SDValue XCoreTargetLowering::
428 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
430 LoadSDNode *LD = cast<LoadSDNode>(Op);
431 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
432 "Unexpected extension type");
433 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
434 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
435 LD->getAddressSpace(),
439 auto &TD = DAG.getDataLayout();
440 unsigned ABIAlignment = TD.getABITypeAlignment(
441 LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
442 // Leave aligned load alone.
443 if (LD->getAlignment() >= ABIAlignment)
446 SDValue Chain = LD->getChain();
447 SDValue BasePtr = LD->getBasePtr();
450 if (!LD->isVolatile()) {
451 const GlobalValue *GV;
453 if (DAG.isBaseWithConstantOffset(BasePtr) &&
454 isWordAligned(BasePtr->getOperand(0), DAG)) {
455 SDValue NewBasePtr = BasePtr->getOperand(0);
456 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
457 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
460 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
461 MinAlign(GV->getAlignment(), 4) == 4) {
462 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
463 BasePtr->getValueType(0));
464 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
469 if (LD->getAlignment() == 2) {
470 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
471 BasePtr, LD->getPointerInfo(), MVT::i16,
472 LD->isVolatile(), LD->isNonTemporal(),
473 LD->isInvariant(), 2);
474 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
475 DAG.getConstant(2, DL, MVT::i32));
476 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
478 LD->getPointerInfo().getWithOffset(2),
479 MVT::i16, LD->isVolatile(),
480 LD->isNonTemporal(), LD->isInvariant(), 2);
481 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
482 DAG.getConstant(16, DL, MVT::i32));
483 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
484 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
486 SDValue Ops[] = { Result, Chain };
487 return DAG.getMergeValues(Ops, DL);
490 // Lower to a call to __misaligned_load(BasePtr).
491 Type *IntPtrTy = TD.getIntPtrType(*DAG.getContext());
492 TargetLowering::ArgListTy Args;
493 TargetLowering::ArgListEntry Entry;
496 Entry.Node = BasePtr;
497 Args.push_back(Entry);
499 TargetLowering::CallLoweringInfo CLI(DAG);
500 CLI.setDebugLoc(DL).setChain(Chain).setCallee(
501 CallingConv::C, IntPtrTy,
502 DAG.getExternalSymbol("__misaligned_load",
503 getPointerTy(DAG.getDataLayout())),
506 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
507 SDValue Ops[] = { CallResult.first, CallResult.second };
508 return DAG.getMergeValues(Ops, DL);
511 SDValue XCoreTargetLowering::
512 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
514 StoreSDNode *ST = cast<StoreSDNode>(Op);
515 assert(!ST->isTruncatingStore() && "Unexpected store type");
516 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
517 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
518 ST->getAddressSpace(),
519 ST->getAlignment())) {
522 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
523 ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
524 // Leave aligned store alone.
525 if (ST->getAlignment() >= ABIAlignment) {
528 SDValue Chain = ST->getChain();
529 SDValue BasePtr = ST->getBasePtr();
530 SDValue Value = ST->getValue();
533 if (ST->getAlignment() == 2) {
535 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
536 DAG.getConstant(16, dl, MVT::i32));
537 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
538 ST->getPointerInfo(), MVT::i16,
539 ST->isVolatile(), ST->isNonTemporal(),
541 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
542 DAG.getConstant(2, dl, MVT::i32));
543 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
544 ST->getPointerInfo().getWithOffset(2),
545 MVT::i16, ST->isVolatile(),
546 ST->isNonTemporal(), 2);
547 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
550 // Lower to a call to __misaligned_store(BasePtr, Value).
551 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
552 TargetLowering::ArgListTy Args;
553 TargetLowering::ArgListEntry Entry;
556 Entry.Node = BasePtr;
557 Args.push_back(Entry);
560 Args.push_back(Entry);
562 TargetLowering::CallLoweringInfo CLI(DAG);
563 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
564 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
565 DAG.getExternalSymbol("__misaligned_store",
566 getPointerTy(DAG.getDataLayout())),
569 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
570 return CallResult.second;
573 SDValue XCoreTargetLowering::
574 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
576 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
577 "Unexpected operand to lower!");
579 SDValue LHS = Op.getOperand(0);
580 SDValue RHS = Op.getOperand(1);
581 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
582 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
583 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
585 SDValue Lo(Hi.getNode(), 1);
586 SDValue Ops[] = { Lo, Hi };
587 return DAG.getMergeValues(Ops, dl);
590 SDValue XCoreTargetLowering::
591 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
593 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
594 "Unexpected operand to lower!");
596 SDValue LHS = Op.getOperand(0);
597 SDValue RHS = Op.getOperand(1);
598 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
599 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
600 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
602 SDValue Lo(Hi.getNode(), 1);
603 SDValue Ops[] = { Lo, Hi };
604 return DAG.getMergeValues(Ops, dl);
607 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
608 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
609 /// each intermediate result in the calculation must also have a single use.
610 /// If the Op is in the correct form the constituent parts are written to Mul0,
611 /// Mul1, Addend0 and Addend1.
613 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
614 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
616 if (Op.getOpcode() != ISD::ADD)
618 SDValue N0 = Op.getOperand(0);
619 SDValue N1 = Op.getOperand(1);
622 if (N0.getOpcode() == ISD::ADD) {
625 } else if (N1.getOpcode() == ISD::ADD) {
631 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
633 if (OtherOp.getOpcode() == ISD::MUL) {
634 // add(add(a,b),mul(x,y))
635 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
637 Mul0 = OtherOp.getOperand(0);
638 Mul1 = OtherOp.getOperand(1);
639 Addend0 = AddOp.getOperand(0);
640 Addend1 = AddOp.getOperand(1);
643 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
644 // add(add(mul(x,y),a),b)
645 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
647 Mul0 = AddOp.getOperand(0).getOperand(0);
648 Mul1 = AddOp.getOperand(0).getOperand(1);
649 Addend0 = AddOp.getOperand(1);
653 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
654 // add(add(a,mul(x,y)),b)
655 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
657 Mul0 = AddOp.getOperand(1).getOperand(0);
658 Mul1 = AddOp.getOperand(1).getOperand(1);
659 Addend0 = AddOp.getOperand(0);
666 SDValue XCoreTargetLowering::
667 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
671 if (N->getOperand(0).getOpcode() == ISD::MUL) {
672 Mul = N->getOperand(0);
673 Other = N->getOperand(1);
674 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
675 Mul = N->getOperand(1);
676 Other = N->getOperand(0);
681 SDValue LL, RL, AddendL, AddendH;
682 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
683 Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
684 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685 Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
686 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
687 Other, DAG.getConstant(0, dl, MVT::i32));
688 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
689 Other, DAG.getConstant(1, dl, MVT::i32));
690 APInt HighMask = APInt::getHighBitsSet(64, 32);
691 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
692 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
693 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
694 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
695 // The inputs are both zero-extended.
696 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
697 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
699 SDValue Lo(Hi.getNode(), 1);
700 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
702 if (LHSSB > 32 && RHSSB > 32) {
703 // The inputs are both sign-extended.
704 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
705 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
707 SDValue Lo(Hi.getNode(), 1);
708 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
711 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
712 Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
713 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
714 Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
715 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
716 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
718 SDValue Lo(Hi.getNode(), 1);
719 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
720 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
721 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
722 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
723 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
726 SDValue XCoreTargetLowering::
727 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
729 assert(N->getValueType(0) == MVT::i64 &&
730 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
731 "Unknown operand to lower!");
733 if (N->getOpcode() == ISD::ADD) {
734 SDValue Result = TryExpandADDWithMul(N, DAG);
735 if (Result.getNode())
741 // Extract components
742 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
744 DAG.getConstant(0, dl, MVT::i32));
745 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
747 DAG.getConstant(1, dl, MVT::i32));
748 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
750 DAG.getConstant(0, dl, MVT::i32));
751 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
753 DAG.getConstant(1, dl, MVT::i32));
756 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
758 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
759 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
761 SDValue Carry(Lo.getNode(), 1);
763 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
765 SDValue Ignored(Hi.getNode(), 1);
767 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
770 SDValue XCoreTargetLowering::
771 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
773 // Whist llvm does not support aggregate varargs we can ignore
774 // the possibility of the ValueType being an implicit byVal vararg.
775 SDNode *Node = Op.getNode();
776 EVT VT = Node->getValueType(0); // not an aggregate
777 SDValue InChain = Node->getOperand(0);
778 SDValue VAListPtr = Node->getOperand(1);
779 EVT PtrVT = VAListPtr.getValueType();
780 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
782 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
783 VAListPtr, MachinePointerInfo(SV),
784 false, false, false, 0);
785 // Increment the pointer, VAList, to the next vararg
786 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
787 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
789 // Store the incremented VAList to the legalized pointer
790 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
791 MachinePointerInfo(SV), false, false, 0);
792 // Load the actual argument out of the pointer VAList
793 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
794 false, false, false, 0);
797 SDValue XCoreTargetLowering::
798 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
801 // vastart stores the address of the VarArgsFrameIndex slot into the
802 // memory location argument
803 MachineFunction &MF = DAG.getMachineFunction();
804 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
805 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
806 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
807 MachinePointerInfo(), false, false, 0);
810 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
811 SelectionDAG &DAG) const {
812 // This nodes represent llvm.frameaddress on the DAG.
813 // It takes one operand, the index of the frame address to return.
814 // An index of zero corresponds to the current function's frame address.
815 // An index of one to the parent's frame address, and so on.
816 // Depths > 0 not supported yet!
817 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
820 MachineFunction &MF = DAG.getMachineFunction();
821 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
822 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
823 RegInfo->getFrameRegister(MF), MVT::i32);
826 SDValue XCoreTargetLowering::
827 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
828 // This nodes represent llvm.returnaddress on the DAG.
829 // It takes one operand, the index of the return address to return.
830 // An index of zero corresponds to the current function's return address.
831 // An index of one to the parent's return address, and so on.
832 // Depths > 0 not supported yet!
833 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
836 MachineFunction &MF = DAG.getMachineFunction();
837 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
838 int FI = XFI->createLRSpillSlot(MF);
839 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
841 getPointerTy(DAG.getDataLayout()), SDLoc(Op), DAG.getEntryNode(), FIN,
842 MachinePointerInfo::getFixedStack(FI), false, false, false, 0);
845 SDValue XCoreTargetLowering::
846 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
847 // This node represents offset from frame pointer to first on-stack argument.
848 // This is needed for correct stack adjustment during unwind.
849 // However, we don't know the offset until after the frame has be finalised.
850 // This is done during the XCoreFTAOElim pass.
851 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
854 SDValue XCoreTargetLowering::
855 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
856 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
857 // This node represents 'eh_return' gcc dwarf builtin, which is used to
858 // return from exception. The general meaning is: adjust stack by OFFSET and
859 // pass execution to HANDLER.
860 MachineFunction &MF = DAG.getMachineFunction();
861 SDValue Chain = Op.getOperand(0);
862 SDValue Offset = Op.getOperand(1);
863 SDValue Handler = Op.getOperand(2);
866 // Absolute SP = (FP + FrameToArgs) + Offset
867 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
868 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
869 RegInfo->getFrameRegister(MF), MVT::i32);
870 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
872 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
873 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
875 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
876 // which leaves 2 caller saved registers, R2 & R3 for us to use.
877 unsigned StackReg = XCore::R2;
878 unsigned HandlerReg = XCore::R3;
880 SDValue OutChains[] = {
881 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
882 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
885 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
887 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
888 DAG.getRegister(StackReg, MVT::i32),
889 DAG.getRegister(HandlerReg, MVT::i32));
893 SDValue XCoreTargetLowering::
894 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
895 return Op.getOperand(0);
898 SDValue XCoreTargetLowering::
899 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
900 SDValue Chain = Op.getOperand(0);
901 SDValue Trmp = Op.getOperand(1); // trampoline
902 SDValue FPtr = Op.getOperand(2); // nested function
903 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
905 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
908 // LDAPF_u10 r11, nest
909 // LDW_2rus r11, r11[0]
910 // STWSP_ru6 r11, sp[0]
911 // LDAPF_u10 r11, fptr
912 // LDW_2rus r11, r11[0]
918 SDValue OutChains[5];
923 OutChains[0] = DAG.getStore(Chain, dl,
924 DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
925 MachinePointerInfo(TrmpAddr), false, false, 0);
927 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
928 DAG.getConstant(4, dl, MVT::i32));
929 OutChains[1] = DAG.getStore(Chain, dl,
930 DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
931 MachinePointerInfo(TrmpAddr, 4), false, false, 0);
933 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
934 DAG.getConstant(8, dl, MVT::i32));
935 OutChains[2] = DAG.getStore(Chain, dl,
936 DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
937 MachinePointerInfo(TrmpAddr, 8), false, false, 0);
939 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
940 DAG.getConstant(12, dl, MVT::i32));
941 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
942 MachinePointerInfo(TrmpAddr, 12), false, false,
945 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
946 DAG.getConstant(16, dl, MVT::i32));
947 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
948 MachinePointerInfo(TrmpAddr, 16), false, false,
951 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
954 SDValue XCoreTargetLowering::
955 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
957 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
959 case Intrinsic::xcore_crc8:
960 EVT VT = Op.getValueType();
962 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
963 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
964 SDValue Crc(Data.getNode(), 1);
965 SDValue Results[] = { Crc, Data };
966 return DAG.getMergeValues(Results, DL);
971 SDValue XCoreTargetLowering::
972 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
974 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
977 SDValue XCoreTargetLowering::
978 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
979 AtomicSDNode *N = cast<AtomicSDNode>(Op);
980 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
981 assert(N->getOrdering() <= Monotonic &&
982 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
983 if (N->getMemoryVT() == MVT::i32) {
984 if (N->getAlignment() < 4)
985 report_fatal_error("atomic load must be aligned");
986 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
987 N->getChain(), N->getBasePtr(), N->getPointerInfo(),
988 N->isVolatile(), N->isNonTemporal(), N->isInvariant(),
989 N->getAlignment(), N->getAAInfo(), N->getRanges());
991 if (N->getMemoryVT() == MVT::i16) {
992 if (N->getAlignment() < 2)
993 report_fatal_error("atomic load must be aligned");
994 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
995 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
996 N->isVolatile(), N->isNonTemporal(),
997 N->isInvariant(), N->getAlignment(), N->getAAInfo());
999 if (N->getMemoryVT() == MVT::i8)
1000 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
1001 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1002 N->isVolatile(), N->isNonTemporal(),
1003 N->isInvariant(), N->getAlignment(), N->getAAInfo());
1007 SDValue XCoreTargetLowering::
1008 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1009 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1010 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1011 assert(N->getOrdering() <= Monotonic &&
1012 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1013 if (N->getMemoryVT() == MVT::i32) {
1014 if (N->getAlignment() < 4)
1015 report_fatal_error("atomic store must be aligned");
1016 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1017 N->getBasePtr(), N->getPointerInfo(),
1018 N->isVolatile(), N->isNonTemporal(),
1019 N->getAlignment(), N->getAAInfo());
1021 if (N->getMemoryVT() == MVT::i16) {
1022 if (N->getAlignment() < 2)
1023 report_fatal_error("atomic store must be aligned");
1024 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1025 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1026 N->isVolatile(), N->isNonTemporal(),
1027 N->getAlignment(), N->getAAInfo());
1029 if (N->getMemoryVT() == MVT::i8)
1030 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1031 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1032 N->isVolatile(), N->isNonTemporal(),
1033 N->getAlignment(), N->getAAInfo());
1037 //===----------------------------------------------------------------------===//
1038 // Calling Convention Implementation
1039 //===----------------------------------------------------------------------===//
1041 #include "XCoreGenCallingConv.inc"
1043 //===----------------------------------------------------------------------===//
1044 // Call Calling Convention Implementation
1045 //===----------------------------------------------------------------------===//
1047 /// XCore call implementation
1049 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1050 SmallVectorImpl<SDValue> &InVals) const {
1051 SelectionDAG &DAG = CLI.DAG;
1053 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1054 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1055 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1056 SDValue Chain = CLI.Chain;
1057 SDValue Callee = CLI.Callee;
1058 bool &isTailCall = CLI.IsTailCall;
1059 CallingConv::ID CallConv = CLI.CallConv;
1060 bool isVarArg = CLI.IsVarArg;
1062 // XCore target does not yet support tail call optimization.
1065 // For now, only CallingConv::C implemented
1069 llvm_unreachable("Unsupported calling convention");
1070 case CallingConv::Fast:
1071 case CallingConv::C:
1072 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1073 Outs, OutVals, Ins, dl, DAG, InVals);
1077 /// LowerCallResult - Lower the result values of a call into the
1078 /// appropriate copies out of appropriate physical registers / memory locations.
1080 LowerCallResult(SDValue Chain, SDValue InFlag,
1081 const SmallVectorImpl<CCValAssign> &RVLocs,
1082 SDLoc dl, SelectionDAG &DAG,
1083 SmallVectorImpl<SDValue> &InVals) {
1084 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1085 // Copy results out of physical registers.
1086 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1087 const CCValAssign &VA = RVLocs[i];
1088 if (VA.isRegLoc()) {
1089 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1090 InFlag).getValue(1);
1091 InFlag = Chain.getValue(2);
1092 InVals.push_back(Chain.getValue(0));
1094 assert(VA.isMemLoc());
1095 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1097 // Reserve space for this result.
1098 InVals.push_back(SDValue());
1102 // Copy results out of memory.
1103 SmallVector<SDValue, 4> MemOpChains;
1104 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1105 int offset = ResultMemLocs[i].first;
1106 unsigned index = ResultMemLocs[i].second;
1107 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1108 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1109 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1110 InVals[index] = load;
1111 MemOpChains.push_back(load.getValue(1));
1114 // Transform all loads nodes into one single node because
1115 // all load nodes are independent of each other.
1116 if (!MemOpChains.empty())
1117 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1122 /// LowerCCCCallTo - functions arguments are copied from virtual
1123 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1124 /// CALLSEQ_END are emitted.
1125 /// TODO: isTailCall, sret.
1127 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1128 CallingConv::ID CallConv, bool isVarArg,
1130 const SmallVectorImpl<ISD::OutputArg> &Outs,
1131 const SmallVectorImpl<SDValue> &OutVals,
1132 const SmallVectorImpl<ISD::InputArg> &Ins,
1133 SDLoc dl, SelectionDAG &DAG,
1134 SmallVectorImpl<SDValue> &InVals) const {
1136 // Analyze operands of the call, assigning locations to each operand.
1137 SmallVector<CCValAssign, 16> ArgLocs;
1138 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1141 // The ABI dictates there should be one stack slot available to the callee
1142 // on function entry (for saving lr).
1143 CCInfo.AllocateStack(4, 4);
1145 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1147 SmallVector<CCValAssign, 16> RVLocs;
1148 // Analyze return values to determine the number of bytes of stack required.
1149 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1151 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1152 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1154 // Get a count of how many bytes are to be pushed on the stack.
1155 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1156 auto PtrVT = getPointerTy(DAG.getDataLayout());
1158 Chain = DAG.getCALLSEQ_START(Chain,
1159 DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
1161 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1162 SmallVector<SDValue, 12> MemOpChains;
1164 // Walk the register/memloc assignments, inserting copies/loads.
1165 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1166 CCValAssign &VA = ArgLocs[i];
1167 SDValue Arg = OutVals[i];
1169 // Promote the value if needed.
1170 switch (VA.getLocInfo()) {
1171 default: llvm_unreachable("Unknown loc info!");
1172 case CCValAssign::Full: break;
1173 case CCValAssign::SExt:
1174 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1176 case CCValAssign::ZExt:
1177 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1179 case CCValAssign::AExt:
1180 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1184 // Arguments that can be passed on register must be kept at
1185 // RegsToPass vector
1186 if (VA.isRegLoc()) {
1187 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1189 assert(VA.isMemLoc());
1191 int Offset = VA.getLocMemOffset();
1193 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1195 DAG.getConstant(Offset/4, dl,
1200 // Transform all store nodes into one single node because
1201 // all store nodes are independent of each other.
1202 if (!MemOpChains.empty())
1203 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1205 // Build a sequence of copy-to-reg nodes chained together with token
1206 // chain and flag operands which copy the outgoing args into registers.
1207 // The InFlag in necessary since all emitted instructions must be
1210 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1211 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1212 RegsToPass[i].second, InFlag);
1213 InFlag = Chain.getValue(1);
1216 // If the callee is a GlobalAddress node (quite common, every direct call is)
1217 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1218 // Likewise ExternalSymbol -> TargetExternalSymbol.
1219 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1220 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1221 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1222 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1224 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1225 // = Chain, Callee, Reg#1, Reg#2, ...
1227 // Returns a chain & a flag for retval copy to use.
1228 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1229 SmallVector<SDValue, 8> Ops;
1230 Ops.push_back(Chain);
1231 Ops.push_back(Callee);
1233 // Add argument registers to the end of the list so that they are
1234 // known live into the call.
1235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1236 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1237 RegsToPass[i].second.getValueType()));
1239 if (InFlag.getNode())
1240 Ops.push_back(InFlag);
1242 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1243 InFlag = Chain.getValue(1);
1245 // Create the CALLSEQ_END node.
1246 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
1247 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
1248 InFlag = Chain.getValue(1);
1250 // Handle result values, copying them out of physregs into vregs that we
1252 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1255 //===----------------------------------------------------------------------===//
1256 // Formal Arguments Calling Convention Implementation
1257 //===----------------------------------------------------------------------===//
1260 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1263 /// XCore formal arguments implementation
1265 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1266 CallingConv::ID CallConv,
1268 const SmallVectorImpl<ISD::InputArg> &Ins,
1271 SmallVectorImpl<SDValue> &InVals)
1276 llvm_unreachable("Unsupported calling convention");
1277 case CallingConv::C:
1278 case CallingConv::Fast:
1279 return LowerCCCArguments(Chain, CallConv, isVarArg,
1280 Ins, dl, DAG, InVals);
1284 /// LowerCCCArguments - transform physical registers into
1285 /// virtual registers and generate load operations for
1286 /// arguments places on the stack.
1289 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1290 CallingConv::ID CallConv,
1292 const SmallVectorImpl<ISD::InputArg>
1296 SmallVectorImpl<SDValue> &InVals) const {
1297 MachineFunction &MF = DAG.getMachineFunction();
1298 MachineFrameInfo *MFI = MF.getFrameInfo();
1299 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1300 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1302 // Assign locations to all of the incoming arguments.
1303 SmallVector<CCValAssign, 16> ArgLocs;
1304 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1307 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1309 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1311 unsigned LRSaveSize = StackSlotSize;
1314 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1316 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1317 // scheduler clobbering a register before it has been copied.
1319 // 1. CopyFromReg (and load) arg & vararg registers.
1320 // 2. Chain CopyFromReg nodes into a TokenFactor.
1321 // 3. Memcpy 'byVal' args & push final InVals.
1322 // 4. Chain mem ops nodes into a TokenFactor.
1323 SmallVector<SDValue, 4> CFRegNode;
1324 SmallVector<ArgDataPair, 4> ArgData;
1325 SmallVector<SDValue, 4> MemOps;
1327 // 1a. CopyFromReg (and load) arg registers.
1328 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1330 CCValAssign &VA = ArgLocs[i];
1333 if (VA.isRegLoc()) {
1334 // Arguments passed in registers
1335 EVT RegVT = VA.getLocVT();
1336 switch (RegVT.getSimpleVT().SimpleTy) {
1340 errs() << "LowerFormalArguments Unhandled argument type: "
1341 << RegVT.getSimpleVT().SimpleTy << "\n";
1343 llvm_unreachable(nullptr);
1346 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1347 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1348 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1349 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1353 assert(VA.isMemLoc());
1354 // Load the argument to a virtual register
1355 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1356 if (ObjSize > StackSlotSize) {
1357 errs() << "LowerFormalArguments Unhandled argument type: "
1358 << EVT(VA.getLocVT()).getEVTString()
1361 // Create the frame index object for this incoming parameter...
1362 int FI = MFI->CreateFixedObject(ObjSize,
1363 LRSaveSize + VA.getLocMemOffset(),
1366 // Create the SelectionDAG nodes corresponding to a load
1367 //from this parameter
1368 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1369 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1370 MachinePointerInfo::getFixedStack(FI),
1371 false, false, false, 0);
1373 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1374 ArgData.push_back(ADP);
1377 // 1b. CopyFromReg vararg registers.
1379 // Argument registers
1380 static const MCPhysReg ArgRegs[] = {
1381 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1383 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1384 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs);
1385 if (FirstVAReg < array_lengthof(ArgRegs)) {
1387 // Save remaining registers, storing higher register numbers at a higher
1389 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1390 // Create a stack slot
1391 int FI = MFI->CreateFixedObject(4, offset, true);
1392 if (i == (int)FirstVAReg) {
1393 XFI->setVarArgsFrameIndex(FI);
1395 offset -= StackSlotSize;
1396 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1397 // Move argument from phys reg -> virt reg
1398 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1399 RegInfo.addLiveIn(ArgRegs[i], VReg);
1400 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1401 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1402 // Move argument from virt reg -> stack
1403 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1404 MachinePointerInfo(), false, false, 0);
1405 MemOps.push_back(Store);
1408 // This will point to the next argument passed via stack.
1409 XFI->setVarArgsFrameIndex(
1410 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1415 // 2. chain CopyFromReg nodes into a TokenFactor.
1416 if (!CFRegNode.empty())
1417 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1419 // 3. Memcpy 'byVal' args & push final InVals.
1420 // Aggregates passed "byVal" need to be copied by the callee.
1421 // The callee will use a pointer to this copy, rather than the original
1423 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1424 ArgDE = ArgData.end();
1425 ArgDI != ArgDE; ++ArgDI) {
1426 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1427 unsigned Size = ArgDI->Flags.getByValSize();
1428 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1429 // Create a new object on the stack and copy the pointee into it.
1430 int FI = MFI->CreateStackObject(Size, Align, false);
1431 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1432 InVals.push_back(FIN);
1433 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1434 DAG.getConstant(Size, dl, MVT::i32),
1435 Align, false, false, false,
1436 MachinePointerInfo(),
1437 MachinePointerInfo()));
1439 InVals.push_back(ArgDI->SDV);
1443 // 4, chain mem ops nodes into a TokenFactor.
1444 if (!MemOps.empty()) {
1445 MemOps.push_back(Chain);
1446 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1452 //===----------------------------------------------------------------------===//
1453 // Return Value Calling Convention Implementation
1454 //===----------------------------------------------------------------------===//
1456 bool XCoreTargetLowering::
1457 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1459 const SmallVectorImpl<ISD::OutputArg> &Outs,
1460 LLVMContext &Context) const {
1461 SmallVector<CCValAssign, 16> RVLocs;
1462 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1463 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1465 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1471 XCoreTargetLowering::LowerReturn(SDValue Chain,
1472 CallingConv::ID CallConv, bool isVarArg,
1473 const SmallVectorImpl<ISD::OutputArg> &Outs,
1474 const SmallVectorImpl<SDValue> &OutVals,
1475 SDLoc dl, SelectionDAG &DAG) const {
1477 XCoreFunctionInfo *XFI =
1478 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1479 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1481 // CCValAssign - represent the assignment of
1482 // the return value to a location
1483 SmallVector<CCValAssign, 16> RVLocs;
1485 // CCState - Info about the registers and stack slot.
1486 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1489 // Analyze return values.
1491 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1493 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1496 SmallVector<SDValue, 4> RetOps(1, Chain);
1498 // Return on XCore is always a "retsp 0"
1499 RetOps.push_back(DAG.getConstant(0, dl, MVT::i32));
1501 SmallVector<SDValue, 4> MemOpChains;
1502 // Handle return values that must be copied to memory.
1503 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1504 CCValAssign &VA = RVLocs[i];
1507 assert(VA.isMemLoc());
1509 report_fatal_error("Can't return value from vararg function in memory");
1512 int Offset = VA.getLocMemOffset();
1513 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1514 // Create the frame index object for the memory location.
1515 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1517 // Create a SelectionDAG node corresponding to a store
1518 // to this memory location.
1519 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1520 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1521 MachinePointerInfo::getFixedStack(FI), false, false,
1525 // Transform all store nodes into one single node because
1526 // all stores are independent of each other.
1527 if (!MemOpChains.empty())
1528 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1530 // Now handle return values copied to registers.
1531 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1532 CCValAssign &VA = RVLocs[i];
1535 // Copy the result values into the output registers.
1536 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1538 // guarantee that all emitted copies are
1539 // stuck together, avoiding something bad
1540 Flag = Chain.getValue(1);
1541 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1544 RetOps[0] = Chain; // Update chain.
1546 // Add the flag if we have it.
1548 RetOps.push_back(Flag);
1550 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1553 //===----------------------------------------------------------------------===//
1554 // Other Lowering Code
1555 //===----------------------------------------------------------------------===//
1558 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1559 MachineBasicBlock *BB) const {
1560 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1561 DebugLoc dl = MI->getDebugLoc();
1562 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1563 "Unexpected instr type to insert");
1565 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1566 // control-flow pattern. The incoming instruction knows the destination vreg
1567 // to set, the condition code register to branch on, the true/false values to
1568 // select between, and a branch opcode to use.
1569 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1570 MachineFunction::iterator It = BB;
1576 // cmpTY ccX, r1, r2
1578 // fallthrough --> copy0MBB
1579 MachineBasicBlock *thisMBB = BB;
1580 MachineFunction *F = BB->getParent();
1581 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1582 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1583 F->insert(It, copy0MBB);
1584 F->insert(It, sinkMBB);
1586 // Transfer the remainder of BB and its successor edges to sinkMBB.
1587 sinkMBB->splice(sinkMBB->begin(), BB,
1588 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1589 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1591 // Next, add the true and fallthrough blocks as its successors.
1592 BB->addSuccessor(copy0MBB);
1593 BB->addSuccessor(sinkMBB);
1595 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1596 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1599 // %FalseValue = ...
1600 // # fallthrough to sinkMBB
1603 // Update machine-CFG edges
1604 BB->addSuccessor(sinkMBB);
1607 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1610 BuildMI(*BB, BB->begin(), dl,
1611 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1612 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1613 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1615 MI->eraseFromParent(); // The pseudo instruction is gone now.
1619 //===----------------------------------------------------------------------===//
1620 // Target Optimization Hooks
1621 //===----------------------------------------------------------------------===//
1623 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1624 DAGCombinerInfo &DCI) const {
1625 SelectionDAG &DAG = DCI.DAG;
1627 switch (N->getOpcode()) {
1629 case ISD::INTRINSIC_VOID:
1630 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1631 case Intrinsic::xcore_outt:
1632 case Intrinsic::xcore_outct:
1633 case Intrinsic::xcore_chkct: {
1634 SDValue OutVal = N->getOperand(3);
1635 // These instructions ignore the high bits.
1636 if (OutVal.hasOneUse()) {
1637 unsigned BitWidth = OutVal.getValueSizeInBits();
1638 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1639 APInt KnownZero, KnownOne;
1640 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1641 !DCI.isBeforeLegalizeOps());
1642 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1643 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1644 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1646 DCI.CommitTargetLoweringOpt(TLO);
1650 case Intrinsic::xcore_setpt: {
1651 SDValue Time = N->getOperand(3);
1652 // This instruction ignores the high bits.
1653 if (Time.hasOneUse()) {
1654 unsigned BitWidth = Time.getValueSizeInBits();
1655 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1656 APInt KnownZero, KnownOne;
1657 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1658 !DCI.isBeforeLegalizeOps());
1659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1660 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1661 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1663 DCI.CommitTargetLoweringOpt(TLO);
1669 case XCoreISD::LADD: {
1670 SDValue N0 = N->getOperand(0);
1671 SDValue N1 = N->getOperand(1);
1672 SDValue N2 = N->getOperand(2);
1673 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1675 EVT VT = N0.getValueType();
1677 // canonicalize constant to RHS
1679 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1681 // fold (ladd 0, 0, x) -> 0, x & 1
1682 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1683 SDValue Carry = DAG.getConstant(0, dl, VT);
1684 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1685 DAG.getConstant(1, dl, VT));
1686 SDValue Ops[] = { Result, Carry };
1687 return DAG.getMergeValues(Ops, dl);
1690 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1692 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1693 APInt KnownZero, KnownOne;
1694 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1695 VT.getSizeInBits() - 1);
1696 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1697 if ((KnownZero & Mask) == Mask) {
1698 SDValue Carry = DAG.getConstant(0, dl, VT);
1699 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1700 SDValue Ops[] = { Result, Carry };
1701 return DAG.getMergeValues(Ops, dl);
1706 case XCoreISD::LSUB: {
1707 SDValue N0 = N->getOperand(0);
1708 SDValue N1 = N->getOperand(1);
1709 SDValue N2 = N->getOperand(2);
1710 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1711 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1712 EVT VT = N0.getValueType();
1714 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1715 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1716 APInt KnownZero, KnownOne;
1717 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1718 VT.getSizeInBits() - 1);
1719 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1720 if ((KnownZero & Mask) == Mask) {
1721 SDValue Borrow = N2;
1722 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1723 DAG.getConstant(0, dl, VT), N2);
1724 SDValue Ops[] = { Result, Borrow };
1725 return DAG.getMergeValues(Ops, dl);
1729 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1731 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1732 APInt KnownZero, KnownOne;
1733 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1734 VT.getSizeInBits() - 1);
1735 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1736 if ((KnownZero & Mask) == Mask) {
1737 SDValue Borrow = DAG.getConstant(0, dl, VT);
1738 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1739 SDValue Ops[] = { Result, Borrow };
1740 return DAG.getMergeValues(Ops, dl);
1745 case XCoreISD::LMUL: {
1746 SDValue N0 = N->getOperand(0);
1747 SDValue N1 = N->getOperand(1);
1748 SDValue N2 = N->getOperand(2);
1749 SDValue N3 = N->getOperand(3);
1750 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1751 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1752 EVT VT = N0.getValueType();
1753 // Canonicalize multiplicative constant to RHS. If both multiplicative
1754 // operands are constant canonicalize smallest to RHS.
1755 if ((N0C && !N1C) ||
1756 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1757 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1761 if (N1C && N1C->isNullValue()) {
1762 // If the high result is unused fold to add(a, b)
1763 if (N->hasNUsesOfValue(0, 0)) {
1764 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1765 SDValue Ops[] = { Lo, Lo };
1766 return DAG.getMergeValues(Ops, dl);
1768 // Otherwise fold to ladd(a, b, 0)
1770 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1771 SDValue Carry(Result.getNode(), 1);
1772 SDValue Ops[] = { Carry, Result };
1773 return DAG.getMergeValues(Ops, dl);
1778 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1779 // lmul(x, y, a, b). The high result of lmul will be ignored.
1780 // This is only profitable if the intermediate results are unused
1782 SDValue Mul0, Mul1, Addend0, Addend1;
1783 if (N->getValueType(0) == MVT::i32 &&
1784 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1785 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1786 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1787 Mul1, Addend0, Addend1);
1788 SDValue Result(Ignored.getNode(), 1);
1791 APInt HighMask = APInt::getHighBitsSet(64, 32);
1792 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1793 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1794 // before type legalization as it is messy to match the operands after
1796 if (N->getValueType(0) == MVT::i64 &&
1797 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1798 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1799 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1800 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1801 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1802 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1803 Mul0, DAG.getConstant(0, dl, MVT::i32));
1804 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1805 Mul1, DAG.getConstant(0, dl, MVT::i32));
1806 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1807 Addend0, DAG.getConstant(0, dl, MVT::i32));
1808 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1809 Addend1, DAG.getConstant(0, dl, MVT::i32));
1810 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1811 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1812 Addend0L, Addend1L);
1813 SDValue Lo(Hi.getNode(), 1);
1814 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1819 // Replace unaligned store of unaligned load with memmove.
1820 StoreSDNode *ST = cast<StoreSDNode>(N);
1821 if (!DCI.isBeforeLegalize() ||
1822 allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1823 ST->getAddressSpace(),
1824 ST->getAlignment()) ||
1825 ST->isVolatile() || ST->isIndexed()) {
1828 SDValue Chain = ST->getChain();
1830 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1831 if (StoreBits % 8) {
1834 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
1835 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1836 unsigned Alignment = ST->getAlignment();
1837 if (Alignment >= ABIAlignment) {
1841 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1842 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1843 LD->getAlignment() == Alignment &&
1844 !LD->isVolatile() && !LD->isIndexed() &&
1845 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1846 bool isTail = isInTailCallPosition(DAG, ST, Chain);
1847 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1849 DAG.getConstant(StoreBits/8, dl, MVT::i32),
1850 Alignment, false, isTail, ST->getPointerInfo(),
1851 LD->getPointerInfo());
1860 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1863 const SelectionDAG &DAG,
1864 unsigned Depth) const {
1865 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1866 switch (Op.getOpcode()) {
1868 case XCoreISD::LADD:
1869 case XCoreISD::LSUB:
1870 if (Op.getResNo() == 1) {
1871 // Top bits of carry / borrow are clear.
1872 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1873 KnownZero.getBitWidth() - 1);
1876 case ISD::INTRINSIC_W_CHAIN:
1878 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1880 case Intrinsic::xcore_getts:
1881 // High bits are known to be zero.
1882 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1883 KnownZero.getBitWidth() - 16);
1885 case Intrinsic::xcore_int:
1886 case Intrinsic::xcore_inct:
1887 // High bits are known to be zero.
1888 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1889 KnownZero.getBitWidth() - 8);
1891 case Intrinsic::xcore_testct:
1892 // Result is either 0 or 1.
1893 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1894 KnownZero.getBitWidth() - 1);
1896 case Intrinsic::xcore_testwct:
1897 // Result is in the range 0 - 4.
1898 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1899 KnownZero.getBitWidth() - 3);
1907 //===----------------------------------------------------------------------===//
1908 // Addressing mode description hooks
1909 //===----------------------------------------------------------------------===//
1911 static inline bool isImmUs(int64_t val)
1913 return (val >= 0 && val <= 11);
1916 static inline bool isImmUs2(int64_t val)
1918 return (val%2 == 0 && isImmUs(val/2));
1921 static inline bool isImmUs4(int64_t val)
1923 return (val%4 == 0 && isImmUs(val/4));
1926 /// isLegalAddressingMode - Return true if the addressing mode represented
1927 /// by AM is legal for this target, for a load/store of the specified type.
1928 bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1929 const AddrMode &AM, Type *Ty,
1930 unsigned AS) const {
1931 if (Ty->getTypeID() == Type::VoidTyID)
1932 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1934 unsigned Size = DL.getTypeAllocSize(Ty);
1936 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1943 if (AM.Scale == 0) {
1944 return isImmUs(AM.BaseOffs);
1947 return AM.Scale == 1 && AM.BaseOffs == 0;
1951 if (AM.Scale == 0) {
1952 return isImmUs2(AM.BaseOffs);
1955 return AM.Scale == 2 && AM.BaseOffs == 0;
1958 if (AM.Scale == 0) {
1959 return isImmUs4(AM.BaseOffs);
1962 return AM.Scale == 4 && AM.BaseOffs == 0;
1966 //===----------------------------------------------------------------------===//
1967 // XCore Inline Assembly Support
1968 //===----------------------------------------------------------------------===//
1970 std::pair<unsigned, const TargetRegisterClass *>
1971 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1972 StringRef Constraint,
1974 if (Constraint.size() == 1) {
1975 switch (Constraint[0]) {
1978 return std::make_pair(0U, &XCore::GRRegsRegClass);
1981 // Use the default implementation in TargetLowering to convert the register
1982 // constraint into a member of a register class.
1983 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);