1 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation ---------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the XCoreTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "xcore-lower"
16 #include "XCoreISelLowering.h"
17 #include "XCore.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"
40 #include <algorithm>
42 using namespace llvm;
44 const char *XCoreTargetLowering::
45 getTargetNodeName(unsigned Opcode) const
46 {
47 switch (Opcode)
48 {
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::MEMBARRIER : return "XCoreISD::MEMBARRIER";
64 default : return NULL;
65 }
66 }
68 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
69 : TargetLowering(XTM, new XCoreTargetObjectFile()),
70 TM(XTM),
71 Subtarget(*XTM.getSubtargetImpl()) {
73 // Set up the register classes.
74 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
76 // Compute derived properties from the register classes
77 computeRegisterProperties();
79 // Division is expensive
80 setIntDivIsCheap(false);
82 setStackPointerRegisterToSaveRestore(XCore::SP);
84 setSchedulingPreference(Sched::Source);
86 // Use i32 for setcc operations results (slt, sgt, ...).
87 setBooleanContents(ZeroOrOneBooleanContent);
88 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
90 // XCore does not have the NodeTypes below.
91 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
92 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
93 setOperationAction(ISD::ADDC, MVT::i32, Expand);
94 setOperationAction(ISD::ADDE, MVT::i32, Expand);
95 setOperationAction(ISD::SUBC, MVT::i32, Expand);
96 setOperationAction(ISD::SUBE, MVT::i32, Expand);
98 // Stop the combiner recombining select and set_cc
99 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
101 // 64bit
102 setOperationAction(ISD::ADD, MVT::i64, Custom);
103 setOperationAction(ISD::SUB, MVT::i64, Custom);
104 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
105 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
106 setOperationAction(ISD::MULHS, MVT::i32, Expand);
107 setOperationAction(ISD::MULHU, MVT::i32, Expand);
108 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
112 // Bit Manipulation
113 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
114 setOperationAction(ISD::ROTL , MVT::i32, Expand);
115 setOperationAction(ISD::ROTR , MVT::i32, Expand);
116 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
117 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::TRAP, MVT::Other, Legal);
121 // Jump tables.
122 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
124 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
125 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
127 // Conversion of i64 -> double produces constantpool nodes
128 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
130 // Loads
131 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
132 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
136 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
138 // Custom expand misaligned loads / stores.
139 setOperationAction(ISD::LOAD, MVT::i32, Custom);
140 setOperationAction(ISD::STORE, MVT::i32, Custom);
142 // Varargs
143 setOperationAction(ISD::VAEND, MVT::Other, Expand);
144 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
145 setOperationAction(ISD::VAARG, MVT::Other, Custom);
146 setOperationAction(ISD::VASTART, MVT::Other, Custom);
148 // Dynamic stack
149 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
150 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
151 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
153 // Exception handling
154 setExceptionPointerRegister(XCore::R0);
155 setExceptionSelectorRegister(XCore::R1);
157 // Atomic operations
158 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
160 // TRAMPOLINE is custom lowered.
161 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
162 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
164 // We want to custom lower some of our intrinsics.
165 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
167 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
168 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
169 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
171 // We have target-specific dag combine patterns for the following nodes:
172 setTargetDAGCombine(ISD::STORE);
173 setTargetDAGCombine(ISD::ADD);
175 setMinFunctionAlignment(1);
176 }
178 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
179 if (Val.getOpcode() != ISD::LOAD)
180 return false;
182 EVT VT1 = Val.getValueType();
183 if (!VT1.isSimple() || !VT1.isInteger() ||
184 !VT2.isSimple() || !VT2.isInteger())
185 return false;
187 switch (VT1.getSimpleVT().SimpleTy) {
188 default: break;
189 case MVT::i8:
190 return true;
191 }
193 return false;
194 }
196 SDValue XCoreTargetLowering::
197 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
198 switch (Op.getOpcode())
199 {
200 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
201 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
202 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
203 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
204 case ISD::LOAD: return LowerLOAD(Op, DAG);
205 case ISD::STORE: return LowerSTORE(Op, DAG);
206 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
207 case ISD::VAARG: return LowerVAARG(Op, DAG);
208 case ISD::VASTART: return LowerVASTART(Op, DAG);
209 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
210 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
211 // FIXME: Remove these when LegalizeDAGTypes lands.
212 case ISD::ADD:
213 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
214 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
215 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
216 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
217 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
218 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
219 default:
220 llvm_unreachable("unimplemented operand");
221 }
222 }
224 /// ReplaceNodeResults - Replace the results of node with an illegal result
225 /// type with new values built out of custom code.
226 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
227 SmallVectorImpl<SDValue>&Results,
228 SelectionDAG &DAG) const {
229 switch (N->getOpcode()) {
230 default:
231 llvm_unreachable("Don't know how to custom expand this!");
232 case ISD::ADD:
233 case ISD::SUB:
234 Results.push_back(ExpandADDSUB(N, DAG));
235 return;
236 }
237 }
239 //===----------------------------------------------------------------------===//
240 // Misc Lower Operation implementation
241 //===----------------------------------------------------------------------===//
243 SDValue XCoreTargetLowering::
244 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
245 {
246 SDLoc dl(Op);
247 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
248 Op.getOperand(3), Op.getOperand(4));
249 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
250 Op.getOperand(1));
251 }
253 SDValue XCoreTargetLowering::
254 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
255 SelectionDAG &DAG) const
256 {
257 // FIXME there is no actual debug info here
258 SDLoc dl(GA);
259 const GlobalValue *UnderlyingGV = GV;
260 // If GV is an alias then use the aliasee to determine the wrapper type
261 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
262 UnderlyingGV = GA->resolveAliasedGlobal();
263 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
264 if (GVar->isConstant())
265 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
266 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
267 }
268 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
269 }
271 SDValue XCoreTargetLowering::
272 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
273 {
274 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
275 const GlobalValue *GV = GN->getGlobal();
276 SDLoc DL(GN);
277 int64_t Offset = GN->getOffset();
278 Type *ObjType = GV->getType()->getPointerElementType();
279 if (getTargetMachine().getCodeModel() == CodeModel::Small ||
280 !ObjType->isSized() ||
281 getDataLayout()->getTypeAllocSize(ObjType) < CodeModelLargeSize) {
282 // We can only fold positive offsets that are a multiple of the word size.
283 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
284 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
285 GA = getGlobalAddressWrapper(GA, GV, DAG);
286 // Handle the rest of the offset.
287 if (Offset != FoldedOffset) {
288 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
289 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
290 }
291 return GA;
292 } else {
293 // Ideally we would not fold in offset with an index <= 11.
294 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
295 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
296 Ty = Type::getInt32Ty(*DAG.getContext());
297 Constant *Idx = ConstantInt::get(Ty, Offset);
298 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
299 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
300 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
301 MachinePointerInfo(), false, false, false, 0);
302 }
303 }
305 SDValue XCoreTargetLowering::
306 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
307 {
308 SDLoc DL(Op);
310 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
311 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
313 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
314 }
316 SDValue XCoreTargetLowering::
317 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
318 {
319 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
320 // FIXME there isn't really debug info here
321 SDLoc dl(CP);
322 EVT PtrVT = Op.getValueType();
323 SDValue Res;
324 if (CP->isMachineConstantPoolEntry()) {
325 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
326 CP->getAlignment(), CP->getOffset());
327 } else {
328 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
329 CP->getAlignment(), CP->getOffset());
330 }
331 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
332 }
334 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
335 return MachineJumpTableInfo::EK_Inline;
336 }
338 SDValue XCoreTargetLowering::
339 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
340 {
341 SDValue Chain = Op.getOperand(0);
342 SDValue Table = Op.getOperand(1);
343 SDValue Index = Op.getOperand(2);
344 SDLoc dl(Op);
345 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
346 unsigned JTI = JT->getIndex();
347 MachineFunction &MF = DAG.getMachineFunction();
348 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
349 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
351 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
352 if (NumEntries <= 32) {
353 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
354 }
355 assert((NumEntries >> 31) == 0);
356 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
357 DAG.getConstant(1, MVT::i32));
358 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
359 ScaledIndex);
360 }
362 SDValue XCoreTargetLowering::
363 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
364 int64_t Offset, SelectionDAG &DAG) const
365 {
366 if ((Offset & 0x3) == 0) {
367 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
368 false, false, false, 0);
369 }
370 // Lower to pair of consecutive word aligned loads plus some bit shifting.
371 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
372 int32_t LowOffset = HighOffset - 4;
373 SDValue LowAddr, HighAddr;
374 if (GlobalAddressSDNode *GASD =
375 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
376 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
377 LowOffset);
378 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
379 HighOffset);
380 } else {
381 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
382 DAG.getConstant(LowOffset, MVT::i32));
383 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
384 DAG.getConstant(HighOffset, MVT::i32));
385 }
386 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
387 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
389 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
390 LowAddr, MachinePointerInfo(),
391 false, false, false, 0);
392 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
393 HighAddr, MachinePointerInfo(),
394 false, false, false, 0);
395 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
396 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
397 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
398 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
399 High.getValue(1));
400 SDValue Ops[] = { Result, Chain };
401 return DAG.getMergeValues(Ops, 2, DL);
402 }
404 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
405 {
406 APInt KnownZero, KnownOne;
407 DAG.ComputeMaskedBits(Value, KnownZero, KnownOne);
408 return KnownZero.countTrailingOnes() >= 2;
409 }
411 SDValue XCoreTargetLowering::
412 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
414 LoadSDNode *LD = cast<LoadSDNode>(Op);
415 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
416 "Unexpected extension type");
417 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
418 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
419 return SDValue();
421 unsigned ABIAlignment = getDataLayout()->
422 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
423 // Leave aligned load alone.
424 if (LD->getAlignment() >= ABIAlignment)
425 return SDValue();
427 SDValue Chain = LD->getChain();
428 SDValue BasePtr = LD->getBasePtr();
429 SDLoc DL(Op);
431 if (!LD->isVolatile()) {
432 const GlobalValue *GV;
433 int64_t Offset = 0;
434 if (DAG.isBaseWithConstantOffset(BasePtr) &&
435 isWordAligned(BasePtr->getOperand(0), DAG)) {
436 SDValue NewBasePtr = BasePtr->getOperand(0);
437 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
438 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
439 Offset, DAG);
440 }
441 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
442 MinAlign(GV->getAlignment(), 4) == 4) {
443 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
444 BasePtr->getValueType(0));
445 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
446 Offset, DAG);
447 }
448 }
450 if (LD->getAlignment() == 2) {
451 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
452 BasePtr, LD->getPointerInfo(), MVT::i16,
453 LD->isVolatile(), LD->isNonTemporal(), 2);
454 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
455 DAG.getConstant(2, MVT::i32));
456 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
457 HighAddr,
458 LD->getPointerInfo().getWithOffset(2),
459 MVT::i16, LD->isVolatile(),
460 LD->isNonTemporal(), 2);
461 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
462 DAG.getConstant(16, MVT::i32));
463 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
464 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
465 High.getValue(1));
466 SDValue Ops[] = { Result, Chain };
467 return DAG.getMergeValues(Ops, 2, DL);
468 }
470 // Lower to a call to __misaligned_load(BasePtr).
471 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
472 TargetLowering::ArgListTy Args;
473 TargetLowering::ArgListEntry Entry;
475 Entry.Ty = IntPtrTy;
476 Entry.Node = BasePtr;
477 Args.push_back(Entry);
479 TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
480 false, false, 0, CallingConv::C, /*isTailCall=*/false,
481 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
482 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
483 Args, DAG, DL);
484 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
486 SDValue Ops[] =
487 { CallResult.first, CallResult.second };
489 return DAG.getMergeValues(Ops, 2, DL);
490 }
492 SDValue XCoreTargetLowering::
493 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
494 {
495 StoreSDNode *ST = cast<StoreSDNode>(Op);
496 assert(!ST->isTruncatingStore() && "Unexpected store type");
497 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
498 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
499 return SDValue();
500 }
501 unsigned ABIAlignment = getDataLayout()->
502 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
503 // Leave aligned store alone.
504 if (ST->getAlignment() >= ABIAlignment) {
505 return SDValue();
506 }
507 SDValue Chain = ST->getChain();
508 SDValue BasePtr = ST->getBasePtr();
509 SDValue Value = ST->getValue();
510 SDLoc dl(Op);
512 if (ST->getAlignment() == 2) {
513 SDValue Low = Value;
514 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
515 DAG.getConstant(16, MVT::i32));
516 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
517 ST->getPointerInfo(), MVT::i16,
518 ST->isVolatile(), ST->isNonTemporal(),
519 2);
520 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
521 DAG.getConstant(2, MVT::i32));
522 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
523 ST->getPointerInfo().getWithOffset(2),
524 MVT::i16, ST->isVolatile(),
525 ST->isNonTemporal(), 2);
526 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
527 }
529 // Lower to a call to __misaligned_store(BasePtr, Value).
530 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
531 TargetLowering::ArgListTy Args;
532 TargetLowering::ArgListEntry Entry;
534 Entry.Ty = IntPtrTy;
535 Entry.Node = BasePtr;
536 Args.push_back(Entry);
538 Entry.Node = Value;
539 Args.push_back(Entry);
541 TargetLowering::CallLoweringInfo CLI(Chain,
542 Type::getVoidTy(*DAG.getContext()), false, false,
543 false, false, 0, CallingConv::C, /*isTailCall=*/false,
544 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
545 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
546 Args, DAG, dl);
547 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
549 return CallResult.second;
550 }
552 SDValue XCoreTargetLowering::
553 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
554 {
555 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
556 "Unexpected operand to lower!");
557 SDLoc dl(Op);
558 SDValue LHS = Op.getOperand(0);
559 SDValue RHS = Op.getOperand(1);
560 SDValue Zero = DAG.getConstant(0, MVT::i32);
561 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
562 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
563 LHS, RHS);
564 SDValue Lo(Hi.getNode(), 1);
565 SDValue Ops[] = { Lo, Hi };
566 return DAG.getMergeValues(Ops, 2, dl);
567 }
569 SDValue XCoreTargetLowering::
570 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
571 {
572 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
573 "Unexpected operand to lower!");
574 SDLoc dl(Op);
575 SDValue LHS = Op.getOperand(0);
576 SDValue RHS = Op.getOperand(1);
577 SDValue Zero = DAG.getConstant(0, MVT::i32);
578 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
579 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
580 Zero, Zero);
581 SDValue Lo(Hi.getNode(), 1);
582 SDValue Ops[] = { Lo, Hi };
583 return DAG.getMergeValues(Ops, 2, dl);
584 }
586 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
587 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
588 /// each intermediate result in the calculation must also have a single use.
589 /// If the Op is in the correct form the constituent parts are written to Mul0,
590 /// Mul1, Addend0 and Addend1.
591 static bool
592 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
593 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
594 {
595 if (Op.getOpcode() != ISD::ADD)
596 return false;
597 SDValue N0 = Op.getOperand(0);
598 SDValue N1 = Op.getOperand(1);
599 SDValue AddOp;
600 SDValue OtherOp;
601 if (N0.getOpcode() == ISD::ADD) {
602 AddOp = N0;
603 OtherOp = N1;
604 } else if (N1.getOpcode() == ISD::ADD) {
605 AddOp = N1;
606 OtherOp = N0;
607 } else {
608 return false;
609 }
610 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
611 return false;
612 if (OtherOp.getOpcode() == ISD::MUL) {
613 // add(add(a,b),mul(x,y))
614 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
615 return false;
616 Mul0 = OtherOp.getOperand(0);
617 Mul1 = OtherOp.getOperand(1);
618 Addend0 = AddOp.getOperand(0);
619 Addend1 = AddOp.getOperand(1);
620 return true;
621 }
622 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
623 // add(add(mul(x,y),a),b)
624 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
625 return false;
626 Mul0 = AddOp.getOperand(0).getOperand(0);
627 Mul1 = AddOp.getOperand(0).getOperand(1);
628 Addend0 = AddOp.getOperand(1);
629 Addend1 = OtherOp;
630 return true;
631 }
632 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
633 // add(add(a,mul(x,y)),b)
634 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
635 return false;
636 Mul0 = AddOp.getOperand(1).getOperand(0);
637 Mul1 = AddOp.getOperand(1).getOperand(1);
638 Addend0 = AddOp.getOperand(0);
639 Addend1 = OtherOp;
640 return true;
641 }
642 return false;
643 }
645 SDValue XCoreTargetLowering::
646 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
647 {
648 SDValue Mul;
649 SDValue Other;
650 if (N->getOperand(0).getOpcode() == ISD::MUL) {
651 Mul = N->getOperand(0);
652 Other = N->getOperand(1);
653 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
654 Mul = N->getOperand(1);
655 Other = N->getOperand(0);
656 } else {
657 return SDValue();
658 }
659 SDLoc dl(N);
660 SDValue LL, RL, AddendL, AddendH;
661 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
662 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
663 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
664 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
665 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
666 Other, DAG.getConstant(0, MVT::i32));
667 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
668 Other, DAG.getConstant(1, MVT::i32));
669 APInt HighMask = APInt::getHighBitsSet(64, 32);
670 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
671 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
672 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
673 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
674 // The inputs are both zero-extended.
675 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
676 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
677 AddendL, LL, RL);
678 SDValue Lo(Hi.getNode(), 1);
679 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
680 }
681 if (LHSSB > 32 && RHSSB > 32) {
682 // The inputs are both sign-extended.
683 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
684 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
685 AddendL, LL, RL);
686 SDValue Lo(Hi.getNode(), 1);
687 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
688 }
689 SDValue LH, RH;
690 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
692 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
693 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
694 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
695 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
696 AddendL, LL, RL);
697 SDValue Lo(Hi.getNode(), 1);
698 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
699 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
700 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
701 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
702 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
703 }
705 SDValue XCoreTargetLowering::
706 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
707 {
708 assert(N->getValueType(0) == MVT::i64 &&
709 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
710 "Unknown operand to lower!");
712 if (N->getOpcode() == ISD::ADD) {
713 SDValue Result = TryExpandADDWithMul(N, DAG);
714 if (Result.getNode() != 0)
715 return Result;
716 }
718 SDLoc dl(N);
720 // Extract components
721 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
722 N->getOperand(0), DAG.getConstant(0, MVT::i32));
723 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
724 N->getOperand(0), DAG.getConstant(1, MVT::i32));
725 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
726 N->getOperand(1), DAG.getConstant(0, MVT::i32));
727 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
728 N->getOperand(1), DAG.getConstant(1, MVT::i32));
730 // Expand
731 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
732 XCoreISD::LSUB;
733 SDValue Zero = DAG.getConstant(0, MVT::i32);
734 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
735 LHSL, RHSL, Zero);
736 SDValue Carry(Lo.getNode(), 1);
738 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
739 LHSH, RHSH, Carry);
740 SDValue Ignored(Hi.getNode(), 1);
741 // Merge the pieces
742 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
743 }
745 SDValue XCoreTargetLowering::
746 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
747 {
748 // Whist llvm does not support aggregate varargs we can ignore
749 // the possibility of the ValueType being an implicit byVal vararg.
750 SDNode *Node = Op.getNode();
751 EVT VT = Node->getValueType(0); // not an aggregate
752 SDValue InChain = Node->getOperand(0);
753 SDValue VAListPtr = Node->getOperand(1);
754 EVT PtrVT = VAListPtr.getValueType();
755 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
756 SDLoc dl(Node);
757 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
758 VAListPtr, MachinePointerInfo(SV),
759 false, false, false, 0);
760 // Increment the pointer, VAList, to the next vararg
761 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
762 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
763 // Store the incremented VAList to the legalized pointer
764 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
765 MachinePointerInfo(SV), false, false, 0);
766 // Load the actual argument out of the pointer VAList
767 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
768 false, false, false, 0);
769 }
771 SDValue XCoreTargetLowering::
772 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
773 {
774 SDLoc dl(Op);
775 // vastart stores the address of the VarArgsFrameIndex slot into the
776 // memory location argument
777 MachineFunction &MF = DAG.getMachineFunction();
778 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
779 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
780 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
781 MachinePointerInfo(), false, false, 0);
782 }
784 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
785 SelectionDAG &DAG) const {
786 SDLoc dl(Op);
787 // Depths > 0 not supported yet!
788 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
789 return SDValue();
791 MachineFunction &MF = DAG.getMachineFunction();
792 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
793 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
794 RegInfo->getFrameRegister(MF), MVT::i32);
795 }
797 SDValue XCoreTargetLowering::
798 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
799 return Op.getOperand(0);
800 }
802 SDValue XCoreTargetLowering::
803 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
804 SDValue Chain = Op.getOperand(0);
805 SDValue Trmp = Op.getOperand(1); // trampoline
806 SDValue FPtr = Op.getOperand(2); // nested function
807 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
809 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
811 // .align 4
812 // LDAPF_u10 r11, nest
813 // LDW_2rus r11, r11[0]
814 // STWSP_ru6 r11, sp[0]
815 // LDAPF_u10 r11, fptr
816 // LDW_2rus r11, r11[0]
817 // BAU_1r r11
818 // nest:
819 // .word nest
820 // fptr:
821 // .word fptr
822 SDValue OutChains[5];
824 SDValue Addr = Trmp;
826 SDLoc dl(Op);
827 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
828 Addr, MachinePointerInfo(TrmpAddr), false, false,
829 0);
831 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
832 DAG.getConstant(4, MVT::i32));
833 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
834 Addr, MachinePointerInfo(TrmpAddr, 4), false,
835 false, 0);
837 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
838 DAG.getConstant(8, MVT::i32));
839 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
840 Addr, MachinePointerInfo(TrmpAddr, 8), false,
841 false, 0);
843 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
844 DAG.getConstant(12, MVT::i32));
845 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
846 MachinePointerInfo(TrmpAddr, 12), false, false,
847 0);
849 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
850 DAG.getConstant(16, MVT::i32));
851 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
852 MachinePointerInfo(TrmpAddr, 16), false, false,
853 0);
855 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
856 }
858 SDValue XCoreTargetLowering::
859 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
860 SDLoc DL(Op);
861 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
862 switch (IntNo) {
863 case Intrinsic::xcore_crc8:
864 EVT VT = Op.getValueType();
865 SDValue Data =
866 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
867 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
868 SDValue Crc(Data.getNode(), 1);
869 SDValue Results[] = { Crc, Data };
870 return DAG.getMergeValues(Results, 2, DL);
871 }
872 return SDValue();
873 }
875 SDValue XCoreTargetLowering::
876 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
877 SDLoc DL(Op);
878 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
879 }
881 //===----------------------------------------------------------------------===//
882 // Calling Convention Implementation
883 //===----------------------------------------------------------------------===//
885 #include "XCoreGenCallingConv.inc"
887 //===----------------------------------------------------------------------===//
888 // Call Calling Convention Implementation
889 //===----------------------------------------------------------------------===//
891 /// XCore call implementation
892 SDValue
893 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
894 SmallVectorImpl<SDValue> &InVals) const {
895 SelectionDAG &DAG = CLI.DAG;
896 SDLoc &dl = CLI.DL;
897 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
898 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
899 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
900 SDValue Chain = CLI.Chain;
901 SDValue Callee = CLI.Callee;
902 bool &isTailCall = CLI.IsTailCall;
903 CallingConv::ID CallConv = CLI.CallConv;
904 bool isVarArg = CLI.IsVarArg;
906 // XCore target does not yet support tail call optimization.
907 isTailCall = false;
909 // For now, only CallingConv::C implemented
910 switch (CallConv)
911 {
912 default:
913 llvm_unreachable("Unsupported calling convention");
914 case CallingConv::Fast:
915 case CallingConv::C:
916 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
917 Outs, OutVals, Ins, dl, DAG, InVals);
918 }
919 }
921 /// LowerCCCCallTo - functions arguments are copied from virtual
922 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
923 /// CALLSEQ_END are emitted.
924 /// TODO: isTailCall, sret.
925 SDValue
926 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
927 CallingConv::ID CallConv, bool isVarArg,
928 bool isTailCall,
929 const SmallVectorImpl<ISD::OutputArg> &Outs,
930 const SmallVectorImpl<SDValue> &OutVals,
931 const SmallVectorImpl<ISD::InputArg> &Ins,
932 SDLoc dl, SelectionDAG &DAG,
933 SmallVectorImpl<SDValue> &InVals) const {
935 // Analyze operands of the call, assigning locations to each operand.
936 SmallVector<CCValAssign, 16> ArgLocs;
937 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
938 getTargetMachine(), ArgLocs, *DAG.getContext());
940 // The ABI dictates there should be one stack slot available to the callee
941 // on function entry (for saving lr).
942 CCInfo.AllocateStack(4, 4);
944 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
946 // Get a count of how many bytes are to be pushed on the stack.
947 unsigned NumBytes = CCInfo.getNextStackOffset();
949 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
950 getPointerTy(), true), dl);
952 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
953 SmallVector<SDValue, 12> MemOpChains;
955 // Walk the register/memloc assignments, inserting copies/loads.
956 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
957 CCValAssign &VA = ArgLocs[i];
958 SDValue Arg = OutVals[i];
960 // Promote the value if needed.
961 switch (VA.getLocInfo()) {
962 default: llvm_unreachable("Unknown loc info!");
963 case CCValAssign::Full: break;
964 case CCValAssign::SExt:
965 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
966 break;
967 case CCValAssign::ZExt:
968 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
969 break;
970 case CCValAssign::AExt:
971 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
972 break;
973 }
975 // Arguments that can be passed on register must be kept at
976 // RegsToPass vector
977 if (VA.isRegLoc()) {
978 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
979 } else {
980 assert(VA.isMemLoc());
982 int Offset = VA.getLocMemOffset();
984 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
985 Chain, Arg,
986 DAG.getConstant(Offset/4, MVT::i32)));
987 }
988 }
990 // Transform all store nodes into one single node because
991 // all store nodes are independent of each other.
992 if (!MemOpChains.empty())
993 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
994 &MemOpChains[0], MemOpChains.size());
996 // Build a sequence of copy-to-reg nodes chained together with token
997 // chain and flag operands which copy the outgoing args into registers.
998 // The InFlag in necessary since all emitted instructions must be
999 // stuck together.
1000 SDValue InFlag;
1001 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1002 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1003 RegsToPass[i].second, InFlag);
1004 InFlag = Chain.getValue(1);
1005 }
1007 // If the callee is a GlobalAddress node (quite common, every direct call is)
1008 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1009 // Likewise ExternalSymbol -> TargetExternalSymbol.
1010 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1011 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1012 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1013 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1015 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1016 // = Chain, Callee, Reg#1, Reg#2, ...
1017 //
1018 // Returns a chain & a flag for retval copy to use.
1019 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1020 SmallVector<SDValue, 8> Ops;
1021 Ops.push_back(Chain);
1022 Ops.push_back(Callee);
1024 // Add argument registers to the end of the list so that they are
1025 // known live into the call.
1026 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1027 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1028 RegsToPass[i].second.getValueType()));
1030 if (InFlag.getNode())
1031 Ops.push_back(InFlag);
1033 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1034 InFlag = Chain.getValue(1);
1036 // Create the CALLSEQ_END node.
1037 Chain = DAG.getCALLSEQ_END(Chain,
1038 DAG.getConstant(NumBytes, getPointerTy(), true),
1039 DAG.getConstant(0, getPointerTy(), true),
1040 InFlag, dl);
1041 InFlag = Chain.getValue(1);
1043 // Handle result values, copying them out of physregs into vregs that we
1044 // return.
1045 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1046 Ins, dl, DAG, InVals);
1047 }
1049 /// LowerCallResult - Lower the result values of a call into the
1050 /// appropriate copies out of appropriate physical registers.
1051 SDValue
1052 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1053 CallingConv::ID CallConv, bool isVarArg,
1054 const SmallVectorImpl<ISD::InputArg> &Ins,
1055 SDLoc dl, SelectionDAG &DAG,
1056 SmallVectorImpl<SDValue> &InVals) const {
1058 // Assign locations to each value returned by this call.
1059 SmallVector<CCValAssign, 16> RVLocs;
1060 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1061 getTargetMachine(), RVLocs, *DAG.getContext());
1063 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1065 // Copy all of the result registers out of their specified physreg.
1066 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1067 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1068 RVLocs[i].getValVT(), InFlag).getValue(1);
1069 InFlag = Chain.getValue(2);
1070 InVals.push_back(Chain.getValue(0));
1071 }
1073 return Chain;
1074 }
1076 //===----------------------------------------------------------------------===//
1077 // Formal Arguments Calling Convention Implementation
1078 //===----------------------------------------------------------------------===//
1080 namespace {
1081 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1082 }
1084 /// XCore formal arguments implementation
1085 SDValue
1086 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1087 CallingConv::ID CallConv,
1088 bool isVarArg,
1089 const SmallVectorImpl<ISD::InputArg> &Ins,
1090 SDLoc dl,
1091 SelectionDAG &DAG,
1092 SmallVectorImpl<SDValue> &InVals)
1093 const {
1094 switch (CallConv)
1095 {
1096 default:
1097 llvm_unreachable("Unsupported calling convention");
1098 case CallingConv::C:
1099 case CallingConv::Fast:
1100 return LowerCCCArguments(Chain, CallConv, isVarArg,
1101 Ins, dl, DAG, InVals);
1102 }
1103 }
1105 /// LowerCCCArguments - transform physical registers into
1106 /// virtual registers and generate load operations for
1107 /// arguments places on the stack.
1108 /// TODO: sret
1109 SDValue
1110 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1111 CallingConv::ID CallConv,
1112 bool isVarArg,
1113 const SmallVectorImpl<ISD::InputArg>
1114 &Ins,
1115 SDLoc dl,
1116 SelectionDAG &DAG,
1117 SmallVectorImpl<SDValue> &InVals) const {
1118 MachineFunction &MF = DAG.getMachineFunction();
1119 MachineFrameInfo *MFI = MF.getFrameInfo();
1120 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1122 // Assign locations to all of the incoming arguments.
1123 SmallVector<CCValAssign, 16> ArgLocs;
1124 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1125 getTargetMachine(), ArgLocs, *DAG.getContext());
1127 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1129 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1131 unsigned LRSaveSize = StackSlotSize;
1133 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1134 // scheduler clobbering a register before it has been copied.
1135 // The stages are:
1136 // 1. CopyFromReg (and load) arg & vararg registers.
1137 // 2. Chain CopyFromReg nodes into a TokenFactor.
1138 // 3. Memcpy 'byVal' args & push final InVals.
1139 // 4. Chain mem ops nodes into a TokenFactor.
1140 SmallVector<SDValue, 4> CFRegNode;
1141 SmallVector<ArgDataPair, 4> ArgData;
1142 SmallVector<SDValue, 4> MemOps;
1144 // 1a. CopyFromReg (and load) arg registers.
1145 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1147 CCValAssign &VA = ArgLocs[i];
1148 SDValue ArgIn;
1150 if (VA.isRegLoc()) {
1151 // Arguments passed in registers
1152 EVT RegVT = VA.getLocVT();
1153 switch (RegVT.getSimpleVT().SimpleTy) {
1154 default:
1155 {
1156 #ifndef NDEBUG
1157 errs() << "LowerFormalArguments Unhandled argument type: "
1158 << RegVT.getSimpleVT().SimpleTy << "\n";
1159 #endif
1160 llvm_unreachable(0);
1161 }
1162 case MVT::i32:
1163 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1164 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1165 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1166 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1167 }
1168 } else {
1169 // sanity check
1170 assert(VA.isMemLoc());
1171 // Load the argument to a virtual register
1172 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1173 if (ObjSize > StackSlotSize) {
1174 errs() << "LowerFormalArguments Unhandled argument type: "
1175 << EVT(VA.getLocVT()).getEVTString()
1176 << "\n";
1177 }
1178 // Create the frame index object for this incoming parameter...
1179 int FI = MFI->CreateFixedObject(ObjSize,
1180 LRSaveSize + VA.getLocMemOffset(),
1181 true);
1183 // Create the SelectionDAG nodes corresponding to a load
1184 //from this parameter
1185 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1186 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1187 MachinePointerInfo::getFixedStack(FI),
1188 false, false, false, 0);
1189 }
1190 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1191 ArgData.push_back(ADP);
1192 }
1194 // 1b. CopyFromReg vararg registers.
1195 if (isVarArg) {
1196 // Argument registers
1197 static const uint16_t ArgRegs[] = {
1198 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1199 };
1200 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1201 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1202 array_lengthof(ArgRegs));
1203 if (FirstVAReg < array_lengthof(ArgRegs)) {
1204 int offset = 0;
1205 // Save remaining registers, storing higher register numbers at a higher
1206 // address
1207 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1208 // Create a stack slot
1209 int FI = MFI->CreateFixedObject(4, offset, true);
1210 if (i == (int)FirstVAReg) {
1211 XFI->setVarArgsFrameIndex(FI);
1212 }
1213 offset -= StackSlotSize;
1214 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1215 // Move argument from phys reg -> virt reg
1216 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1217 RegInfo.addLiveIn(ArgRegs[i], VReg);
1218 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1219 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1220 // Move argument from virt reg -> stack
1221 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1222 MachinePointerInfo(), false, false, 0);
1223 MemOps.push_back(Store);
1224 }
1225 } else {
1226 // This will point to the next argument passed via stack.
1227 XFI->setVarArgsFrameIndex(
1228 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1229 true));
1230 }
1231 }
1233 // 2. chain CopyFromReg nodes into a TokenFactor.
1234 if (!CFRegNode.empty())
1235 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &CFRegNode[0],
1236 CFRegNode.size());
1238 // 3. Memcpy 'byVal' args & push final InVals.
1239 // Aggregates passed "byVal" need to be copied by the callee.
1240 // The callee will use a pointer to this copy, rather than the original
1241 // pointer.
1242 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1243 ArgDE = ArgData.end();
1244 ArgDI != ArgDE; ++ArgDI) {
1245 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1246 unsigned Size = ArgDI->Flags.getByValSize();
1247 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1248 // Create a new object on the stack and copy the pointee into it.
1249 int FI = MFI->CreateStackObject(Size, Align, false, false);
1250 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1251 InVals.push_back(FIN);
1252 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1253 DAG.getConstant(Size, MVT::i32),
1254 Align, false, false,
1255 MachinePointerInfo(),
1256 MachinePointerInfo()));
1257 } else {
1258 InVals.push_back(ArgDI->SDV);
1259 }
1260 }
1262 // 4, chain mem ops nodes into a TokenFactor.
1263 if (!MemOps.empty()) {
1264 MemOps.push_back(Chain);
1265 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
1266 MemOps.size());
1267 }
1269 return Chain;
1270 }
1272 //===----------------------------------------------------------------------===//
1273 // Return Value Calling Convention Implementation
1274 //===----------------------------------------------------------------------===//
1276 bool XCoreTargetLowering::
1277 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1278 bool isVarArg,
1279 const SmallVectorImpl<ISD::OutputArg> &Outs,
1280 LLVMContext &Context) const {
1281 SmallVector<CCValAssign, 16> RVLocs;
1282 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1283 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1284 }
1286 SDValue
1287 XCoreTargetLowering::LowerReturn(SDValue Chain,
1288 CallingConv::ID CallConv, bool isVarArg,
1289 const SmallVectorImpl<ISD::OutputArg> &Outs,
1290 const SmallVectorImpl<SDValue> &OutVals,
1291 SDLoc dl, SelectionDAG &DAG) const {
1293 // CCValAssign - represent the assignment of
1294 // the return value to a location
1295 SmallVector<CCValAssign, 16> RVLocs;
1297 // CCState - Info about the registers and stack slot.
1298 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1299 getTargetMachine(), RVLocs, *DAG.getContext());
1301 // Analyze return values.
1302 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1304 SDValue Flag;
1305 SmallVector<SDValue, 4> RetOps(1, Chain);
1307 // Return on XCore is always a "retsp 0"
1308 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1310 // Copy the result values into the output registers.
1311 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1312 CCValAssign &VA = RVLocs[i];
1313 assert(VA.isRegLoc() && "Can only return in registers!");
1315 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1316 OutVals[i], Flag);
1318 // guarantee that all emitted copies are
1319 // stuck together, avoiding something bad
1320 Flag = Chain.getValue(1);
1321 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1322 }
1324 RetOps[0] = Chain; // Update chain.
1326 // Add the flag if we have it.
1327 if (Flag.getNode())
1328 RetOps.push_back(Flag);
1330 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1331 &RetOps[0], RetOps.size());
1332 }
1334 //===----------------------------------------------------------------------===//
1335 // Other Lowering Code
1336 //===----------------------------------------------------------------------===//
1338 MachineBasicBlock *
1339 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1340 MachineBasicBlock *BB) const {
1341 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1342 DebugLoc dl = MI->getDebugLoc();
1343 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1344 "Unexpected instr type to insert");
1346 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1347 // control-flow pattern. The incoming instruction knows the destination vreg
1348 // to set, the condition code register to branch on, the true/false values to
1349 // select between, and a branch opcode to use.
1350 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1351 MachineFunction::iterator It = BB;
1352 ++It;
1354 // thisMBB:
1355 // ...
1356 // TrueVal = ...
1357 // cmpTY ccX, r1, r2
1358 // bCC copy1MBB
1359 // fallthrough --> copy0MBB
1360 MachineBasicBlock *thisMBB = BB;
1361 MachineFunction *F = BB->getParent();
1362 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1363 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1364 F->insert(It, copy0MBB);
1365 F->insert(It, sinkMBB);
1367 // Transfer the remainder of BB and its successor edges to sinkMBB.
1368 sinkMBB->splice(sinkMBB->begin(), BB,
1369 llvm::next(MachineBasicBlock::iterator(MI)),
1370 BB->end());
1371 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1373 // Next, add the true and fallthrough blocks as its successors.
1374 BB->addSuccessor(copy0MBB);
1375 BB->addSuccessor(sinkMBB);
1377 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1378 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1380 // copy0MBB:
1381 // %FalseValue = ...
1382 // # fallthrough to sinkMBB
1383 BB = copy0MBB;
1385 // Update machine-CFG edges
1386 BB->addSuccessor(sinkMBB);
1388 // sinkMBB:
1389 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1390 // ...
1391 BB = sinkMBB;
1392 BuildMI(*BB, BB->begin(), dl,
1393 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1394 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1395 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1397 MI->eraseFromParent(); // The pseudo instruction is gone now.
1398 return BB;
1399 }
1401 //===----------------------------------------------------------------------===//
1402 // Target Optimization Hooks
1403 //===----------------------------------------------------------------------===//
1405 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1406 DAGCombinerInfo &DCI) const {
1407 SelectionDAG &DAG = DCI.DAG;
1408 SDLoc dl(N);
1409 switch (N->getOpcode()) {
1410 default: break;
1411 case XCoreISD::LADD: {
1412 SDValue N0 = N->getOperand(0);
1413 SDValue N1 = N->getOperand(1);
1414 SDValue N2 = N->getOperand(2);
1415 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1416 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1417 EVT VT = N0.getValueType();
1419 // canonicalize constant to RHS
1420 if (N0C && !N1C)
1421 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1423 // fold (ladd 0, 0, x) -> 0, x & 1
1424 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1425 SDValue Carry = DAG.getConstant(0, VT);
1426 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1427 DAG.getConstant(1, VT));
1428 SDValue Ops[] = { Result, Carry };
1429 return DAG.getMergeValues(Ops, 2, dl);
1430 }
1432 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1433 // low bit set
1434 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1435 APInt KnownZero, KnownOne;
1436 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1437 VT.getSizeInBits() - 1);
1438 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1439 if ((KnownZero & Mask) == Mask) {
1440 SDValue Carry = DAG.getConstant(0, VT);
1441 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1442 SDValue Ops[] = { Result, Carry };
1443 return DAG.getMergeValues(Ops, 2, dl);
1444 }
1445 }
1446 }
1447 break;
1448 case XCoreISD::LSUB: {
1449 SDValue N0 = N->getOperand(0);
1450 SDValue N1 = N->getOperand(1);
1451 SDValue N2 = N->getOperand(2);
1452 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1453 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1454 EVT VT = N0.getValueType();
1456 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1457 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1458 APInt KnownZero, KnownOne;
1459 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1460 VT.getSizeInBits() - 1);
1461 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1462 if ((KnownZero & Mask) == Mask) {
1463 SDValue Borrow = N2;
1464 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1465 DAG.getConstant(0, VT), N2);
1466 SDValue Ops[] = { Result, Borrow };
1467 return DAG.getMergeValues(Ops, 2, dl);
1468 }
1469 }
1471 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1472 // low bit set
1473 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1474 APInt KnownZero, KnownOne;
1475 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1476 VT.getSizeInBits() - 1);
1477 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1478 if ((KnownZero & Mask) == Mask) {
1479 SDValue Borrow = DAG.getConstant(0, VT);
1480 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1481 SDValue Ops[] = { Result, Borrow };
1482 return DAG.getMergeValues(Ops, 2, dl);
1483 }
1484 }
1485 }
1486 break;
1487 case XCoreISD::LMUL: {
1488 SDValue N0 = N->getOperand(0);
1489 SDValue N1 = N->getOperand(1);
1490 SDValue N2 = N->getOperand(2);
1491 SDValue N3 = N->getOperand(3);
1492 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1494 EVT VT = N0.getValueType();
1495 // Canonicalize multiplicative constant to RHS. If both multiplicative
1496 // operands are constant canonicalize smallest to RHS.
1497 if ((N0C && !N1C) ||
1498 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1499 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1500 N1, N0, N2, N3);
1502 // lmul(x, 0, a, b)
1503 if (N1C && N1C->isNullValue()) {
1504 // If the high result is unused fold to add(a, b)
1505 if (N->hasNUsesOfValue(0, 0)) {
1506 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1507 SDValue Ops[] = { Lo, Lo };
1508 return DAG.getMergeValues(Ops, 2, dl);
1509 }
1510 // Otherwise fold to ladd(a, b, 0)
1511 SDValue Result =
1512 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1513 SDValue Carry(Result.getNode(), 1);
1514 SDValue Ops[] = { Carry, Result };
1515 return DAG.getMergeValues(Ops, 2, dl);
1516 }
1517 }
1518 break;
1519 case ISD::ADD: {
1520 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1521 // lmul(x, y, a, b). The high result of lmul will be ignored.
1522 // This is only profitable if the intermediate results are unused
1523 // elsewhere.
1524 SDValue Mul0, Mul1, Addend0, Addend1;
1525 if (N->getValueType(0) == MVT::i32 &&
1526 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1527 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1528 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1529 Mul1, Addend0, Addend1);
1530 SDValue Result(Ignored.getNode(), 1);
1531 return Result;
1532 }
1533 APInt HighMask = APInt::getHighBitsSet(64, 32);
1534 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1535 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1536 // before type legalization as it is messy to match the operands after
1537 // that.
1538 if (N->getValueType(0) == MVT::i64 &&
1539 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1540 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1541 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1542 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1543 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1544 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1545 Mul0, DAG.getConstant(0, MVT::i32));
1546 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1547 Mul1, DAG.getConstant(0, MVT::i32));
1548 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1549 Addend0, DAG.getConstant(0, MVT::i32));
1550 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1551 Addend1, DAG.getConstant(0, MVT::i32));
1552 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1553 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1554 Addend0L, Addend1L);
1555 SDValue Lo(Hi.getNode(), 1);
1556 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1557 }
1558 }
1559 break;
1560 case ISD::STORE: {
1561 // Replace unaligned store of unaligned load with memmove.
1562 StoreSDNode *ST = cast<StoreSDNode>(N);
1563 if (!DCI.isBeforeLegalize() ||
1564 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1565 ST->isVolatile() || ST->isIndexed()) {
1566 break;
1567 }
1568 SDValue Chain = ST->getChain();
1570 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1571 if (StoreBits % 8) {
1572 break;
1573 }
1574 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1575 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1576 unsigned Alignment = ST->getAlignment();
1577 if (Alignment >= ABIAlignment) {
1578 break;
1579 }
1581 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1582 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1583 LD->getAlignment() == Alignment &&
1584 !LD->isVolatile() && !LD->isIndexed() &&
1585 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1586 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1587 LD->getBasePtr(),
1588 DAG.getConstant(StoreBits/8, MVT::i32),
1589 Alignment, false, ST->getPointerInfo(),
1590 LD->getPointerInfo());
1591 }
1592 }
1593 break;
1594 }
1595 }
1596 return SDValue();
1597 }
1599 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1600 APInt &KnownZero,
1601 APInt &KnownOne,
1602 const SelectionDAG &DAG,
1603 unsigned Depth) const {
1604 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1605 switch (Op.getOpcode()) {
1606 default: break;
1607 case XCoreISD::LADD:
1608 case XCoreISD::LSUB:
1609 if (Op.getResNo() == 1) {
1610 // Top bits of carry / borrow are clear.
1611 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1612 KnownZero.getBitWidth() - 1);
1613 }
1614 break;
1615 }
1616 }
1618 //===----------------------------------------------------------------------===//
1619 // Addressing mode description hooks
1620 //===----------------------------------------------------------------------===//
1622 static inline bool isImmUs(int64_t val)
1623 {
1624 return (val >= 0 && val <= 11);
1625 }
1627 static inline bool isImmUs2(int64_t val)
1628 {
1629 return (val%2 == 0 && isImmUs(val/2));
1630 }
1632 static inline bool isImmUs4(int64_t val)
1633 {
1634 return (val%4 == 0 && isImmUs(val/4));
1635 }
1637 /// isLegalAddressingMode - Return true if the addressing mode represented
1638 /// by AM is legal for this target, for a load/store of the specified type.
1639 bool
1640 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1641 Type *Ty) const {
1642 if (Ty->getTypeID() == Type::VoidTyID)
1643 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1645 const DataLayout *TD = TM.getDataLayout();
1646 unsigned Size = TD->getTypeAllocSize(Ty);
1647 if (AM.BaseGV) {
1648 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1649 AM.BaseOffs%4 == 0;
1650 }
1652 switch (Size) {
1653 case 1:
1654 // reg + imm
1655 if (AM.Scale == 0) {
1656 return isImmUs(AM.BaseOffs);
1657 }
1658 // reg + reg
1659 return AM.Scale == 1 && AM.BaseOffs == 0;
1660 case 2:
1661 case 3:
1662 // reg + imm
1663 if (AM.Scale == 0) {
1664 return isImmUs2(AM.BaseOffs);
1665 }
1666 // reg + reg<<1
1667 return AM.Scale == 2 && AM.BaseOffs == 0;
1668 default:
1669 // reg + imm
1670 if (AM.Scale == 0) {
1671 return isImmUs4(AM.BaseOffs);
1672 }
1673 // reg + reg<<2
1674 return AM.Scale == 4 && AM.BaseOffs == 0;
1675 }
1676 }
1678 //===----------------------------------------------------------------------===//
1679 // XCore Inline Assembly Support
1680 //===----------------------------------------------------------------------===//
1682 std::pair<unsigned, const TargetRegisterClass*>
1683 XCoreTargetLowering::
1684 getRegForInlineAsmConstraint(const std::string &Constraint,
1685 MVT VT) const {
1686 if (Constraint.size() == 1) {
1687 switch (Constraint[0]) {
1688 default : break;
1689 case 'r':
1690 return std::make_pair(0U, &XCore::GRRegsRegClass);
1691 }
1692 }
1693 // Use the default implementation in TargetLowering to convert the register
1694 // constraint into a member of a register class.
1695 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1696 }