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/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
43 const char *XCoreTargetLowering::
44 getTargetNodeName(unsigned Opcode) const
48 case XCoreISD::BL : return "XCoreISD::BL";
49 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
50 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
51 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
52 case XCoreISD::STWSP : return "XCoreISD::STWSP";
53 case XCoreISD::RETSP : return "XCoreISD::RETSP";
54 case XCoreISD::LADD : return "XCoreISD::LADD";
55 case XCoreISD::LSUB : return "XCoreISD::LSUB";
56 case XCoreISD::LMUL : return "XCoreISD::LMUL";
57 case XCoreISD::MACCU : return "XCoreISD::MACCU";
58 case XCoreISD::MACCS : return "XCoreISD::MACCS";
59 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
60 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
61 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
62 default : return NULL;
66 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
67 : TargetLowering(XTM, new XCoreTargetObjectFile()),
69 Subtarget(*XTM.getSubtargetImpl()) {
71 // Set up the register classes.
72 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
74 // Compute derived properties from the register classes
75 computeRegisterProperties();
77 // Division is expensive
78 setIntDivIsCheap(false);
80 setStackPointerRegisterToSaveRestore(XCore::SP);
82 setSchedulingPreference(Sched::Source);
84 // Use i32 for setcc operations results (slt, sgt, ...).
85 setBooleanContents(ZeroOrOneBooleanContent);
86 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
88 // XCore does not have the NodeTypes below.
89 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
90 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 setOperationAction(ISD::ADDC, MVT::i32, Expand);
92 setOperationAction(ISD::ADDE, MVT::i32, Expand);
93 setOperationAction(ISD::SUBC, MVT::i32, Expand);
94 setOperationAction(ISD::SUBE, MVT::i32, Expand);
96 // Stop the combiner recombining select and set_cc
97 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
100 setOperationAction(ISD::ADD, MVT::i64, Custom);
101 setOperationAction(ISD::SUB, MVT::i64, Custom);
102 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
103 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
104 setOperationAction(ISD::MULHS, MVT::i32, Expand);
105 setOperationAction(ISD::MULHU, MVT::i32, Expand);
106 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
112 setOperationAction(ISD::ROTL , MVT::i32, Expand);
113 setOperationAction(ISD::ROTR , MVT::i32, Expand);
114 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
115 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
117 setOperationAction(ISD::TRAP, MVT::Other, Legal);
120 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
122 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
123 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
125 // Conversion of i64 -> double produces constantpool nodes
126 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
129 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
130 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
131 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
134 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
136 // Custom expand misaligned loads / stores.
137 setOperationAction(ISD::LOAD, MVT::i32, Custom);
138 setOperationAction(ISD::STORE, MVT::i32, Custom);
141 setOperationAction(ISD::VAEND, MVT::Other, Expand);
142 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
143 setOperationAction(ISD::VAARG, MVT::Other, Custom);
144 setOperationAction(ISD::VASTART, MVT::Other, Custom);
147 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
148 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
149 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
151 // TRAMPOLINE is custom lowered.
152 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
153 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
155 // We want to custom lower some of our intrinsics.
156 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
158 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
159 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
160 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
162 // We have target-specific dag combine patterns for the following nodes:
163 setTargetDAGCombine(ISD::STORE);
164 setTargetDAGCombine(ISD::ADD);
166 setMinFunctionAlignment(1);
169 SDValue XCoreTargetLowering::
170 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
171 switch (Op.getOpcode())
173 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
174 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
175 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
176 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
177 case ISD::LOAD: return LowerLOAD(Op, DAG);
178 case ISD::STORE: return LowerSTORE(Op, DAG);
179 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
180 case ISD::VAARG: return LowerVAARG(Op, DAG);
181 case ISD::VASTART: return LowerVASTART(Op, DAG);
182 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
183 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
184 // FIXME: Remove these when LegalizeDAGTypes lands.
186 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
187 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
188 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
189 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
190 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
192 llvm_unreachable("unimplemented operand");
196 /// ReplaceNodeResults - Replace the results of node with an illegal result
197 /// type with new values built out of custom code.
198 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
199 SmallVectorImpl<SDValue>&Results,
200 SelectionDAG &DAG) const {
201 switch (N->getOpcode()) {
203 llvm_unreachable("Don't know how to custom expand this!");
206 Results.push_back(ExpandADDSUB(N, DAG));
211 //===----------------------------------------------------------------------===//
212 // Misc Lower Operation implementation
213 //===----------------------------------------------------------------------===//
215 SDValue XCoreTargetLowering::
216 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
219 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
220 Op.getOperand(3), Op.getOperand(4));
221 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
225 SDValue XCoreTargetLowering::
226 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
227 SelectionDAG &DAG) const
229 // FIXME there is no actual debug info here
231 const GlobalValue *UnderlyingGV = GV;
232 // If GV is an alias then use the aliasee to determine the wrapper type
233 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
234 UnderlyingGV = GA->resolveAliasedGlobal();
235 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
236 if (GVar->isConstant())
237 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
238 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
240 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
243 SDValue XCoreTargetLowering::
244 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
247 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
248 const GlobalValue *GV = GN->getGlobal();
249 int64_t Offset = GN->getOffset();
250 // We can only fold positive offsets that are a multiple of the word size.
251 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
252 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
253 GA = getGlobalAddressWrapper(GA, GV, DAG);
254 // Handle the rest of the offset.
255 if (Offset != FoldedOffset) {
256 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
257 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
262 SDValue XCoreTargetLowering::
263 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
267 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
268 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
270 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
273 SDValue XCoreTargetLowering::
274 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
276 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
277 // FIXME there isn't really debug info here
279 EVT PtrVT = Op.getValueType();
281 if (CP->isMachineConstantPoolEntry()) {
282 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
285 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
288 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
291 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
292 return MachineJumpTableInfo::EK_Inline;
295 SDValue XCoreTargetLowering::
296 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
298 SDValue Chain = Op.getOperand(0);
299 SDValue Table = Op.getOperand(1);
300 SDValue Index = Op.getOperand(2);
302 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
303 unsigned JTI = JT->getIndex();
304 MachineFunction &MF = DAG.getMachineFunction();
305 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
306 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
308 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
309 if (NumEntries <= 32) {
310 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
312 assert((NumEntries >> 31) == 0);
313 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
314 DAG.getConstant(1, MVT::i32));
315 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
319 SDValue XCoreTargetLowering::
320 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
321 int64_t Offset, SelectionDAG &DAG) const
323 if ((Offset & 0x3) == 0) {
324 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
325 false, false, false, 0);
327 // Lower to pair of consecutive word aligned loads plus some bit shifting.
328 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
329 int32_t LowOffset = HighOffset - 4;
330 SDValue LowAddr, HighAddr;
331 if (GlobalAddressSDNode *GASD =
332 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
333 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
335 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
338 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
339 DAG.getConstant(LowOffset, MVT::i32));
340 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
341 DAG.getConstant(HighOffset, MVT::i32));
343 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
344 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
346 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
347 LowAddr, MachinePointerInfo(),
348 false, false, false, 0);
349 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
350 HighAddr, MachinePointerInfo(),
351 false, false, false, 0);
352 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
353 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
354 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
355 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
357 SDValue Ops[] = { Result, Chain };
358 return DAG.getMergeValues(Ops, 2, DL);
361 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
363 APInt KnownZero, KnownOne;
364 DAG.ComputeMaskedBits(Value, KnownZero, KnownOne);
365 return KnownZero.countTrailingOnes() >= 2;
368 SDValue XCoreTargetLowering::
369 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
370 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
371 LoadSDNode *LD = cast<LoadSDNode>(Op);
372 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
373 "Unexpected extension type");
374 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
375 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
378 unsigned ABIAlignment = getDataLayout()->
379 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
380 // Leave aligned load alone.
381 if (LD->getAlignment() >= ABIAlignment)
384 SDValue Chain = LD->getChain();
385 SDValue BasePtr = LD->getBasePtr();
388 if (!LD->isVolatile()) {
389 const GlobalValue *GV;
391 if (DAG.isBaseWithConstantOffset(BasePtr) &&
392 isWordAligned(BasePtr->getOperand(0), DAG)) {
393 SDValue NewBasePtr = BasePtr->getOperand(0);
394 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
395 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
398 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
399 MinAlign(GV->getAlignment(), 4) == 4) {
400 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
401 BasePtr->getValueType(0));
402 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
407 if (LD->getAlignment() == 2) {
408 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
409 BasePtr, LD->getPointerInfo(), MVT::i16,
410 LD->isVolatile(), LD->isNonTemporal(), 2);
411 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
412 DAG.getConstant(2, MVT::i32));
413 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
415 LD->getPointerInfo().getWithOffset(2),
416 MVT::i16, LD->isVolatile(),
417 LD->isNonTemporal(), 2);
418 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
419 DAG.getConstant(16, MVT::i32));
420 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, 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 // Lower to a call to __misaligned_load(BasePtr).
428 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
429 TargetLowering::ArgListTy Args;
430 TargetLowering::ArgListEntry Entry;
433 Entry.Node = BasePtr;
434 Args.push_back(Entry);
436 TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
437 false, false, 0, CallingConv::C, /*isTailCall=*/false,
438 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
439 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
441 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
444 { CallResult.first, CallResult.second };
446 return DAG.getMergeValues(Ops, 2, DL);
449 SDValue XCoreTargetLowering::
450 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
452 StoreSDNode *ST = cast<StoreSDNode>(Op);
453 assert(!ST->isTruncatingStore() && "Unexpected store type");
454 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
455 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
458 unsigned ABIAlignment = getDataLayout()->
459 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
460 // Leave aligned store alone.
461 if (ST->getAlignment() >= ABIAlignment) {
464 SDValue Chain = ST->getChain();
465 SDValue BasePtr = ST->getBasePtr();
466 SDValue Value = ST->getValue();
469 if (ST->getAlignment() == 2) {
471 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
472 DAG.getConstant(16, MVT::i32));
473 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
474 ST->getPointerInfo(), MVT::i16,
475 ST->isVolatile(), ST->isNonTemporal(),
477 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
478 DAG.getConstant(2, MVT::i32));
479 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
480 ST->getPointerInfo().getWithOffset(2),
481 MVT::i16, ST->isVolatile(),
482 ST->isNonTemporal(), 2);
483 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
486 // Lower to a call to __misaligned_store(BasePtr, Value).
487 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
488 TargetLowering::ArgListTy Args;
489 TargetLowering::ArgListEntry Entry;
492 Entry.Node = BasePtr;
493 Args.push_back(Entry);
496 Args.push_back(Entry);
498 TargetLowering::CallLoweringInfo CLI(Chain,
499 Type::getVoidTy(*DAG.getContext()), false, false,
500 false, false, 0, CallingConv::C, /*isTailCall=*/false,
501 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
502 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
504 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
506 return CallResult.second;
509 SDValue XCoreTargetLowering::
510 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
512 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
513 "Unexpected operand to lower!");
515 SDValue LHS = Op.getOperand(0);
516 SDValue RHS = Op.getOperand(1);
517 SDValue Zero = DAG.getConstant(0, MVT::i32);
518 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
519 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
521 SDValue Lo(Hi.getNode(), 1);
522 SDValue Ops[] = { Lo, Hi };
523 return DAG.getMergeValues(Ops, 2, dl);
526 SDValue XCoreTargetLowering::
527 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
529 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
530 "Unexpected operand to lower!");
532 SDValue LHS = Op.getOperand(0);
533 SDValue RHS = Op.getOperand(1);
534 SDValue Zero = DAG.getConstant(0, MVT::i32);
535 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
536 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
538 SDValue Lo(Hi.getNode(), 1);
539 SDValue Ops[] = { Lo, Hi };
540 return DAG.getMergeValues(Ops, 2, dl);
543 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
544 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
545 /// each intermediate result in the calculation must also have a single use.
546 /// If the Op is in the correct form the constituent parts are written to Mul0,
547 /// Mul1, Addend0 and Addend1.
549 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
550 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
552 if (Op.getOpcode() != ISD::ADD)
554 SDValue N0 = Op.getOperand(0);
555 SDValue N1 = Op.getOperand(1);
558 if (N0.getOpcode() == ISD::ADD) {
561 } else if (N1.getOpcode() == ISD::ADD) {
567 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
569 if (OtherOp.getOpcode() == ISD::MUL) {
570 // add(add(a,b),mul(x,y))
571 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
573 Mul0 = OtherOp.getOperand(0);
574 Mul1 = OtherOp.getOperand(1);
575 Addend0 = AddOp.getOperand(0);
576 Addend1 = AddOp.getOperand(1);
579 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
580 // add(add(mul(x,y),a),b)
581 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
583 Mul0 = AddOp.getOperand(0).getOperand(0);
584 Mul1 = AddOp.getOperand(0).getOperand(1);
585 Addend0 = AddOp.getOperand(1);
589 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
590 // add(add(a,mul(x,y)),b)
591 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
593 Mul0 = AddOp.getOperand(1).getOperand(0);
594 Mul1 = AddOp.getOperand(1).getOperand(1);
595 Addend0 = AddOp.getOperand(0);
602 SDValue XCoreTargetLowering::
603 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
607 if (N->getOperand(0).getOpcode() == ISD::MUL) {
608 Mul = N->getOperand(0);
609 Other = N->getOperand(1);
610 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
611 Mul = N->getOperand(1);
612 Other = N->getOperand(0);
617 SDValue LL, RL, AddendL, AddendH;
618 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
619 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
620 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
621 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
622 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
623 Other, DAG.getConstant(0, MVT::i32));
624 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
625 Other, DAG.getConstant(1, MVT::i32));
626 APInt HighMask = APInt::getHighBitsSet(64, 32);
627 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
628 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
629 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
630 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
631 // The inputs are both zero-extended.
632 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
633 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
635 SDValue Lo(Hi.getNode(), 1);
636 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
638 if (LHSSB > 32 && RHSSB > 32) {
639 // The inputs are both sign-extended.
640 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
641 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
643 SDValue Lo(Hi.getNode(), 1);
644 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
647 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
648 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
649 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
650 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
651 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
652 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
654 SDValue Lo(Hi.getNode(), 1);
655 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
656 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
657 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
658 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
659 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
662 SDValue XCoreTargetLowering::
663 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
665 assert(N->getValueType(0) == MVT::i64 &&
666 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
667 "Unknown operand to lower!");
669 if (N->getOpcode() == ISD::ADD) {
670 SDValue Result = TryExpandADDWithMul(N, DAG);
671 if (Result.getNode() != 0)
677 // Extract components
678 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
679 N->getOperand(0), DAG.getConstant(0, MVT::i32));
680 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
681 N->getOperand(0), DAG.getConstant(1, MVT::i32));
682 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
683 N->getOperand(1), DAG.getConstant(0, MVT::i32));
684 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685 N->getOperand(1), DAG.getConstant(1, MVT::i32));
688 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
690 SDValue Zero = DAG.getConstant(0, MVT::i32);
691 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
693 SDValue Carry(Lo.getNode(), 1);
695 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
697 SDValue Ignored(Hi.getNode(), 1);
699 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
702 SDValue XCoreTargetLowering::
703 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
705 // Whist llvm does not support aggregate varargs we can ignore
706 // the possibility of the ValueType being an implicit byVal vararg.
707 SDNode *Node = Op.getNode();
708 EVT VT = Node->getValueType(0); // not an aggregate
709 SDValue InChain = Node->getOperand(0);
710 SDValue VAListPtr = Node->getOperand(1);
711 EVT PtrVT = VAListPtr.getValueType();
712 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
714 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
715 VAListPtr, MachinePointerInfo(SV),
716 false, false, false, 0);
717 // Increment the pointer, VAList, to the next vararg
718 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
719 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
720 // Store the incremented VAList to the legalized pointer
721 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
722 MachinePointerInfo(SV), false, false, 0);
723 // Load the actual argument out of the pointer VAList
724 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
725 false, false, false, 0);
728 SDValue XCoreTargetLowering::
729 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
732 // vastart stores the address of the VarArgsFrameIndex slot into the
733 // memory location argument
734 MachineFunction &MF = DAG.getMachineFunction();
735 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
736 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
737 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
738 MachinePointerInfo(), false, false, 0);
741 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
742 SelectionDAG &DAG) const {
744 // Depths > 0 not supported yet!
745 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
748 MachineFunction &MF = DAG.getMachineFunction();
749 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
750 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
751 RegInfo->getFrameRegister(MF), MVT::i32);
754 SDValue XCoreTargetLowering::
755 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
756 return Op.getOperand(0);
759 SDValue XCoreTargetLowering::
760 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
761 SDValue Chain = Op.getOperand(0);
762 SDValue Trmp = Op.getOperand(1); // trampoline
763 SDValue FPtr = Op.getOperand(2); // nested function
764 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
766 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
769 // LDAPF_u10 r11, nest
770 // LDW_2rus r11, r11[0]
771 // STWSP_ru6 r11, sp[0]
772 // LDAPF_u10 r11, fptr
773 // LDW_2rus r11, r11[0]
779 SDValue OutChains[5];
784 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
785 Addr, MachinePointerInfo(TrmpAddr), false, false,
788 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
789 DAG.getConstant(4, MVT::i32));
790 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
791 Addr, MachinePointerInfo(TrmpAddr, 4), false,
794 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
795 DAG.getConstant(8, MVT::i32));
796 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
797 Addr, MachinePointerInfo(TrmpAddr, 8), false,
800 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
801 DAG.getConstant(12, MVT::i32));
802 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
803 MachinePointerInfo(TrmpAddr, 12), false, false,
806 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
807 DAG.getConstant(16, MVT::i32));
808 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
809 MachinePointerInfo(TrmpAddr, 16), false, false,
812 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
815 SDValue XCoreTargetLowering::
816 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
818 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
820 case Intrinsic::xcore_crc8:
821 EVT VT = Op.getValueType();
823 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
824 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
825 SDValue Crc(Data.getNode(), 1);
826 SDValue Results[] = { Crc, Data };
827 return DAG.getMergeValues(Results, 2, DL);
832 //===----------------------------------------------------------------------===//
833 // Calling Convention Implementation
834 //===----------------------------------------------------------------------===//
836 #include "XCoreGenCallingConv.inc"
838 //===----------------------------------------------------------------------===//
839 // Call Calling Convention Implementation
840 //===----------------------------------------------------------------------===//
842 /// XCore call implementation
844 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
845 SmallVectorImpl<SDValue> &InVals) const {
846 SelectionDAG &DAG = CLI.DAG;
848 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
849 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
850 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
851 SDValue Chain = CLI.Chain;
852 SDValue Callee = CLI.Callee;
853 bool &isTailCall = CLI.IsTailCall;
854 CallingConv::ID CallConv = CLI.CallConv;
855 bool isVarArg = CLI.IsVarArg;
857 // XCore target does not yet support tail call optimization.
860 // For now, only CallingConv::C implemented
864 llvm_unreachable("Unsupported calling convention");
865 case CallingConv::Fast:
867 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
868 Outs, OutVals, Ins, dl, DAG, InVals);
872 /// LowerCCCCallTo - functions arguments are copied from virtual
873 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
874 /// CALLSEQ_END are emitted.
875 /// TODO: isTailCall, sret.
877 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
878 CallingConv::ID CallConv, bool isVarArg,
880 const SmallVectorImpl<ISD::OutputArg> &Outs,
881 const SmallVectorImpl<SDValue> &OutVals,
882 const SmallVectorImpl<ISD::InputArg> &Ins,
883 SDLoc dl, SelectionDAG &DAG,
884 SmallVectorImpl<SDValue> &InVals) const {
886 // Analyze operands of the call, assigning locations to each operand.
887 SmallVector<CCValAssign, 16> ArgLocs;
888 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
889 getTargetMachine(), ArgLocs, *DAG.getContext());
891 // The ABI dictates there should be one stack slot available to the callee
892 // on function entry (for saving lr).
893 CCInfo.AllocateStack(4, 4);
895 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
897 // Get a count of how many bytes are to be pushed on the stack.
898 unsigned NumBytes = CCInfo.getNextStackOffset();
900 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
901 getPointerTy(), true), dl);
903 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
904 SmallVector<SDValue, 12> MemOpChains;
906 // Walk the register/memloc assignments, inserting copies/loads.
907 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
908 CCValAssign &VA = ArgLocs[i];
909 SDValue Arg = OutVals[i];
911 // Promote the value if needed.
912 switch (VA.getLocInfo()) {
913 default: llvm_unreachable("Unknown loc info!");
914 case CCValAssign::Full: break;
915 case CCValAssign::SExt:
916 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
918 case CCValAssign::ZExt:
919 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
921 case CCValAssign::AExt:
922 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
926 // Arguments that can be passed on register must be kept at
929 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
931 assert(VA.isMemLoc());
933 int Offset = VA.getLocMemOffset();
935 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
937 DAG.getConstant(Offset/4, MVT::i32)));
941 // Transform all store nodes into one single node because
942 // all store nodes are independent of each other.
943 if (!MemOpChains.empty())
944 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
945 &MemOpChains[0], MemOpChains.size());
947 // Build a sequence of copy-to-reg nodes chained together with token
948 // chain and flag operands which copy the outgoing args into registers.
949 // The InFlag in necessary since all emitted instructions must be
952 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
953 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
954 RegsToPass[i].second, InFlag);
955 InFlag = Chain.getValue(1);
958 // If the callee is a GlobalAddress node (quite common, every direct call is)
959 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
960 // Likewise ExternalSymbol -> TargetExternalSymbol.
961 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
962 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
963 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
964 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
966 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
967 // = Chain, Callee, Reg#1, Reg#2, ...
969 // Returns a chain & a flag for retval copy to use.
970 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
971 SmallVector<SDValue, 8> Ops;
972 Ops.push_back(Chain);
973 Ops.push_back(Callee);
975 // Add argument registers to the end of the list so that they are
976 // known live into the call.
977 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
978 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
979 RegsToPass[i].second.getValueType()));
981 if (InFlag.getNode())
982 Ops.push_back(InFlag);
984 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
985 InFlag = Chain.getValue(1);
987 // Create the CALLSEQ_END node.
988 Chain = DAG.getCALLSEQ_END(Chain,
989 DAG.getConstant(NumBytes, getPointerTy(), true),
990 DAG.getConstant(0, getPointerTy(), true),
992 InFlag = Chain.getValue(1);
994 // Handle result values, copying them out of physregs into vregs that we
996 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
997 Ins, dl, DAG, InVals);
1000 /// LowerCallResult - Lower the result values of a call into the
1001 /// appropriate copies out of appropriate physical registers.
1003 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1004 CallingConv::ID CallConv, bool isVarArg,
1005 const SmallVectorImpl<ISD::InputArg> &Ins,
1006 SDLoc dl, SelectionDAG &DAG,
1007 SmallVectorImpl<SDValue> &InVals) const {
1009 // Assign locations to each value returned by this call.
1010 SmallVector<CCValAssign, 16> RVLocs;
1011 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1012 getTargetMachine(), RVLocs, *DAG.getContext());
1014 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1016 // Copy all of the result registers out of their specified physreg.
1017 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1018 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1019 RVLocs[i].getValVT(), InFlag).getValue(1);
1020 InFlag = Chain.getValue(2);
1021 InVals.push_back(Chain.getValue(0));
1027 //===----------------------------------------------------------------------===//
1028 // Formal Arguments Calling Convention Implementation
1029 //===----------------------------------------------------------------------===//
1032 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1035 /// XCore formal arguments implementation
1037 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1038 CallingConv::ID CallConv,
1040 const SmallVectorImpl<ISD::InputArg> &Ins,
1043 SmallVectorImpl<SDValue> &InVals)
1048 llvm_unreachable("Unsupported calling convention");
1049 case CallingConv::C:
1050 case CallingConv::Fast:
1051 return LowerCCCArguments(Chain, CallConv, isVarArg,
1052 Ins, dl, DAG, InVals);
1056 /// LowerCCCArguments - transform physical registers into
1057 /// virtual registers and generate load operations for
1058 /// arguments places on the stack.
1061 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1062 CallingConv::ID CallConv,
1064 const SmallVectorImpl<ISD::InputArg>
1068 SmallVectorImpl<SDValue> &InVals) const {
1069 MachineFunction &MF = DAG.getMachineFunction();
1070 MachineFrameInfo *MFI = MF.getFrameInfo();
1071 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1073 // Assign locations to all of the incoming arguments.
1074 SmallVector<CCValAssign, 16> ArgLocs;
1075 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1076 getTargetMachine(), ArgLocs, *DAG.getContext());
1078 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1080 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1082 unsigned LRSaveSize = StackSlotSize;
1084 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1085 // scheduler clobbering a register before it has been copied.
1087 // 1. CopyFromReg (and load) arg & vararg registers.
1088 // 2. Chain CopyFromReg nodes into a TokenFactor.
1089 // 3. Memcpy 'byVal' args & push final InVals.
1090 // 4. Chain mem ops nodes into a TokenFactor.
1091 SmallVector<SDValue, 4> CFRegNode;
1092 SmallVector<ArgDataPair, 4> ArgData;
1093 SmallVector<SDValue, 4> MemOps;
1095 // 1a. CopyFromReg (and load) arg registers.
1096 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1098 CCValAssign &VA = ArgLocs[i];
1101 if (VA.isRegLoc()) {
1102 // Arguments passed in registers
1103 EVT RegVT = VA.getLocVT();
1104 switch (RegVT.getSimpleVT().SimpleTy) {
1108 errs() << "LowerFormalArguments Unhandled argument type: "
1109 << RegVT.getSimpleVT().SimpleTy << "\n";
1111 llvm_unreachable(0);
1114 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1115 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1116 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1117 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1121 assert(VA.isMemLoc());
1122 // Load the argument to a virtual register
1123 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1124 if (ObjSize > StackSlotSize) {
1125 errs() << "LowerFormalArguments Unhandled argument type: "
1126 << EVT(VA.getLocVT()).getEVTString()
1129 // Create the frame index object for this incoming parameter...
1130 int FI = MFI->CreateFixedObject(ObjSize,
1131 LRSaveSize + VA.getLocMemOffset(),
1134 // Create the SelectionDAG nodes corresponding to a load
1135 //from this parameter
1136 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1137 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1138 MachinePointerInfo::getFixedStack(FI),
1139 false, false, false, 0);
1141 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1142 ArgData.push_back(ADP);
1145 // 1b. CopyFromReg vararg registers.
1147 // Argument registers
1148 static const uint16_t ArgRegs[] = {
1149 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1151 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1152 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1153 array_lengthof(ArgRegs));
1154 if (FirstVAReg < array_lengthof(ArgRegs)) {
1156 // Save remaining registers, storing higher register numbers at a higher
1158 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1159 // Create a stack slot
1160 int FI = MFI->CreateFixedObject(4, offset, true);
1161 if (i == (int)FirstVAReg) {
1162 XFI->setVarArgsFrameIndex(FI);
1164 offset -= StackSlotSize;
1165 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1166 // Move argument from phys reg -> virt reg
1167 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1168 RegInfo.addLiveIn(ArgRegs[i], VReg);
1169 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1170 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1171 // Move argument from virt reg -> stack
1172 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1173 MachinePointerInfo(), false, false, 0);
1174 MemOps.push_back(Store);
1177 // This will point to the next argument passed via stack.
1178 XFI->setVarArgsFrameIndex(
1179 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1184 // 2. chain CopyFromReg nodes into a TokenFactor.
1185 if (!CFRegNode.empty())
1186 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &CFRegNode[0],
1189 // 3. Memcpy 'byVal' args & push final InVals.
1190 // Aggregates passed "byVal" need to be copied by the callee.
1191 // The callee will use a pointer to this copy, rather than the original
1193 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1194 ArgDE = ArgData.end();
1195 ArgDI != ArgDE; ++ArgDI) {
1196 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1197 unsigned Size = ArgDI->Flags.getByValSize();
1198 unsigned Align = ArgDI->Flags.getByValAlign();
1199 // Create a new object on the stack and copy the pointee into it.
1200 int FI = MFI->CreateStackObject(Size, Align, false, false);
1201 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1202 InVals.push_back(FIN);
1203 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1204 DAG.getConstant(Size, MVT::i32),
1205 Align, false, false,
1206 MachinePointerInfo(),
1207 MachinePointerInfo()));
1209 InVals.push_back(ArgDI->SDV);
1213 // 4, chain mem ops nodes into a TokenFactor.
1214 if (!MemOps.empty()) {
1215 MemOps.push_back(Chain);
1216 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
1223 //===----------------------------------------------------------------------===//
1224 // Return Value Calling Convention Implementation
1225 //===----------------------------------------------------------------------===//
1227 bool XCoreTargetLowering::
1228 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1230 const SmallVectorImpl<ISD::OutputArg> &Outs,
1231 LLVMContext &Context) const {
1232 SmallVector<CCValAssign, 16> RVLocs;
1233 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1234 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1238 XCoreTargetLowering::LowerReturn(SDValue Chain,
1239 CallingConv::ID CallConv, bool isVarArg,
1240 const SmallVectorImpl<ISD::OutputArg> &Outs,
1241 const SmallVectorImpl<SDValue> &OutVals,
1242 SDLoc dl, SelectionDAG &DAG) const {
1244 // CCValAssign - represent the assignment of
1245 // the return value to a location
1246 SmallVector<CCValAssign, 16> RVLocs;
1248 // CCState - Info about the registers and stack slot.
1249 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1250 getTargetMachine(), RVLocs, *DAG.getContext());
1252 // Analyze return values.
1253 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1256 SmallVector<SDValue, 4> RetOps(1, Chain);
1258 // Return on XCore is always a "retsp 0"
1259 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1261 // Copy the result values into the output registers.
1262 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1263 CCValAssign &VA = RVLocs[i];
1264 assert(VA.isRegLoc() && "Can only return in registers!");
1266 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1269 // guarantee that all emitted copies are
1270 // stuck together, avoiding something bad
1271 Flag = Chain.getValue(1);
1272 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1275 RetOps[0] = Chain; // Update chain.
1277 // Add the flag if we have it.
1279 RetOps.push_back(Flag);
1281 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1282 &RetOps[0], RetOps.size());
1285 //===----------------------------------------------------------------------===//
1286 // Other Lowering Code
1287 //===----------------------------------------------------------------------===//
1290 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1291 MachineBasicBlock *BB) const {
1292 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1293 DebugLoc dl = MI->getDebugLoc();
1294 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1295 "Unexpected instr type to insert");
1297 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1298 // control-flow pattern. The incoming instruction knows the destination vreg
1299 // to set, the condition code register to branch on, the true/false values to
1300 // select between, and a branch opcode to use.
1301 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1302 MachineFunction::iterator It = BB;
1308 // cmpTY ccX, r1, r2
1310 // fallthrough --> copy0MBB
1311 MachineBasicBlock *thisMBB = BB;
1312 MachineFunction *F = BB->getParent();
1313 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1314 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1315 F->insert(It, copy0MBB);
1316 F->insert(It, sinkMBB);
1318 // Transfer the remainder of BB and its successor edges to sinkMBB.
1319 sinkMBB->splice(sinkMBB->begin(), BB,
1320 llvm::next(MachineBasicBlock::iterator(MI)),
1322 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1324 // Next, add the true and fallthrough blocks as its successors.
1325 BB->addSuccessor(copy0MBB);
1326 BB->addSuccessor(sinkMBB);
1328 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1329 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1332 // %FalseValue = ...
1333 // # fallthrough to sinkMBB
1336 // Update machine-CFG edges
1337 BB->addSuccessor(sinkMBB);
1340 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1343 BuildMI(*BB, BB->begin(), dl,
1344 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1345 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1346 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1348 MI->eraseFromParent(); // The pseudo instruction is gone now.
1352 //===----------------------------------------------------------------------===//
1353 // Target Optimization Hooks
1354 //===----------------------------------------------------------------------===//
1356 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1357 DAGCombinerInfo &DCI) const {
1358 SelectionDAG &DAG = DCI.DAG;
1360 switch (N->getOpcode()) {
1362 case XCoreISD::LADD: {
1363 SDValue N0 = N->getOperand(0);
1364 SDValue N1 = N->getOperand(1);
1365 SDValue N2 = N->getOperand(2);
1366 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1368 EVT VT = N0.getValueType();
1370 // canonicalize constant to RHS
1372 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1374 // fold (ladd 0, 0, x) -> 0, x & 1
1375 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1376 SDValue Carry = DAG.getConstant(0, VT);
1377 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1378 DAG.getConstant(1, VT));
1379 SDValue Ops[] = { Result, Carry };
1380 return DAG.getMergeValues(Ops, 2, dl);
1383 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1385 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1386 APInt KnownZero, KnownOne;
1387 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1388 VT.getSizeInBits() - 1);
1389 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1390 if ((KnownZero & Mask) == Mask) {
1391 SDValue Carry = DAG.getConstant(0, VT);
1392 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1393 SDValue Ops[] = { Result, Carry };
1394 return DAG.getMergeValues(Ops, 2, dl);
1399 case XCoreISD::LSUB: {
1400 SDValue N0 = N->getOperand(0);
1401 SDValue N1 = N->getOperand(1);
1402 SDValue N2 = N->getOperand(2);
1403 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1404 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1405 EVT VT = N0.getValueType();
1407 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1408 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1409 APInt KnownZero, KnownOne;
1410 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1411 VT.getSizeInBits() - 1);
1412 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1413 if ((KnownZero & Mask) == Mask) {
1414 SDValue Borrow = N2;
1415 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1416 DAG.getConstant(0, VT), N2);
1417 SDValue Ops[] = { Result, Borrow };
1418 return DAG.getMergeValues(Ops, 2, dl);
1422 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1424 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1425 APInt KnownZero, KnownOne;
1426 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1427 VT.getSizeInBits() - 1);
1428 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1429 if ((KnownZero & Mask) == Mask) {
1430 SDValue Borrow = DAG.getConstant(0, VT);
1431 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1432 SDValue Ops[] = { Result, Borrow };
1433 return DAG.getMergeValues(Ops, 2, dl);
1438 case XCoreISD::LMUL: {
1439 SDValue N0 = N->getOperand(0);
1440 SDValue N1 = N->getOperand(1);
1441 SDValue N2 = N->getOperand(2);
1442 SDValue N3 = N->getOperand(3);
1443 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1445 EVT VT = N0.getValueType();
1446 // Canonicalize multiplicative constant to RHS. If both multiplicative
1447 // operands are constant canonicalize smallest to RHS.
1448 if ((N0C && !N1C) ||
1449 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1450 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1454 if (N1C && N1C->isNullValue()) {
1455 // If the high result is unused fold to add(a, b)
1456 if (N->hasNUsesOfValue(0, 0)) {
1457 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1458 SDValue Ops[] = { Lo, Lo };
1459 return DAG.getMergeValues(Ops, 2, dl);
1461 // Otherwise fold to ladd(a, b, 0)
1463 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1464 SDValue Carry(Result.getNode(), 1);
1465 SDValue Ops[] = { Carry, Result };
1466 return DAG.getMergeValues(Ops, 2, dl);
1471 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1472 // lmul(x, y, a, b). The high result of lmul will be ignored.
1473 // This is only profitable if the intermediate results are unused
1475 SDValue Mul0, Mul1, Addend0, Addend1;
1476 if (N->getValueType(0) == MVT::i32 &&
1477 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1478 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1479 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1480 Mul1, Addend0, Addend1);
1481 SDValue Result(Ignored.getNode(), 1);
1484 APInt HighMask = APInt::getHighBitsSet(64, 32);
1485 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1486 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1487 // before type legalization as it is messy to match the operands after
1489 if (N->getValueType(0) == MVT::i64 &&
1490 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1491 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1492 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1493 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1494 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1495 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1496 Mul0, DAG.getConstant(0, MVT::i32));
1497 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1498 Mul1, DAG.getConstant(0, MVT::i32));
1499 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1500 Addend0, DAG.getConstant(0, MVT::i32));
1501 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1502 Addend1, DAG.getConstant(0, MVT::i32));
1503 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1504 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1505 Addend0L, Addend1L);
1506 SDValue Lo(Hi.getNode(), 1);
1507 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1512 // Replace unaligned store of unaligned load with memmove.
1513 StoreSDNode *ST = cast<StoreSDNode>(N);
1514 if (!DCI.isBeforeLegalize() ||
1515 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1516 ST->isVolatile() || ST->isIndexed()) {
1519 SDValue Chain = ST->getChain();
1521 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1522 if (StoreBits % 8) {
1525 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1526 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1527 unsigned Alignment = ST->getAlignment();
1528 if (Alignment >= ABIAlignment) {
1532 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1533 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1534 LD->getAlignment() == Alignment &&
1535 !LD->isVolatile() && !LD->isIndexed() &&
1536 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1537 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1539 DAG.getConstant(StoreBits/8, MVT::i32),
1540 Alignment, false, ST->getPointerInfo(),
1541 LD->getPointerInfo());
1550 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1553 const SelectionDAG &DAG,
1554 unsigned Depth) const {
1555 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1556 switch (Op.getOpcode()) {
1558 case XCoreISD::LADD:
1559 case XCoreISD::LSUB:
1560 if (Op.getResNo() == 1) {
1561 // Top bits of carry / borrow are clear.
1562 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1563 KnownZero.getBitWidth() - 1);
1569 //===----------------------------------------------------------------------===//
1570 // Addressing mode description hooks
1571 //===----------------------------------------------------------------------===//
1573 static inline bool isImmUs(int64_t val)
1575 return (val >= 0 && val <= 11);
1578 static inline bool isImmUs2(int64_t val)
1580 return (val%2 == 0 && isImmUs(val/2));
1583 static inline bool isImmUs4(int64_t val)
1585 return (val%4 == 0 && isImmUs(val/4));
1588 /// isLegalAddressingMode - Return true if the addressing mode represented
1589 /// by AM is legal for this target, for a load/store of the specified type.
1591 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1593 if (Ty->getTypeID() == Type::VoidTyID)
1594 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1596 const DataLayout *TD = TM.getDataLayout();
1597 unsigned Size = TD->getTypeAllocSize(Ty);
1599 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1606 if (AM.Scale == 0) {
1607 return isImmUs(AM.BaseOffs);
1610 return AM.Scale == 1 && AM.BaseOffs == 0;
1614 if (AM.Scale == 0) {
1615 return isImmUs2(AM.BaseOffs);
1618 return AM.Scale == 2 && AM.BaseOffs == 0;
1621 if (AM.Scale == 0) {
1622 return isImmUs4(AM.BaseOffs);
1625 return AM.Scale == 4 && AM.BaseOffs == 0;
1629 //===----------------------------------------------------------------------===//
1630 // XCore Inline Assembly Support
1631 //===----------------------------------------------------------------------===//
1633 std::pair<unsigned, const TargetRegisterClass*>
1634 XCoreTargetLowering::
1635 getRegForInlineAsmConstraint(const std::string &Constraint,
1637 if (Constraint.size() == 1) {
1638 switch (Constraint[0]) {
1641 return std::make_pair(0U, &XCore::GRRegsRegClass);
1644 // Use the default implementation in TargetLowering to convert the register
1645 // constraint into a member of a register class.
1646 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);