1 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the XCoreTargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "xcore-lower"
16 #include "XCoreISelLowering.h"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreTargetObjectFile.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
44 const char *XCoreTargetLowering::
45 getTargetNodeName(unsigned Opcode) const
49 case XCoreISD::BL : return "XCoreISD::BL";
50 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
51 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
52 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
53 case XCoreISD::STWSP : return "XCoreISD::STWSP";
54 case XCoreISD::RETSP : return "XCoreISD::RETSP";
55 case XCoreISD::LADD : return "XCoreISD::LADD";
56 case XCoreISD::LSUB : return "XCoreISD::LSUB";
57 case XCoreISD::LMUL : return "XCoreISD::LMUL";
58 case XCoreISD::MACCU : return "XCoreISD::MACCU";
59 case XCoreISD::MACCS : return "XCoreISD::MACCS";
60 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
61 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
62 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
63 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
64 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
65 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
66 default : return NULL;
70 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
71 : TargetLowering(XTM, new XCoreTargetObjectFile()),
73 Subtarget(*XTM.getSubtargetImpl()) {
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78 // Compute derived properties from the register classes
79 computeRegisterProperties();
81 // Division is expensive
82 setIntDivIsCheap(false);
84 setStackPointerRegisterToSaveRestore(XCore::SP);
86 setSchedulingPreference(Sched::Source);
88 // Use i32 for setcc operations results (slt, sgt, ...).
89 setBooleanContents(ZeroOrOneBooleanContent);
90 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
92 // XCore does not have the NodeTypes below.
93 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
94 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
95 setOperationAction(ISD::ADDC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDE, MVT::i32, Expand);
97 setOperationAction(ISD::SUBC, MVT::i32, Expand);
98 setOperationAction(ISD::SUBE, MVT::i32, Expand);
100 // Stop the combiner recombining select and set_cc
101 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
104 setOperationAction(ISD::ADD, MVT::i64, Custom);
105 setOperationAction(ISD::SUB, MVT::i64, Custom);
106 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
107 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
108 setOperationAction(ISD::MULHS, MVT::i32, Expand);
109 setOperationAction(ISD::MULHU, MVT::i32, Expand);
110 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
112 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
115 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
116 setOperationAction(ISD::ROTL , MVT::i32, Expand);
117 setOperationAction(ISD::ROTR , MVT::i32, Expand);
118 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
121 setOperationAction(ISD::TRAP, MVT::Other, Legal);
124 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
126 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
127 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
129 // Conversion of i64 -> double produces constantpool nodes
130 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
133 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
137 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
138 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
140 // Custom expand misaligned loads / stores.
141 setOperationAction(ISD::LOAD, MVT::i32, Custom);
142 setOperationAction(ISD::STORE, MVT::i32, Custom);
145 setOperationAction(ISD::VAEND, MVT::Other, Expand);
146 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
147 setOperationAction(ISD::VAARG, MVT::Other, Custom);
148 setOperationAction(ISD::VASTART, MVT::Other, Custom);
151 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
152 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
153 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
155 // Exception handling
156 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
157 setExceptionPointerRegister(XCore::R0);
158 setExceptionSelectorRegister(XCore::R1);
159 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
162 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
163 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
164 setInsertFencesForAtomic(true);
165 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
166 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
167 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
169 // TRAMPOLINE is custom lowered.
170 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
171 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
173 // We want to custom lower some of our intrinsics.
174 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
176 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
177 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
178 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
180 // We have target-specific dag combine patterns for the following nodes:
181 setTargetDAGCombine(ISD::STORE);
182 setTargetDAGCombine(ISD::ADD);
184 setMinFunctionAlignment(1);
187 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
188 if (Val.getOpcode() != ISD::LOAD)
191 EVT VT1 = Val.getValueType();
192 if (!VT1.isSimple() || !VT1.isInteger() ||
193 !VT2.isSimple() || !VT2.isInteger())
196 switch (VT1.getSimpleVT().SimpleTy) {
205 SDValue XCoreTargetLowering::
206 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
207 switch (Op.getOpcode())
209 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
210 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
211 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
212 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
213 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
214 case ISD::LOAD: return LowerLOAD(Op, DAG);
215 case ISD::STORE: return LowerSTORE(Op, DAG);
216 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
217 case ISD::VAARG: return LowerVAARG(Op, DAG);
218 case ISD::VASTART: return LowerVASTART(Op, DAG);
219 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
220 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
221 // FIXME: Remove these when LegalizeDAGTypes lands.
223 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
224 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
225 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
226 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
227 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
228 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
229 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
230 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
231 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
232 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
234 llvm_unreachable("unimplemented operand");
238 /// ReplaceNodeResults - Replace the results of node with an illegal result
239 /// type with new values built out of custom code.
240 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
241 SmallVectorImpl<SDValue>&Results,
242 SelectionDAG &DAG) const {
243 switch (N->getOpcode()) {
245 llvm_unreachable("Don't know how to custom expand this!");
248 Results.push_back(ExpandADDSUB(N, DAG));
253 //===----------------------------------------------------------------------===//
254 // Misc Lower Operation implementation
255 //===----------------------------------------------------------------------===//
257 SDValue XCoreTargetLowering::
258 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
261 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
262 Op.getOperand(3), Op.getOperand(4));
263 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
267 SDValue XCoreTargetLowering::
268 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
269 SelectionDAG &DAG) const
271 // FIXME there is no actual debug info here
273 const GlobalValue *UnderlyingGV = GV;
274 // If GV is an alias then use the aliasee to determine the wrapper type
275 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
276 UnderlyingGV = GA->resolveAliasedGlobal();
277 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
278 if (GVar->isConstant())
279 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
280 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
282 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
285 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
286 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
289 Type *ObjType = GV->getType()->getPointerElementType();
290 if (!ObjType->isSized())
293 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
294 return ObjSize < CodeModelLargeSize && ObjSize != 0;
297 SDValue XCoreTargetLowering::
298 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
300 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
301 const GlobalValue *GV = GN->getGlobal();
303 int64_t Offset = GN->getOffset();
304 if (IsSmallObject(GV, *this)) {
305 // We can only fold positive offsets that are a multiple of the word size.
306 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
307 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
308 GA = getGlobalAddressWrapper(GA, GV, DAG);
309 // Handle the rest of the offset.
310 if (Offset != FoldedOffset) {
311 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
312 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
316 // Ideally we would not fold in offset with an index <= 11.
317 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
318 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
319 Ty = Type::getInt32Ty(*DAG.getContext());
320 Constant *Idx = ConstantInt::get(Ty, Offset);
321 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
322 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
323 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
324 MachinePointerInfo(), false, false, false, 0);
328 SDValue XCoreTargetLowering::
329 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
333 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
334 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
336 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
339 SDValue XCoreTargetLowering::
340 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
342 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
343 // FIXME there isn't really debug info here
345 EVT PtrVT = Op.getValueType();
347 if (CP->isMachineConstantPoolEntry()) {
348 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
349 CP->getAlignment(), CP->getOffset());
351 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
352 CP->getAlignment(), CP->getOffset());
354 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
357 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
358 return MachineJumpTableInfo::EK_Inline;
361 SDValue XCoreTargetLowering::
362 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
364 SDValue Chain = Op.getOperand(0);
365 SDValue Table = Op.getOperand(1);
366 SDValue Index = Op.getOperand(2);
368 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
369 unsigned JTI = JT->getIndex();
370 MachineFunction &MF = DAG.getMachineFunction();
371 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
372 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
374 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
375 if (NumEntries <= 32) {
376 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
378 assert((NumEntries >> 31) == 0);
379 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
380 DAG.getConstant(1, MVT::i32));
381 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
385 SDValue XCoreTargetLowering::
386 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
387 int64_t Offset, SelectionDAG &DAG) const
389 if ((Offset & 0x3) == 0) {
390 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
391 false, false, false, 0);
393 // Lower to pair of consecutive word aligned loads plus some bit shifting.
394 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
395 int32_t LowOffset = HighOffset - 4;
396 SDValue LowAddr, HighAddr;
397 if (GlobalAddressSDNode *GASD =
398 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
399 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
401 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
404 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
405 DAG.getConstant(LowOffset, MVT::i32));
406 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
407 DAG.getConstant(HighOffset, MVT::i32));
409 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
410 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
412 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
413 LowAddr, MachinePointerInfo(),
414 false, false, false, 0);
415 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
416 HighAddr, MachinePointerInfo(),
417 false, false, false, 0);
418 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
419 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
420 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
421 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
423 SDValue Ops[] = { Result, Chain };
424 return DAG.getMergeValues(Ops, 2, DL);
427 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
429 APInt KnownZero, KnownOne;
430 DAG.ComputeMaskedBits(Value, KnownZero, KnownOne);
431 return KnownZero.countTrailingOnes() >= 2;
434 SDValue XCoreTargetLowering::
435 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
437 LoadSDNode *LD = cast<LoadSDNode>(Op);
438 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
439 "Unexpected extension type");
440 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
441 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
444 unsigned ABIAlignment = getDataLayout()->
445 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
446 // Leave aligned load alone.
447 if (LD->getAlignment() >= ABIAlignment)
450 SDValue Chain = LD->getChain();
451 SDValue BasePtr = LD->getBasePtr();
454 if (!LD->isVolatile()) {
455 const GlobalValue *GV;
457 if (DAG.isBaseWithConstantOffset(BasePtr) &&
458 isWordAligned(BasePtr->getOperand(0), DAG)) {
459 SDValue NewBasePtr = BasePtr->getOperand(0);
460 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
461 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
464 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
465 MinAlign(GV->getAlignment(), 4) == 4) {
466 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
467 BasePtr->getValueType(0));
468 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
473 if (LD->getAlignment() == 2) {
474 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
475 BasePtr, LD->getPointerInfo(), MVT::i16,
476 LD->isVolatile(), LD->isNonTemporal(), 2);
477 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
478 DAG.getConstant(2, MVT::i32));
479 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
481 LD->getPointerInfo().getWithOffset(2),
482 MVT::i16, LD->isVolatile(),
483 LD->isNonTemporal(), 2);
484 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
485 DAG.getConstant(16, MVT::i32));
486 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
487 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
489 SDValue Ops[] = { Result, Chain };
490 return DAG.getMergeValues(Ops, 2, DL);
493 // Lower to a call to __misaligned_load(BasePtr).
494 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
495 TargetLowering::ArgListTy Args;
496 TargetLowering::ArgListEntry Entry;
499 Entry.Node = BasePtr;
500 Args.push_back(Entry);
502 TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
503 false, false, 0, CallingConv::C, /*isTailCall=*/false,
504 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
505 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
507 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
510 { CallResult.first, CallResult.second };
512 return DAG.getMergeValues(Ops, 2, DL);
515 SDValue XCoreTargetLowering::
516 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
518 StoreSDNode *ST = cast<StoreSDNode>(Op);
519 assert(!ST->isTruncatingStore() && "Unexpected store type");
520 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
521 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
524 unsigned ABIAlignment = getDataLayout()->
525 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
526 // Leave aligned store alone.
527 if (ST->getAlignment() >= ABIAlignment) {
530 SDValue Chain = ST->getChain();
531 SDValue BasePtr = ST->getBasePtr();
532 SDValue Value = ST->getValue();
535 if (ST->getAlignment() == 2) {
537 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
538 DAG.getConstant(16, MVT::i32));
539 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
540 ST->getPointerInfo(), MVT::i16,
541 ST->isVolatile(), ST->isNonTemporal(),
543 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
544 DAG.getConstant(2, MVT::i32));
545 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
546 ST->getPointerInfo().getWithOffset(2),
547 MVT::i16, ST->isVolatile(),
548 ST->isNonTemporal(), 2);
549 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
552 // Lower to a call to __misaligned_store(BasePtr, Value).
553 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
554 TargetLowering::ArgListTy Args;
555 TargetLowering::ArgListEntry Entry;
558 Entry.Node = BasePtr;
559 Args.push_back(Entry);
562 Args.push_back(Entry);
564 TargetLowering::CallLoweringInfo CLI(Chain,
565 Type::getVoidTy(*DAG.getContext()), false, false,
566 false, false, 0, CallingConv::C, /*isTailCall=*/false,
567 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
568 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
570 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
572 return CallResult.second;
575 SDValue XCoreTargetLowering::
576 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
578 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
579 "Unexpected operand to lower!");
581 SDValue LHS = Op.getOperand(0);
582 SDValue RHS = Op.getOperand(1);
583 SDValue Zero = DAG.getConstant(0, MVT::i32);
584 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
585 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
587 SDValue Lo(Hi.getNode(), 1);
588 SDValue Ops[] = { Lo, Hi };
589 return DAG.getMergeValues(Ops, 2, dl);
592 SDValue XCoreTargetLowering::
593 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
595 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
596 "Unexpected operand to lower!");
598 SDValue LHS = Op.getOperand(0);
599 SDValue RHS = Op.getOperand(1);
600 SDValue Zero = DAG.getConstant(0, MVT::i32);
601 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
602 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
604 SDValue Lo(Hi.getNode(), 1);
605 SDValue Ops[] = { Lo, Hi };
606 return DAG.getMergeValues(Ops, 2, dl);
609 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
610 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
611 /// each intermediate result in the calculation must also have a single use.
612 /// If the Op is in the correct form the constituent parts are written to Mul0,
613 /// Mul1, Addend0 and Addend1.
615 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
616 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
618 if (Op.getOpcode() != ISD::ADD)
620 SDValue N0 = Op.getOperand(0);
621 SDValue N1 = Op.getOperand(1);
624 if (N0.getOpcode() == ISD::ADD) {
627 } else if (N1.getOpcode() == ISD::ADD) {
633 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
635 if (OtherOp.getOpcode() == ISD::MUL) {
636 // add(add(a,b),mul(x,y))
637 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
639 Mul0 = OtherOp.getOperand(0);
640 Mul1 = OtherOp.getOperand(1);
641 Addend0 = AddOp.getOperand(0);
642 Addend1 = AddOp.getOperand(1);
645 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
646 // add(add(mul(x,y),a),b)
647 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
649 Mul0 = AddOp.getOperand(0).getOperand(0);
650 Mul1 = AddOp.getOperand(0).getOperand(1);
651 Addend0 = AddOp.getOperand(1);
655 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
656 // add(add(a,mul(x,y)),b)
657 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
659 Mul0 = AddOp.getOperand(1).getOperand(0);
660 Mul1 = AddOp.getOperand(1).getOperand(1);
661 Addend0 = AddOp.getOperand(0);
668 SDValue XCoreTargetLowering::
669 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
673 if (N->getOperand(0).getOpcode() == ISD::MUL) {
674 Mul = N->getOperand(0);
675 Other = N->getOperand(1);
676 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
677 Mul = N->getOperand(1);
678 Other = N->getOperand(0);
683 SDValue LL, RL, AddendL, AddendH;
684 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
686 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
687 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
688 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
689 Other, DAG.getConstant(0, MVT::i32));
690 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691 Other, DAG.getConstant(1, MVT::i32));
692 APInt HighMask = APInt::getHighBitsSet(64, 32);
693 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
694 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
695 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
696 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
697 // The inputs are both zero-extended.
698 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
699 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
701 SDValue Lo(Hi.getNode(), 1);
702 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
704 if (LHSSB > 32 && RHSSB > 32) {
705 // The inputs are both sign-extended.
706 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
707 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
709 SDValue Lo(Hi.getNode(), 1);
710 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
713 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
714 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
715 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
716 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
717 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
718 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
720 SDValue Lo(Hi.getNode(), 1);
721 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
722 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
723 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
724 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
725 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
728 SDValue XCoreTargetLowering::
729 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
731 assert(N->getValueType(0) == MVT::i64 &&
732 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
733 "Unknown operand to lower!");
735 if (N->getOpcode() == ISD::ADD) {
736 SDValue Result = TryExpandADDWithMul(N, DAG);
737 if (Result.getNode() != 0)
743 // Extract components
744 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
745 N->getOperand(0), DAG.getConstant(0, MVT::i32));
746 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
747 N->getOperand(0), DAG.getConstant(1, MVT::i32));
748 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
749 N->getOperand(1), DAG.getConstant(0, MVT::i32));
750 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751 N->getOperand(1), DAG.getConstant(1, MVT::i32));
754 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
756 SDValue Zero = DAG.getConstant(0, MVT::i32);
757 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
759 SDValue Carry(Lo.getNode(), 1);
761 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
763 SDValue Ignored(Hi.getNode(), 1);
765 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
768 SDValue XCoreTargetLowering::
769 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
771 // Whist llvm does not support aggregate varargs we can ignore
772 // the possibility of the ValueType being an implicit byVal vararg.
773 SDNode *Node = Op.getNode();
774 EVT VT = Node->getValueType(0); // not an aggregate
775 SDValue InChain = Node->getOperand(0);
776 SDValue VAListPtr = Node->getOperand(1);
777 EVT PtrVT = VAListPtr.getValueType();
778 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
780 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
781 VAListPtr, MachinePointerInfo(SV),
782 false, false, false, 0);
783 // Increment the pointer, VAList, to the next vararg
784 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
785 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
786 // Store the incremented VAList to the legalized pointer
787 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
788 MachinePointerInfo(SV), false, false, 0);
789 // Load the actual argument out of the pointer VAList
790 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
791 false, false, false, 0);
794 SDValue XCoreTargetLowering::
795 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
798 // vastart stores the address of the VarArgsFrameIndex slot into the
799 // memory location argument
800 MachineFunction &MF = DAG.getMachineFunction();
801 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
802 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
803 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
804 MachinePointerInfo(), false, false, 0);
807 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
808 SelectionDAG &DAG) const {
809 // This nodes represent llvm.frameaddress on the DAG.
810 // It takes one operand, the index of the frame address to return.
811 // An index of zero corresponds to the current function's frame address.
812 // An index of one to the parent's frame address, and so on.
813 // Depths > 0 not supported yet!
814 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
817 MachineFunction &MF = DAG.getMachineFunction();
818 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
819 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
820 RegInfo->getFrameRegister(MF), MVT::i32);
823 SDValue XCoreTargetLowering::
824 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
825 // This nodes represent llvm.returnaddress on the DAG.
826 // It takes one operand, the index of the return address to return.
827 // An index of zero corresponds to the current function's return address.
828 // An index of one to the parent's return address, and so on.
829 // Depths > 0 not supported yet!
830 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
833 MachineFunction &MF = DAG.getMachineFunction();
834 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
835 int FI = XFI->createLRSpillSlot(MF);
836 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
837 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
838 MachinePointerInfo::getFixedStack(FI), false, false,
842 SDValue XCoreTargetLowering::
843 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
844 // This node represents offset from frame pointer to first on-stack argument.
845 // This is needed for correct stack adjustment during unwind.
846 // However, we don't know the offset until after the frame has be finalised.
847 // This is done during the XCoreFTAOElim pass.
848 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
851 SDValue XCoreTargetLowering::
852 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
853 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
854 // This node represents 'eh_return' gcc dwarf builtin, which is used to
855 // return from exception. The general meaning is: adjust stack by OFFSET and
856 // pass execution to HANDLER.
857 MachineFunction &MF = DAG.getMachineFunction();
858 SDValue Chain = Op.getOperand(0);
859 SDValue Offset = Op.getOperand(1);
860 SDValue Handler = Op.getOperand(2);
863 // Absolute SP = (FP + FrameToArgs) + Offset
864 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
865 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
866 RegInfo->getFrameRegister(MF), MVT::i32);
867 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
869 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
870 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
872 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
873 // which leaves 2 caller saved registers, R2 & R3 for us to use.
874 unsigned StackReg = XCore::R2;
875 unsigned HandlerReg = XCore::R3;
877 SDValue OutChains[] = {
878 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
879 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
882 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 2);
884 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
885 DAG.getRegister(StackReg, MVT::i32),
886 DAG.getRegister(HandlerReg, MVT::i32));
890 SDValue XCoreTargetLowering::
891 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
892 return Op.getOperand(0);
895 SDValue XCoreTargetLowering::
896 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
897 SDValue Chain = Op.getOperand(0);
898 SDValue Trmp = Op.getOperand(1); // trampoline
899 SDValue FPtr = Op.getOperand(2); // nested function
900 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
902 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
905 // LDAPF_u10 r11, nest
906 // LDW_2rus r11, r11[0]
907 // STWSP_ru6 r11, sp[0]
908 // LDAPF_u10 r11, fptr
909 // LDW_2rus r11, r11[0]
915 SDValue OutChains[5];
920 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
921 Addr, MachinePointerInfo(TrmpAddr), false, false,
924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
925 DAG.getConstant(4, MVT::i32));
926 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
927 Addr, MachinePointerInfo(TrmpAddr, 4), false,
930 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
931 DAG.getConstant(8, MVT::i32));
932 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
933 Addr, MachinePointerInfo(TrmpAddr, 8), false,
936 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
937 DAG.getConstant(12, MVT::i32));
938 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
939 MachinePointerInfo(TrmpAddr, 12), false, false,
942 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
943 DAG.getConstant(16, MVT::i32));
944 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
945 MachinePointerInfo(TrmpAddr, 16), false, false,
948 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
951 SDValue XCoreTargetLowering::
952 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
954 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
956 case Intrinsic::xcore_crc8:
957 EVT VT = Op.getValueType();
959 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
960 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
961 SDValue Crc(Data.getNode(), 1);
962 SDValue Results[] = { Crc, Data };
963 return DAG.getMergeValues(Results, 2, DL);
968 SDValue XCoreTargetLowering::
969 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
971 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
974 SDValue XCoreTargetLowering::
975 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
976 AtomicSDNode *N = cast<AtomicSDNode>(Op);
977 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
978 assert(N->getOrdering() <= Monotonic &&
979 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
980 if (N->getMemoryVT() == MVT::i32) {
981 if (N->getAlignment() < 4)
982 report_fatal_error("atomic load must be aligned");
983 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
984 N->getBasePtr(), N->getPointerInfo(),
985 N->isVolatile(), N->isNonTemporal(),
986 N->isInvariant(), N->getAlignment(),
987 N->getTBAAInfo(), N->getRanges());
989 if (N->getMemoryVT() == MVT::i16) {
990 if (N->getAlignment() < 2)
991 report_fatal_error("atomic load must be aligned");
992 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
993 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
994 N->isVolatile(), N->isNonTemporal(),
995 N->getAlignment(), N->getTBAAInfo());
997 if (N->getMemoryVT() == MVT::i8)
998 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
999 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1000 N->isVolatile(), N->isNonTemporal(),
1001 N->getAlignment(), N->getTBAAInfo());
1005 SDValue XCoreTargetLowering::
1006 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1007 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1008 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1009 assert(N->getOrdering() <= Monotonic &&
1010 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1011 if (N->getMemoryVT() == MVT::i32) {
1012 if (N->getAlignment() < 4)
1013 report_fatal_error("atomic store must be aligned");
1014 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1015 N->getBasePtr(), N->getPointerInfo(),
1016 N->isVolatile(), N->isNonTemporal(),
1017 N->getAlignment(), N->getTBAAInfo());
1019 if (N->getMemoryVT() == MVT::i16) {
1020 if (N->getAlignment() < 2)
1021 report_fatal_error("atomic store must be aligned");
1022 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1023 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1024 N->isVolatile(), N->isNonTemporal(),
1025 N->getAlignment(), N->getTBAAInfo());
1027 if (N->getMemoryVT() == MVT::i8)
1028 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1029 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1030 N->isVolatile(), N->isNonTemporal(),
1031 N->getAlignment(), N->getTBAAInfo());
1035 //===----------------------------------------------------------------------===//
1036 // Calling Convention Implementation
1037 //===----------------------------------------------------------------------===//
1039 #include "XCoreGenCallingConv.inc"
1041 //===----------------------------------------------------------------------===//
1042 // Call Calling Convention Implementation
1043 //===----------------------------------------------------------------------===//
1045 /// XCore call implementation
1047 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1048 SmallVectorImpl<SDValue> &InVals) const {
1049 SelectionDAG &DAG = CLI.DAG;
1051 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1052 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1053 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1054 SDValue Chain = CLI.Chain;
1055 SDValue Callee = CLI.Callee;
1056 bool &isTailCall = CLI.IsTailCall;
1057 CallingConv::ID CallConv = CLI.CallConv;
1058 bool isVarArg = CLI.IsVarArg;
1060 // XCore target does not yet support tail call optimization.
1063 // For now, only CallingConv::C implemented
1067 llvm_unreachable("Unsupported calling convention");
1068 case CallingConv::Fast:
1069 case CallingConv::C:
1070 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1071 Outs, OutVals, Ins, dl, DAG, InVals);
1075 /// LowerCCCCallTo - functions arguments are copied from virtual
1076 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1077 /// CALLSEQ_END are emitted.
1078 /// TODO: isTailCall, sret.
1080 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1081 CallingConv::ID CallConv, bool isVarArg,
1083 const SmallVectorImpl<ISD::OutputArg> &Outs,
1084 const SmallVectorImpl<SDValue> &OutVals,
1085 const SmallVectorImpl<ISD::InputArg> &Ins,
1086 SDLoc dl, SelectionDAG &DAG,
1087 SmallVectorImpl<SDValue> &InVals) const {
1089 // Analyze operands of the call, assigning locations to each operand.
1090 SmallVector<CCValAssign, 16> ArgLocs;
1091 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1092 getTargetMachine(), ArgLocs, *DAG.getContext());
1094 // The ABI dictates there should be one stack slot available to the callee
1095 // on function entry (for saving lr).
1096 CCInfo.AllocateStack(4, 4);
1098 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1100 // Get a count of how many bytes are to be pushed on the stack.
1101 unsigned NumBytes = CCInfo.getNextStackOffset();
1103 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1104 getPointerTy(), true), dl);
1106 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1107 SmallVector<SDValue, 12> MemOpChains;
1109 // Walk the register/memloc assignments, inserting copies/loads.
1110 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1111 CCValAssign &VA = ArgLocs[i];
1112 SDValue Arg = OutVals[i];
1114 // Promote the value if needed.
1115 switch (VA.getLocInfo()) {
1116 default: llvm_unreachable("Unknown loc info!");
1117 case CCValAssign::Full: break;
1118 case CCValAssign::SExt:
1119 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1121 case CCValAssign::ZExt:
1122 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1124 case CCValAssign::AExt:
1125 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1129 // Arguments that can be passed on register must be kept at
1130 // RegsToPass vector
1131 if (VA.isRegLoc()) {
1132 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1134 assert(VA.isMemLoc());
1136 int Offset = VA.getLocMemOffset();
1138 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1140 DAG.getConstant(Offset/4, MVT::i32)));
1144 // Transform all store nodes into one single node because
1145 // all store nodes are independent of each other.
1146 if (!MemOpChains.empty())
1147 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1148 &MemOpChains[0], MemOpChains.size());
1150 // Build a sequence of copy-to-reg nodes chained together with token
1151 // chain and flag operands which copy the outgoing args into registers.
1152 // The InFlag in necessary since all emitted instructions must be
1155 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1156 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1157 RegsToPass[i].second, InFlag);
1158 InFlag = Chain.getValue(1);
1161 // If the callee is a GlobalAddress node (quite common, every direct call is)
1162 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1163 // Likewise ExternalSymbol -> TargetExternalSymbol.
1164 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1165 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1166 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1167 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1169 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1170 // = Chain, Callee, Reg#1, Reg#2, ...
1172 // Returns a chain & a flag for retval copy to use.
1173 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1174 SmallVector<SDValue, 8> Ops;
1175 Ops.push_back(Chain);
1176 Ops.push_back(Callee);
1178 // Add argument registers to the end of the list so that they are
1179 // known live into the call.
1180 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1181 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1182 RegsToPass[i].second.getValueType()));
1184 if (InFlag.getNode())
1185 Ops.push_back(InFlag);
1187 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1188 InFlag = Chain.getValue(1);
1190 // Create the CALLSEQ_END node.
1191 Chain = DAG.getCALLSEQ_END(Chain,
1192 DAG.getConstant(NumBytes, getPointerTy(), true),
1193 DAG.getConstant(0, getPointerTy(), true),
1195 InFlag = Chain.getValue(1);
1197 // Handle result values, copying them out of physregs into vregs that we
1199 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1200 Ins, dl, DAG, InVals);
1203 /// LowerCallResult - Lower the result values of a call into the
1204 /// appropriate copies out of appropriate physical registers.
1206 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1207 CallingConv::ID CallConv, bool isVarArg,
1208 const SmallVectorImpl<ISD::InputArg> &Ins,
1209 SDLoc dl, SelectionDAG &DAG,
1210 SmallVectorImpl<SDValue> &InVals) const {
1212 // Assign locations to each value returned by this call.
1213 SmallVector<CCValAssign, 16> RVLocs;
1214 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1215 getTargetMachine(), RVLocs, *DAG.getContext());
1217 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1219 // Copy all of the result registers out of their specified physreg.
1220 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1221 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1222 RVLocs[i].getValVT(), InFlag).getValue(1);
1223 InFlag = Chain.getValue(2);
1224 InVals.push_back(Chain.getValue(0));
1230 //===----------------------------------------------------------------------===//
1231 // Formal Arguments Calling Convention Implementation
1232 //===----------------------------------------------------------------------===//
1235 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1238 /// XCore formal arguments implementation
1240 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1241 CallingConv::ID CallConv,
1243 const SmallVectorImpl<ISD::InputArg> &Ins,
1246 SmallVectorImpl<SDValue> &InVals)
1251 llvm_unreachable("Unsupported calling convention");
1252 case CallingConv::C:
1253 case CallingConv::Fast:
1254 return LowerCCCArguments(Chain, CallConv, isVarArg,
1255 Ins, dl, DAG, InVals);
1259 /// LowerCCCArguments - transform physical registers into
1260 /// virtual registers and generate load operations for
1261 /// arguments places on the stack.
1264 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1265 CallingConv::ID CallConv,
1267 const SmallVectorImpl<ISD::InputArg>
1271 SmallVectorImpl<SDValue> &InVals) const {
1272 MachineFunction &MF = DAG.getMachineFunction();
1273 MachineFrameInfo *MFI = MF.getFrameInfo();
1274 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1276 // Assign locations to all of the incoming arguments.
1277 SmallVector<CCValAssign, 16> ArgLocs;
1278 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1279 getTargetMachine(), ArgLocs, *DAG.getContext());
1281 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1283 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1285 unsigned LRSaveSize = StackSlotSize;
1287 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1288 // scheduler clobbering a register before it has been copied.
1290 // 1. CopyFromReg (and load) arg & vararg registers.
1291 // 2. Chain CopyFromReg nodes into a TokenFactor.
1292 // 3. Memcpy 'byVal' args & push final InVals.
1293 // 4. Chain mem ops nodes into a TokenFactor.
1294 SmallVector<SDValue, 4> CFRegNode;
1295 SmallVector<ArgDataPair, 4> ArgData;
1296 SmallVector<SDValue, 4> MemOps;
1298 // 1a. CopyFromReg (and load) arg registers.
1299 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1301 CCValAssign &VA = ArgLocs[i];
1304 if (VA.isRegLoc()) {
1305 // Arguments passed in registers
1306 EVT RegVT = VA.getLocVT();
1307 switch (RegVT.getSimpleVT().SimpleTy) {
1311 errs() << "LowerFormalArguments Unhandled argument type: "
1312 << RegVT.getSimpleVT().SimpleTy << "\n";
1314 llvm_unreachable(0);
1317 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1318 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1319 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1320 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1324 assert(VA.isMemLoc());
1325 // Load the argument to a virtual register
1326 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1327 if (ObjSize > StackSlotSize) {
1328 errs() << "LowerFormalArguments Unhandled argument type: "
1329 << EVT(VA.getLocVT()).getEVTString()
1332 // Create the frame index object for this incoming parameter...
1333 int FI = MFI->CreateFixedObject(ObjSize,
1334 LRSaveSize + VA.getLocMemOffset(),
1337 // Create the SelectionDAG nodes corresponding to a load
1338 //from this parameter
1339 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1340 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1341 MachinePointerInfo::getFixedStack(FI),
1342 false, false, false, 0);
1344 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1345 ArgData.push_back(ADP);
1348 // 1b. CopyFromReg vararg registers.
1350 // Argument registers
1351 static const uint16_t ArgRegs[] = {
1352 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1354 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1355 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1356 array_lengthof(ArgRegs));
1357 if (FirstVAReg < array_lengthof(ArgRegs)) {
1359 // Save remaining registers, storing higher register numbers at a higher
1361 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1362 // Create a stack slot
1363 int FI = MFI->CreateFixedObject(4, offset, true);
1364 if (i == (int)FirstVAReg) {
1365 XFI->setVarArgsFrameIndex(FI);
1367 offset -= StackSlotSize;
1368 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1369 // Move argument from phys reg -> virt reg
1370 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1371 RegInfo.addLiveIn(ArgRegs[i], VReg);
1372 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1373 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1374 // Move argument from virt reg -> stack
1375 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1376 MachinePointerInfo(), false, false, 0);
1377 MemOps.push_back(Store);
1380 // This will point to the next argument passed via stack.
1381 XFI->setVarArgsFrameIndex(
1382 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1387 // 2. chain CopyFromReg nodes into a TokenFactor.
1388 if (!CFRegNode.empty())
1389 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &CFRegNode[0],
1392 // 3. Memcpy 'byVal' args & push final InVals.
1393 // Aggregates passed "byVal" need to be copied by the callee.
1394 // The callee will use a pointer to this copy, rather than the original
1396 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1397 ArgDE = ArgData.end();
1398 ArgDI != ArgDE; ++ArgDI) {
1399 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1400 unsigned Size = ArgDI->Flags.getByValSize();
1401 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1402 // Create a new object on the stack and copy the pointee into it.
1403 int FI = MFI->CreateStackObject(Size, Align, false);
1404 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1405 InVals.push_back(FIN);
1406 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1407 DAG.getConstant(Size, MVT::i32),
1408 Align, false, false,
1409 MachinePointerInfo(),
1410 MachinePointerInfo()));
1412 InVals.push_back(ArgDI->SDV);
1416 // 4, chain mem ops nodes into a TokenFactor.
1417 if (!MemOps.empty()) {
1418 MemOps.push_back(Chain);
1419 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
1426 //===----------------------------------------------------------------------===//
1427 // Return Value Calling Convention Implementation
1428 //===----------------------------------------------------------------------===//
1430 bool XCoreTargetLowering::
1431 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1433 const SmallVectorImpl<ISD::OutputArg> &Outs,
1434 LLVMContext &Context) const {
1435 SmallVector<CCValAssign, 16> RVLocs;
1436 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1437 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1441 XCoreTargetLowering::LowerReturn(SDValue Chain,
1442 CallingConv::ID CallConv, bool isVarArg,
1443 const SmallVectorImpl<ISD::OutputArg> &Outs,
1444 const SmallVectorImpl<SDValue> &OutVals,
1445 SDLoc dl, SelectionDAG &DAG) const {
1447 // CCValAssign - represent the assignment of
1448 // the return value to a location
1449 SmallVector<CCValAssign, 16> RVLocs;
1451 // CCState - Info about the registers and stack slot.
1452 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1453 getTargetMachine(), RVLocs, *DAG.getContext());
1455 // Analyze return values.
1456 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1459 SmallVector<SDValue, 4> RetOps(1, Chain);
1461 // Return on XCore is always a "retsp 0"
1462 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1464 // Copy the result values into the output registers.
1465 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1466 CCValAssign &VA = RVLocs[i];
1467 assert(VA.isRegLoc() && "Can only return in registers!");
1469 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1472 // guarantee that all emitted copies are
1473 // stuck together, avoiding something bad
1474 Flag = Chain.getValue(1);
1475 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1478 RetOps[0] = Chain; // Update chain.
1480 // Add the flag if we have it.
1482 RetOps.push_back(Flag);
1484 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1485 &RetOps[0], RetOps.size());
1488 //===----------------------------------------------------------------------===//
1489 // Other Lowering Code
1490 //===----------------------------------------------------------------------===//
1493 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1494 MachineBasicBlock *BB) const {
1495 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1496 DebugLoc dl = MI->getDebugLoc();
1497 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1498 "Unexpected instr type to insert");
1500 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1501 // control-flow pattern. The incoming instruction knows the destination vreg
1502 // to set, the condition code register to branch on, the true/false values to
1503 // select between, and a branch opcode to use.
1504 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1505 MachineFunction::iterator It = BB;
1511 // cmpTY ccX, r1, r2
1513 // fallthrough --> copy0MBB
1514 MachineBasicBlock *thisMBB = BB;
1515 MachineFunction *F = BB->getParent();
1516 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1517 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1518 F->insert(It, copy0MBB);
1519 F->insert(It, sinkMBB);
1521 // Transfer the remainder of BB and its successor edges to sinkMBB.
1522 sinkMBB->splice(sinkMBB->begin(), BB,
1523 llvm::next(MachineBasicBlock::iterator(MI)),
1525 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1527 // Next, add the true and fallthrough blocks as its successors.
1528 BB->addSuccessor(copy0MBB);
1529 BB->addSuccessor(sinkMBB);
1531 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1532 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1535 // %FalseValue = ...
1536 // # fallthrough to sinkMBB
1539 // Update machine-CFG edges
1540 BB->addSuccessor(sinkMBB);
1543 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1546 BuildMI(*BB, BB->begin(), dl,
1547 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1548 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1549 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1551 MI->eraseFromParent(); // The pseudo instruction is gone now.
1555 //===----------------------------------------------------------------------===//
1556 // Target Optimization Hooks
1557 //===----------------------------------------------------------------------===//
1559 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1560 DAGCombinerInfo &DCI) const {
1561 SelectionDAG &DAG = DCI.DAG;
1563 switch (N->getOpcode()) {
1565 case XCoreISD::LADD: {
1566 SDValue N0 = N->getOperand(0);
1567 SDValue N1 = N->getOperand(1);
1568 SDValue N2 = N->getOperand(2);
1569 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1570 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1571 EVT VT = N0.getValueType();
1573 // canonicalize constant to RHS
1575 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1577 // fold (ladd 0, 0, x) -> 0, x & 1
1578 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1579 SDValue Carry = DAG.getConstant(0, VT);
1580 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1581 DAG.getConstant(1, VT));
1582 SDValue Ops[] = { Result, Carry };
1583 return DAG.getMergeValues(Ops, 2, dl);
1586 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1588 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1589 APInt KnownZero, KnownOne;
1590 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1591 VT.getSizeInBits() - 1);
1592 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1593 if ((KnownZero & Mask) == Mask) {
1594 SDValue Carry = DAG.getConstant(0, VT);
1595 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1596 SDValue Ops[] = { Result, Carry };
1597 return DAG.getMergeValues(Ops, 2, dl);
1602 case XCoreISD::LSUB: {
1603 SDValue N0 = N->getOperand(0);
1604 SDValue N1 = N->getOperand(1);
1605 SDValue N2 = N->getOperand(2);
1606 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1607 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1608 EVT VT = N0.getValueType();
1610 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1611 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1612 APInt KnownZero, KnownOne;
1613 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1614 VT.getSizeInBits() - 1);
1615 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1616 if ((KnownZero & Mask) == Mask) {
1617 SDValue Borrow = N2;
1618 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1619 DAG.getConstant(0, VT), N2);
1620 SDValue Ops[] = { Result, Borrow };
1621 return DAG.getMergeValues(Ops, 2, dl);
1625 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1627 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1628 APInt KnownZero, KnownOne;
1629 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1630 VT.getSizeInBits() - 1);
1631 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1632 if ((KnownZero & Mask) == Mask) {
1633 SDValue Borrow = DAG.getConstant(0, VT);
1634 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1635 SDValue Ops[] = { Result, Borrow };
1636 return DAG.getMergeValues(Ops, 2, dl);
1641 case XCoreISD::LMUL: {
1642 SDValue N0 = N->getOperand(0);
1643 SDValue N1 = N->getOperand(1);
1644 SDValue N2 = N->getOperand(2);
1645 SDValue N3 = N->getOperand(3);
1646 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1647 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1648 EVT VT = N0.getValueType();
1649 // Canonicalize multiplicative constant to RHS. If both multiplicative
1650 // operands are constant canonicalize smallest to RHS.
1651 if ((N0C && !N1C) ||
1652 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1653 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1657 if (N1C && N1C->isNullValue()) {
1658 // If the high result is unused fold to add(a, b)
1659 if (N->hasNUsesOfValue(0, 0)) {
1660 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1661 SDValue Ops[] = { Lo, Lo };
1662 return DAG.getMergeValues(Ops, 2, dl);
1664 // Otherwise fold to ladd(a, b, 0)
1666 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1667 SDValue Carry(Result.getNode(), 1);
1668 SDValue Ops[] = { Carry, Result };
1669 return DAG.getMergeValues(Ops, 2, dl);
1674 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1675 // lmul(x, y, a, b). The high result of lmul will be ignored.
1676 // This is only profitable if the intermediate results are unused
1678 SDValue Mul0, Mul1, Addend0, Addend1;
1679 if (N->getValueType(0) == MVT::i32 &&
1680 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1681 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1682 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1683 Mul1, Addend0, Addend1);
1684 SDValue Result(Ignored.getNode(), 1);
1687 APInt HighMask = APInt::getHighBitsSet(64, 32);
1688 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1689 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1690 // before type legalization as it is messy to match the operands after
1692 if (N->getValueType(0) == MVT::i64 &&
1693 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1694 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1695 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1696 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1697 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1698 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1699 Mul0, DAG.getConstant(0, MVT::i32));
1700 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1701 Mul1, DAG.getConstant(0, MVT::i32));
1702 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1703 Addend0, DAG.getConstant(0, MVT::i32));
1704 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1705 Addend1, DAG.getConstant(0, MVT::i32));
1706 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1707 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1708 Addend0L, Addend1L);
1709 SDValue Lo(Hi.getNode(), 1);
1710 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1715 // Replace unaligned store of unaligned load with memmove.
1716 StoreSDNode *ST = cast<StoreSDNode>(N);
1717 if (!DCI.isBeforeLegalize() ||
1718 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1719 ST->isVolatile() || ST->isIndexed()) {
1722 SDValue Chain = ST->getChain();
1724 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1725 if (StoreBits % 8) {
1728 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1729 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1730 unsigned Alignment = ST->getAlignment();
1731 if (Alignment >= ABIAlignment) {
1735 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1736 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1737 LD->getAlignment() == Alignment &&
1738 !LD->isVolatile() && !LD->isIndexed() &&
1739 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1740 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1742 DAG.getConstant(StoreBits/8, MVT::i32),
1743 Alignment, false, ST->getPointerInfo(),
1744 LD->getPointerInfo());
1753 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1756 const SelectionDAG &DAG,
1757 unsigned Depth) const {
1758 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1759 switch (Op.getOpcode()) {
1761 case XCoreISD::LADD:
1762 case XCoreISD::LSUB:
1763 if (Op.getResNo() == 1) {
1764 // Top bits of carry / borrow are clear.
1765 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1766 KnownZero.getBitWidth() - 1);
1772 //===----------------------------------------------------------------------===//
1773 // Addressing mode description hooks
1774 //===----------------------------------------------------------------------===//
1776 static inline bool isImmUs(int64_t val)
1778 return (val >= 0 && val <= 11);
1781 static inline bool isImmUs2(int64_t val)
1783 return (val%2 == 0 && isImmUs(val/2));
1786 static inline bool isImmUs4(int64_t val)
1788 return (val%4 == 0 && isImmUs(val/4));
1791 /// isLegalAddressingMode - Return true if the addressing mode represented
1792 /// by AM is legal for this target, for a load/store of the specified type.
1794 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1796 if (Ty->getTypeID() == Type::VoidTyID)
1797 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1799 const DataLayout *TD = TM.getDataLayout();
1800 unsigned Size = TD->getTypeAllocSize(Ty);
1802 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1809 if (AM.Scale == 0) {
1810 return isImmUs(AM.BaseOffs);
1813 return AM.Scale == 1 && AM.BaseOffs == 0;
1817 if (AM.Scale == 0) {
1818 return isImmUs2(AM.BaseOffs);
1821 return AM.Scale == 2 && AM.BaseOffs == 0;
1824 if (AM.Scale == 0) {
1825 return isImmUs4(AM.BaseOffs);
1828 return AM.Scale == 4 && AM.BaseOffs == 0;
1832 //===----------------------------------------------------------------------===//
1833 // XCore Inline Assembly Support
1834 //===----------------------------------------------------------------------===//
1836 std::pair<unsigned, const TargetRegisterClass*>
1837 XCoreTargetLowering::
1838 getRegForInlineAsmConstraint(const std::string &Constraint,
1840 if (Constraint.size() == 1) {
1841 switch (Constraint[0]) {
1844 return std::make_pair(0U, &XCore::GRRegsRegClass);
1847 // Use the default implementation in TargetLowering to convert the register
1848 // constraint into a member of a register class.
1849 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);