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 //===----------------------------------------------------------------------===//
13
14 #include "XCoreISelLowering.h"
15 #include "XCore.h"
16 #include "XCoreMachineFunctionInfo.h"
17 #include "XCoreSubtarget.h"
18 #include "XCoreTargetMachine.h"
19 #include "XCoreTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39
40 using namespace llvm;
41
42 #define DEBUG_TYPE "xcore-lower"
43
44 const char *XCoreTargetLowering::
getTargetNodeName(unsigned Opcode) const45 getTargetNodeName(unsigned Opcode) const
46 {
47 switch ((XCoreISD::NodeType)Opcode)
48 {
49 case XCoreISD::FIRST_NUMBER : break;
50 case XCoreISD::BL : return "XCoreISD::BL";
51 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
52 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
53 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
54 case XCoreISD::LDWSP : return "XCoreISD::LDWSP";
55 case XCoreISD::STWSP : return "XCoreISD::STWSP";
56 case XCoreISD::RETSP : return "XCoreISD::RETSP";
57 case XCoreISD::LADD : return "XCoreISD::LADD";
58 case XCoreISD::LSUB : return "XCoreISD::LSUB";
59 case XCoreISD::LMUL : return "XCoreISD::LMUL";
60 case XCoreISD::MACCU : return "XCoreISD::MACCU";
61 case XCoreISD::MACCS : return "XCoreISD::MACCS";
62 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
63 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
64 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
65 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
66 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
67 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
68 }
69 return nullptr;
70 }
71
XCoreTargetLowering(const TargetMachine & TM,const XCoreSubtarget & Subtarget)72 XCoreTargetLowering::XCoreTargetLowering(const TargetMachine &TM,
73 const XCoreSubtarget &Subtarget)
74 : TargetLowering(TM), TM(TM), Subtarget(Subtarget) {
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78
79 // Compute derived properties from the register classes
80 computeRegisterProperties(Subtarget.getRegisterInfo());
81
82 setStackPointerRegisterToSaveRestore(XCore::SP);
83
84 setSchedulingPreference(Sched::Source);
85
86 // Use i32 for setcc operations results (slt, sgt, ...).
87 setBooleanContents(ZeroOrOneBooleanContent);
88 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
89
90 // XCore does not have the NodeTypes below.
91 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
92 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
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);
97
98 // 64bit
99 setOperationAction(ISD::ADD, MVT::i64, Custom);
100 setOperationAction(ISD::SUB, MVT::i64, Custom);
101 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
102 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
103 setOperationAction(ISD::MULHS, MVT::i32, Expand);
104 setOperationAction(ISD::MULHU, MVT::i32, Expand);
105 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
106 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
108
109 // Bit Manipulation
110 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
111 setOperationAction(ISD::ROTL , MVT::i32, Expand);
112 setOperationAction(ISD::ROTR , MVT::i32, Expand);
113
114 setOperationAction(ISD::TRAP, MVT::Other, Legal);
115
116 // Jump tables.
117 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
118
119 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
120 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
121
122 // Conversion of i64 -> double produces constantpool nodes
123 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
124
125 // Loads
126 for (MVT VT : MVT::integer_valuetypes()) {
127 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
128 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
129 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
130
131 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
132 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Expand);
133 }
134
135 // Custom expand misaligned loads / stores.
136 setOperationAction(ISD::LOAD, MVT::i32, Custom);
137 setOperationAction(ISD::STORE, MVT::i32, Custom);
138
139 // Varargs
140 setOperationAction(ISD::VAEND, MVT::Other, Expand);
141 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
142 setOperationAction(ISD::VAARG, MVT::Other, Custom);
143 setOperationAction(ISD::VASTART, MVT::Other, Custom);
144
145 // Dynamic stack
146 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
147 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
148 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
149
150 // Exception handling
151 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
152 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
153
154 // Atomic operations
155 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
156 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
157 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
158 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
159 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
160
161 // TRAMPOLINE is custom lowered.
162 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
163 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
164
165 // We want to custom lower some of our intrinsics.
166 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
167
168 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
169 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
170 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
171
172 // We have target-specific dag combine patterns for the following nodes:
173 setTargetDAGCombine(ISD::STORE);
174 setTargetDAGCombine(ISD::ADD);
175 setTargetDAGCombine(ISD::INTRINSIC_VOID);
176 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
177
178 setMinFunctionAlignment(1);
179 setPrefFunctionAlignment(2);
180 }
181
isZExtFree(SDValue Val,EVT VT2) const182 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
183 if (Val.getOpcode() != ISD::LOAD)
184 return false;
185
186 EVT VT1 = Val.getValueType();
187 if (!VT1.isSimple() || !VT1.isInteger() ||
188 !VT2.isSimple() || !VT2.isInteger())
189 return false;
190
191 switch (VT1.getSimpleVT().SimpleTy) {
192 default: break;
193 case MVT::i8:
194 return true;
195 }
196
197 return false;
198 }
199
200 SDValue XCoreTargetLowering::
LowerOperation(SDValue Op,SelectionDAG & DAG) const201 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
202 switch (Op.getOpcode())
203 {
204 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
205 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
206 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
207 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
208 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
209 case ISD::LOAD: return LowerLOAD(Op, DAG);
210 case ISD::STORE: return LowerSTORE(Op, DAG);
211 case ISD::VAARG: return LowerVAARG(Op, DAG);
212 case ISD::VASTART: return LowerVASTART(Op, DAG);
213 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
214 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
215 // FIXME: Remove these when LegalizeDAGTypes lands.
216 case ISD::ADD:
217 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
218 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
219 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
220 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
221 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
222 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
223 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
224 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
225 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
226 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
227 default:
228 llvm_unreachable("unimplemented operand");
229 }
230 }
231
232 /// ReplaceNodeResults - Replace the results of node with an illegal result
233 /// type with new values built out of custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const234 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
235 SmallVectorImpl<SDValue>&Results,
236 SelectionDAG &DAG) const {
237 switch (N->getOpcode()) {
238 default:
239 llvm_unreachable("Don't know how to custom expand this!");
240 case ISD::ADD:
241 case ISD::SUB:
242 Results.push_back(ExpandADDSUB(N, DAG));
243 return;
244 }
245 }
246
247 //===----------------------------------------------------------------------===//
248 // Misc Lower Operation implementation
249 //===----------------------------------------------------------------------===//
250
getGlobalAddressWrapper(SDValue GA,const GlobalValue * GV,SelectionDAG & DAG) const251 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
252 const GlobalValue *GV,
253 SelectionDAG &DAG) const {
254 // FIXME there is no actual debug info here
255 SDLoc dl(GA);
256
257 if (GV->getValueType()->isFunctionTy())
258 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
259
260 const auto *GVar = dyn_cast<GlobalVariable>(GV);
261 if ((GV->hasSection() && GV->getSection().startswith(".cp.")) ||
262 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
263 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
264
265 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
266 }
267
IsSmallObject(const GlobalValue * GV,const XCoreTargetLowering & XTL)268 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
269 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
270 return true;
271
272 Type *ObjType = GV->getValueType();
273 if (!ObjType->isSized())
274 return false;
275
276 auto &DL = GV->getParent()->getDataLayout();
277 unsigned ObjSize = DL.getTypeAllocSize(ObjType);
278 return ObjSize < CodeModelLargeSize && ObjSize != 0;
279 }
280
281 SDValue XCoreTargetLowering::
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const282 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
283 {
284 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
285 const GlobalValue *GV = GN->getGlobal();
286 SDLoc DL(GN);
287 int64_t Offset = GN->getOffset();
288 if (IsSmallObject(GV, *this)) {
289 // We can only fold positive offsets that are a multiple of the word size.
290 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
291 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
292 GA = getGlobalAddressWrapper(GA, GV, DAG);
293 // Handle the rest of the offset.
294 if (Offset != FoldedOffset) {
295 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, DL, MVT::i32);
296 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
297 }
298 return GA;
299 } else {
300 // Ideally we would not fold in offset with an index <= 11.
301 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
302 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
303 Ty = Type::getInt32Ty(*DAG.getContext());
304 Constant *Idx = ConstantInt::get(Ty, Offset);
305 Constant *GAI = ConstantExpr::getGetElementPtr(
306 Type::getInt8Ty(*DAG.getContext()), GA, Idx);
307 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
308 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL,
309 DAG.getEntryNode(), CP, MachinePointerInfo(), false,
310 false, false, 0);
311 }
312 }
313
314 SDValue XCoreTargetLowering::
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const315 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
316 {
317 SDLoc DL(Op);
318 auto PtrVT = getPointerTy(DAG.getDataLayout());
319 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
320 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
321
322 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, PtrVT, Result);
323 }
324
325 SDValue XCoreTargetLowering::
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const326 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
327 {
328 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
329 // FIXME there isn't really debug info here
330 SDLoc dl(CP);
331 EVT PtrVT = Op.getValueType();
332 SDValue Res;
333 if (CP->isMachineConstantPoolEntry()) {
334 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
335 CP->getAlignment(), CP->getOffset());
336 } else {
337 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
338 CP->getAlignment(), CP->getOffset());
339 }
340 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
341 }
342
getJumpTableEncoding() const343 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
344 return MachineJumpTableInfo::EK_Inline;
345 }
346
347 SDValue XCoreTargetLowering::
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const348 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
349 {
350 SDValue Chain = Op.getOperand(0);
351 SDValue Table = Op.getOperand(1);
352 SDValue Index = Op.getOperand(2);
353 SDLoc dl(Op);
354 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
355 unsigned JTI = JT->getIndex();
356 MachineFunction &MF = DAG.getMachineFunction();
357 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
358 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
359
360 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
361 if (NumEntries <= 32) {
362 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
363 }
364 assert((NumEntries >> 31) == 0);
365 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
366 DAG.getConstant(1, dl, MVT::i32));
367 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
368 ScaledIndex);
369 }
370
lowerLoadWordFromAlignedBasePlusOffset(const SDLoc & DL,SDValue Chain,SDValue Base,int64_t Offset,SelectionDAG & DAG) const371 SDValue XCoreTargetLowering::lowerLoadWordFromAlignedBasePlusOffset(
372 const SDLoc &DL, SDValue Chain, SDValue Base, int64_t Offset,
373 SelectionDAG &DAG) const {
374 auto PtrVT = getPointerTy(DAG.getDataLayout());
375 if ((Offset & 0x3) == 0) {
376 return DAG.getLoad(PtrVT, DL, Chain, Base, MachinePointerInfo(), false,
377 false, false, 0);
378 }
379 // Lower to pair of consecutive word aligned loads plus some bit shifting.
380 int32_t HighOffset = alignTo(Offset, 4);
381 int32_t LowOffset = HighOffset - 4;
382 SDValue LowAddr, HighAddr;
383 if (GlobalAddressSDNode *GASD =
384 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
385 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
386 LowOffset);
387 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
388 HighOffset);
389 } else {
390 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
391 DAG.getConstant(LowOffset, DL, MVT::i32));
392 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
393 DAG.getConstant(HighOffset, DL, MVT::i32));
394 }
395 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
396 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
397
398 SDValue Low = DAG.getLoad(PtrVT, DL, Chain, LowAddr, MachinePointerInfo(),
399 false, false, false, 0);
400 SDValue High = DAG.getLoad(PtrVT, DL, Chain, HighAddr, MachinePointerInfo(),
401 false, false, false, 0);
402 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
403 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
404 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
405 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
406 High.getValue(1));
407 SDValue Ops[] = { Result, Chain };
408 return DAG.getMergeValues(Ops, DL);
409 }
410
isWordAligned(SDValue Value,SelectionDAG & DAG)411 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
412 {
413 APInt KnownZero, KnownOne;
414 DAG.computeKnownBits(Value, KnownZero, KnownOne);
415 return KnownZero.countTrailingOnes() >= 2;
416 }
417
418 SDValue XCoreTargetLowering::
LowerLOAD(SDValue Op,SelectionDAG & DAG) const419 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
420 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
421 LoadSDNode *LD = cast<LoadSDNode>(Op);
422 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
423 "Unexpected extension type");
424 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
425 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
426 LD->getAddressSpace(),
427 LD->getAlignment()))
428 return SDValue();
429
430 auto &TD = DAG.getDataLayout();
431 unsigned ABIAlignment = TD.getABITypeAlignment(
432 LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
433 // Leave aligned load alone.
434 if (LD->getAlignment() >= ABIAlignment)
435 return SDValue();
436
437 SDValue Chain = LD->getChain();
438 SDValue BasePtr = LD->getBasePtr();
439 SDLoc DL(Op);
440
441 if (!LD->isVolatile()) {
442 const GlobalValue *GV;
443 int64_t Offset = 0;
444 if (DAG.isBaseWithConstantOffset(BasePtr) &&
445 isWordAligned(BasePtr->getOperand(0), DAG)) {
446 SDValue NewBasePtr = BasePtr->getOperand(0);
447 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
448 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
449 Offset, DAG);
450 }
451 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
452 MinAlign(GV->getAlignment(), 4) == 4) {
453 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
454 BasePtr->getValueType(0));
455 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
456 Offset, DAG);
457 }
458 }
459
460 if (LD->getAlignment() == 2) {
461 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
462 BasePtr, LD->getPointerInfo(), MVT::i16,
463 LD->isVolatile(), LD->isNonTemporal(),
464 LD->isInvariant(), 2);
465 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
466 DAG.getConstant(2, DL, MVT::i32));
467 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
468 HighAddr,
469 LD->getPointerInfo().getWithOffset(2),
470 MVT::i16, LD->isVolatile(),
471 LD->isNonTemporal(), LD->isInvariant(), 2);
472 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
473 DAG.getConstant(16, DL, MVT::i32));
474 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
475 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
476 High.getValue(1));
477 SDValue Ops[] = { Result, Chain };
478 return DAG.getMergeValues(Ops, DL);
479 }
480
481 // Lower to a call to __misaligned_load(BasePtr).
482 Type *IntPtrTy = TD.getIntPtrType(*DAG.getContext());
483 TargetLowering::ArgListTy Args;
484 TargetLowering::ArgListEntry Entry;
485
486 Entry.Ty = IntPtrTy;
487 Entry.Node = BasePtr;
488 Args.push_back(Entry);
489
490 TargetLowering::CallLoweringInfo CLI(DAG);
491 CLI.setDebugLoc(DL).setChain(Chain).setCallee(
492 CallingConv::C, IntPtrTy,
493 DAG.getExternalSymbol("__misaligned_load",
494 getPointerTy(DAG.getDataLayout())),
495 std::move(Args));
496
497 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
498 SDValue Ops[] = { CallResult.first, CallResult.second };
499 return DAG.getMergeValues(Ops, DL);
500 }
501
502 SDValue XCoreTargetLowering::
LowerSTORE(SDValue Op,SelectionDAG & DAG) const503 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
504 {
505 StoreSDNode *ST = cast<StoreSDNode>(Op);
506 assert(!ST->isTruncatingStore() && "Unexpected store type");
507 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
508 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
509 ST->getAddressSpace(),
510 ST->getAlignment())) {
511 return SDValue();
512 }
513 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
514 ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
515 // Leave aligned store alone.
516 if (ST->getAlignment() >= ABIAlignment) {
517 return SDValue();
518 }
519 SDValue Chain = ST->getChain();
520 SDValue BasePtr = ST->getBasePtr();
521 SDValue Value = ST->getValue();
522 SDLoc dl(Op);
523
524 if (ST->getAlignment() == 2) {
525 SDValue Low = Value;
526 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
527 DAG.getConstant(16, dl, MVT::i32));
528 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
529 ST->getPointerInfo(), MVT::i16,
530 ST->isVolatile(), ST->isNonTemporal(),
531 2);
532 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
533 DAG.getConstant(2, dl, MVT::i32));
534 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
535 ST->getPointerInfo().getWithOffset(2),
536 MVT::i16, ST->isVolatile(),
537 ST->isNonTemporal(), 2);
538 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
539 }
540
541 // Lower to a call to __misaligned_store(BasePtr, Value).
542 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
543 TargetLowering::ArgListTy Args;
544 TargetLowering::ArgListEntry Entry;
545
546 Entry.Ty = IntPtrTy;
547 Entry.Node = BasePtr;
548 Args.push_back(Entry);
549
550 Entry.Node = Value;
551 Args.push_back(Entry);
552
553 TargetLowering::CallLoweringInfo CLI(DAG);
554 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
555 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
556 DAG.getExternalSymbol("__misaligned_store",
557 getPointerTy(DAG.getDataLayout())),
558 std::move(Args));
559
560 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
561 return CallResult.second;
562 }
563
564 SDValue XCoreTargetLowering::
LowerSMUL_LOHI(SDValue Op,SelectionDAG & DAG) const565 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
566 {
567 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
568 "Unexpected operand to lower!");
569 SDLoc dl(Op);
570 SDValue LHS = Op.getOperand(0);
571 SDValue RHS = Op.getOperand(1);
572 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
573 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
574 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
575 LHS, RHS);
576 SDValue Lo(Hi.getNode(), 1);
577 SDValue Ops[] = { Lo, Hi };
578 return DAG.getMergeValues(Ops, dl);
579 }
580
581 SDValue XCoreTargetLowering::
LowerUMUL_LOHI(SDValue Op,SelectionDAG & DAG) const582 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
583 {
584 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
585 "Unexpected operand to lower!");
586 SDLoc dl(Op);
587 SDValue LHS = Op.getOperand(0);
588 SDValue RHS = Op.getOperand(1);
589 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
590 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
591 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
592 Zero, Zero);
593 SDValue Lo(Hi.getNode(), 1);
594 SDValue Ops[] = { Lo, Hi };
595 return DAG.getMergeValues(Ops, dl);
596 }
597
598 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
599 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
600 /// each intermediate result in the calculation must also have a single use.
601 /// If the Op is in the correct form the constituent parts are written to Mul0,
602 /// Mul1, Addend0 and Addend1.
603 static bool
isADDADDMUL(SDValue Op,SDValue & Mul0,SDValue & Mul1,SDValue & Addend0,SDValue & Addend1,bool requireIntermediatesHaveOneUse)604 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
605 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
606 {
607 if (Op.getOpcode() != ISD::ADD)
608 return false;
609 SDValue N0 = Op.getOperand(0);
610 SDValue N1 = Op.getOperand(1);
611 SDValue AddOp;
612 SDValue OtherOp;
613 if (N0.getOpcode() == ISD::ADD) {
614 AddOp = N0;
615 OtherOp = N1;
616 } else if (N1.getOpcode() == ISD::ADD) {
617 AddOp = N1;
618 OtherOp = N0;
619 } else {
620 return false;
621 }
622 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
623 return false;
624 if (OtherOp.getOpcode() == ISD::MUL) {
625 // add(add(a,b),mul(x,y))
626 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
627 return false;
628 Mul0 = OtherOp.getOperand(0);
629 Mul1 = OtherOp.getOperand(1);
630 Addend0 = AddOp.getOperand(0);
631 Addend1 = AddOp.getOperand(1);
632 return true;
633 }
634 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
635 // add(add(mul(x,y),a),b)
636 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
637 return false;
638 Mul0 = AddOp.getOperand(0).getOperand(0);
639 Mul1 = AddOp.getOperand(0).getOperand(1);
640 Addend0 = AddOp.getOperand(1);
641 Addend1 = OtherOp;
642 return true;
643 }
644 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
645 // add(add(a,mul(x,y)),b)
646 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
647 return false;
648 Mul0 = AddOp.getOperand(1).getOperand(0);
649 Mul1 = AddOp.getOperand(1).getOperand(1);
650 Addend0 = AddOp.getOperand(0);
651 Addend1 = OtherOp;
652 return true;
653 }
654 return false;
655 }
656
657 SDValue XCoreTargetLowering::
TryExpandADDWithMul(SDNode * N,SelectionDAG & DAG) const658 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
659 {
660 SDValue Mul;
661 SDValue Other;
662 if (N->getOperand(0).getOpcode() == ISD::MUL) {
663 Mul = N->getOperand(0);
664 Other = N->getOperand(1);
665 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
666 Mul = N->getOperand(1);
667 Other = N->getOperand(0);
668 } else {
669 return SDValue();
670 }
671 SDLoc dl(N);
672 SDValue LL, RL, AddendL, AddendH;
673 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
674 Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
675 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
676 Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
677 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
678 Other, DAG.getConstant(0, dl, MVT::i32));
679 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
680 Other, DAG.getConstant(1, dl, MVT::i32));
681 APInt HighMask = APInt::getHighBitsSet(64, 32);
682 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
683 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
684 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
685 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
686 // The inputs are both zero-extended.
687 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
688 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
689 AddendL, LL, RL);
690 SDValue Lo(Hi.getNode(), 1);
691 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
692 }
693 if (LHSSB > 32 && RHSSB > 32) {
694 // The inputs are both sign-extended.
695 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
696 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
697 AddendL, LL, RL);
698 SDValue Lo(Hi.getNode(), 1);
699 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
700 }
701 SDValue LH, RH;
702 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
703 Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
704 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
705 Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
706 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
707 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
708 AddendL, LL, RL);
709 SDValue Lo(Hi.getNode(), 1);
710 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
711 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
712 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
713 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
714 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
715 }
716
717 SDValue XCoreTargetLowering::
ExpandADDSUB(SDNode * N,SelectionDAG & DAG) const718 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
719 {
720 assert(N->getValueType(0) == MVT::i64 &&
721 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
722 "Unknown operand to lower!");
723
724 if (N->getOpcode() == ISD::ADD)
725 if (SDValue Result = TryExpandADDWithMul(N, DAG))
726 return Result;
727
728 SDLoc dl(N);
729
730 // Extract components
731 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
732 N->getOperand(0),
733 DAG.getConstant(0, dl, MVT::i32));
734 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
735 N->getOperand(0),
736 DAG.getConstant(1, dl, MVT::i32));
737 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
738 N->getOperand(1),
739 DAG.getConstant(0, dl, MVT::i32));
740 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
741 N->getOperand(1),
742 DAG.getConstant(1, dl, MVT::i32));
743
744 // Expand
745 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
746 XCoreISD::LSUB;
747 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
748 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
749 LHSL, RHSL, Zero);
750 SDValue Carry(Lo.getNode(), 1);
751
752 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
753 LHSH, RHSH, Carry);
754 SDValue Ignored(Hi.getNode(), 1);
755 // Merge the pieces
756 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
757 }
758
759 SDValue XCoreTargetLowering::
LowerVAARG(SDValue Op,SelectionDAG & DAG) const760 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
761 {
762 // Whist llvm does not support aggregate varargs we can ignore
763 // the possibility of the ValueType being an implicit byVal vararg.
764 SDNode *Node = Op.getNode();
765 EVT VT = Node->getValueType(0); // not an aggregate
766 SDValue InChain = Node->getOperand(0);
767 SDValue VAListPtr = Node->getOperand(1);
768 EVT PtrVT = VAListPtr.getValueType();
769 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
770 SDLoc dl(Node);
771 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
772 VAListPtr, MachinePointerInfo(SV),
773 false, false, false, 0);
774 // Increment the pointer, VAList, to the next vararg
775 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
776 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
777 dl));
778 // Store the incremented VAList to the legalized pointer
779 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
780 MachinePointerInfo(SV), false, false, 0);
781 // Load the actual argument out of the pointer VAList
782 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
783 false, false, false, 0);
784 }
785
786 SDValue XCoreTargetLowering::
LowerVASTART(SDValue Op,SelectionDAG & DAG) const787 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
788 {
789 SDLoc dl(Op);
790 // vastart stores the address of the VarArgsFrameIndex slot into the
791 // memory location argument
792 MachineFunction &MF = DAG.getMachineFunction();
793 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
794 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
795 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
796 MachinePointerInfo(), false, false, 0);
797 }
798
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const799 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
800 SelectionDAG &DAG) const {
801 // This nodes represent llvm.frameaddress on the DAG.
802 // It takes one operand, the index of the frame address to return.
803 // An index of zero corresponds to the current function's frame address.
804 // An index of one to the parent's frame address, and so on.
805 // Depths > 0 not supported yet!
806 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
807 return SDValue();
808
809 MachineFunction &MF = DAG.getMachineFunction();
810 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
811 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
812 RegInfo->getFrameRegister(MF), MVT::i32);
813 }
814
815 SDValue XCoreTargetLowering::
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const816 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
817 // This nodes represent llvm.returnaddress on the DAG.
818 // It takes one operand, the index of the return address to return.
819 // An index of zero corresponds to the current function's return address.
820 // An index of one to the parent's return address, and so on.
821 // Depths > 0 not supported yet!
822 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
823 return SDValue();
824
825 MachineFunction &MF = DAG.getMachineFunction();
826 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
827 int FI = XFI->createLRSpillSlot(MF);
828 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
829 return DAG.getLoad(
830 getPointerTy(DAG.getDataLayout()), SDLoc(Op), DAG.getEntryNode(), FIN,
831 MachinePointerInfo::getFixedStack(MF, FI), false, false, false, 0);
832 }
833
834 SDValue XCoreTargetLowering::
LowerFRAME_TO_ARGS_OFFSET(SDValue Op,SelectionDAG & DAG) const835 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
836 // This node represents offset from frame pointer to first on-stack argument.
837 // This is needed for correct stack adjustment during unwind.
838 // However, we don't know the offset until after the frame has be finalised.
839 // This is done during the XCoreFTAOElim pass.
840 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
841 }
842
843 SDValue XCoreTargetLowering::
LowerEH_RETURN(SDValue Op,SelectionDAG & DAG) const844 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
845 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
846 // This node represents 'eh_return' gcc dwarf builtin, which is used to
847 // return from exception. The general meaning is: adjust stack by OFFSET and
848 // pass execution to HANDLER.
849 MachineFunction &MF = DAG.getMachineFunction();
850 SDValue Chain = Op.getOperand(0);
851 SDValue Offset = Op.getOperand(1);
852 SDValue Handler = Op.getOperand(2);
853 SDLoc dl(Op);
854
855 // Absolute SP = (FP + FrameToArgs) + Offset
856 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
857 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
858 RegInfo->getFrameRegister(MF), MVT::i32);
859 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
860 MVT::i32);
861 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
862 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
863
864 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
865 // which leaves 2 caller saved registers, R2 & R3 for us to use.
866 unsigned StackReg = XCore::R2;
867 unsigned HandlerReg = XCore::R3;
868
869 SDValue OutChains[] = {
870 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
871 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
872 };
873
874 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
875
876 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
877 DAG.getRegister(StackReg, MVT::i32),
878 DAG.getRegister(HandlerReg, MVT::i32));
879
880 }
881
882 SDValue XCoreTargetLowering::
LowerADJUST_TRAMPOLINE(SDValue Op,SelectionDAG & DAG) const883 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
884 return Op.getOperand(0);
885 }
886
887 SDValue XCoreTargetLowering::
LowerINIT_TRAMPOLINE(SDValue Op,SelectionDAG & DAG) const888 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
889 SDValue Chain = Op.getOperand(0);
890 SDValue Trmp = Op.getOperand(1); // trampoline
891 SDValue FPtr = Op.getOperand(2); // nested function
892 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
893
894 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
895
896 // .align 4
897 // LDAPF_u10 r11, nest
898 // LDW_2rus r11, r11[0]
899 // STWSP_ru6 r11, sp[0]
900 // LDAPF_u10 r11, fptr
901 // LDW_2rus r11, r11[0]
902 // BAU_1r r11
903 // nest:
904 // .word nest
905 // fptr:
906 // .word fptr
907 SDValue OutChains[5];
908
909 SDValue Addr = Trmp;
910
911 SDLoc dl(Op);
912 OutChains[0] = DAG.getStore(Chain, dl,
913 DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
914 MachinePointerInfo(TrmpAddr), false, false, 0);
915
916 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
917 DAG.getConstant(4, dl, MVT::i32));
918 OutChains[1] = DAG.getStore(Chain, dl,
919 DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
920 MachinePointerInfo(TrmpAddr, 4), false, false, 0);
921
922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
923 DAG.getConstant(8, dl, MVT::i32));
924 OutChains[2] = DAG.getStore(Chain, dl,
925 DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
926 MachinePointerInfo(TrmpAddr, 8), false, false, 0);
927
928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
929 DAG.getConstant(12, dl, MVT::i32));
930 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
931 MachinePointerInfo(TrmpAddr, 12), false, false,
932 0);
933
934 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
935 DAG.getConstant(16, dl, MVT::i32));
936 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
937 MachinePointerInfo(TrmpAddr, 16), false, false,
938 0);
939
940 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
941 }
942
943 SDValue XCoreTargetLowering::
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const944 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
945 SDLoc DL(Op);
946 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
947 switch (IntNo) {
948 case Intrinsic::xcore_crc8:
949 EVT VT = Op.getValueType();
950 SDValue Data =
951 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
952 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
953 SDValue Crc(Data.getNode(), 1);
954 SDValue Results[] = { Crc, Data };
955 return DAG.getMergeValues(Results, DL);
956 }
957 return SDValue();
958 }
959
960 SDValue XCoreTargetLowering::
LowerATOMIC_FENCE(SDValue Op,SelectionDAG & DAG) const961 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
962 SDLoc DL(Op);
963 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
964 }
965
966 SDValue XCoreTargetLowering::
LowerATOMIC_LOAD(SDValue Op,SelectionDAG & DAG) const967 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
968 AtomicSDNode *N = cast<AtomicSDNode>(Op);
969 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
970 assert((N->getOrdering() == AtomicOrdering::Unordered ||
971 N->getOrdering() == AtomicOrdering::Monotonic) &&
972 "setInsertFencesForAtomic(true) expects unordered / monotonic");
973 if (N->getMemoryVT() == MVT::i32) {
974 if (N->getAlignment() < 4)
975 report_fatal_error("atomic load must be aligned");
976 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
977 N->getChain(), N->getBasePtr(), N->getPointerInfo(),
978 N->isVolatile(), N->isNonTemporal(), N->isInvariant(),
979 N->getAlignment(), N->getAAInfo(), N->getRanges());
980 }
981 if (N->getMemoryVT() == MVT::i16) {
982 if (N->getAlignment() < 2)
983 report_fatal_error("atomic load must be aligned");
984 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
985 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
986 N->isVolatile(), N->isNonTemporal(),
987 N->isInvariant(), N->getAlignment(), N->getAAInfo());
988 }
989 if (N->getMemoryVT() == MVT::i8)
990 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
991 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
992 N->isVolatile(), N->isNonTemporal(),
993 N->isInvariant(), N->getAlignment(), N->getAAInfo());
994 return SDValue();
995 }
996
997 SDValue XCoreTargetLowering::
LowerATOMIC_STORE(SDValue Op,SelectionDAG & DAG) const998 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
999 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1000 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1001 assert((N->getOrdering() == AtomicOrdering::Unordered ||
1002 N->getOrdering() == AtomicOrdering::Monotonic) &&
1003 "setInsertFencesForAtomic(true) expects unordered / monotonic");
1004 if (N->getMemoryVT() == MVT::i32) {
1005 if (N->getAlignment() < 4)
1006 report_fatal_error("atomic store must be aligned");
1007 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1008 N->getBasePtr(), N->getPointerInfo(),
1009 N->isVolatile(), N->isNonTemporal(),
1010 N->getAlignment(), N->getAAInfo());
1011 }
1012 if (N->getMemoryVT() == MVT::i16) {
1013 if (N->getAlignment() < 2)
1014 report_fatal_error("atomic store must be aligned");
1015 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1016 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1017 N->isVolatile(), N->isNonTemporal(),
1018 N->getAlignment(), N->getAAInfo());
1019 }
1020 if (N->getMemoryVT() == MVT::i8)
1021 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1022 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1023 N->isVolatile(), N->isNonTemporal(),
1024 N->getAlignment(), N->getAAInfo());
1025 return SDValue();
1026 }
1027
1028 //===----------------------------------------------------------------------===//
1029 // Calling Convention Implementation
1030 //===----------------------------------------------------------------------===//
1031
1032 #include "XCoreGenCallingConv.inc"
1033
1034 //===----------------------------------------------------------------------===//
1035 // Call Calling Convention Implementation
1036 //===----------------------------------------------------------------------===//
1037
1038 /// XCore call implementation
1039 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const1040 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1041 SmallVectorImpl<SDValue> &InVals) const {
1042 SelectionDAG &DAG = CLI.DAG;
1043 SDLoc &dl = CLI.DL;
1044 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1045 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1046 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1047 SDValue Chain = CLI.Chain;
1048 SDValue Callee = CLI.Callee;
1049 bool &isTailCall = CLI.IsTailCall;
1050 CallingConv::ID CallConv = CLI.CallConv;
1051 bool isVarArg = CLI.IsVarArg;
1052
1053 // XCore target does not yet support tail call optimization.
1054 isTailCall = false;
1055
1056 // For now, only CallingConv::C implemented
1057 switch (CallConv)
1058 {
1059 default:
1060 llvm_unreachable("Unsupported calling convention");
1061 case CallingConv::Fast:
1062 case CallingConv::C:
1063 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1064 Outs, OutVals, Ins, dl, DAG, InVals);
1065 }
1066 }
1067
1068 /// LowerCallResult - Lower the result values of a call into the
1069 /// appropriate copies out of appropriate physical registers / memory locations.
LowerCallResult(SDValue Chain,SDValue InFlag,const SmallVectorImpl<CCValAssign> & RVLocs,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals)1070 static SDValue LowerCallResult(SDValue Chain, SDValue InFlag,
1071 const SmallVectorImpl<CCValAssign> &RVLocs,
1072 const SDLoc &dl, SelectionDAG &DAG,
1073 SmallVectorImpl<SDValue> &InVals) {
1074 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1075 // Copy results out of physical registers.
1076 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1077 const CCValAssign &VA = RVLocs[i];
1078 if (VA.isRegLoc()) {
1079 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1080 InFlag).getValue(1);
1081 InFlag = Chain.getValue(2);
1082 InVals.push_back(Chain.getValue(0));
1083 } else {
1084 assert(VA.isMemLoc());
1085 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1086 InVals.size()));
1087 // Reserve space for this result.
1088 InVals.push_back(SDValue());
1089 }
1090 }
1091
1092 // Copy results out of memory.
1093 SmallVector<SDValue, 4> MemOpChains;
1094 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1095 int offset = ResultMemLocs[i].first;
1096 unsigned index = ResultMemLocs[i].second;
1097 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1098 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1099 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1100 InVals[index] = load;
1101 MemOpChains.push_back(load.getValue(1));
1102 }
1103
1104 // Transform all loads nodes into one single node because
1105 // all load nodes are independent of each other.
1106 if (!MemOpChains.empty())
1107 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1108
1109 return Chain;
1110 }
1111
1112 /// LowerCCCCallTo - functions arguments are copied from virtual
1113 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1114 /// CALLSEQ_END are emitted.
1115 /// TODO: isTailCall, sret.
LowerCCCCallTo(SDValue Chain,SDValue Callee,CallingConv::ID CallConv,bool isVarArg,bool isTailCall,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const1116 SDValue XCoreTargetLowering::LowerCCCCallTo(
1117 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
1118 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
1119 const SmallVectorImpl<SDValue> &OutVals,
1120 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1121 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1122
1123 // Analyze operands of the call, assigning locations to each operand.
1124 SmallVector<CCValAssign, 16> ArgLocs;
1125 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1126 *DAG.getContext());
1127
1128 // The ABI dictates there should be one stack slot available to the callee
1129 // on function entry (for saving lr).
1130 CCInfo.AllocateStack(4, 4);
1131
1132 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1133
1134 SmallVector<CCValAssign, 16> RVLocs;
1135 // Analyze return values to determine the number of bytes of stack required.
1136 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1137 *DAG.getContext());
1138 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1139 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1140
1141 // Get a count of how many bytes are to be pushed on the stack.
1142 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1143 auto PtrVT = getPointerTy(DAG.getDataLayout());
1144
1145 Chain = DAG.getCALLSEQ_START(Chain,
1146 DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
1147
1148 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1149 SmallVector<SDValue, 12> MemOpChains;
1150
1151 // Walk the register/memloc assignments, inserting copies/loads.
1152 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1153 CCValAssign &VA = ArgLocs[i];
1154 SDValue Arg = OutVals[i];
1155
1156 // Promote the value if needed.
1157 switch (VA.getLocInfo()) {
1158 default: llvm_unreachable("Unknown loc info!");
1159 case CCValAssign::Full: break;
1160 case CCValAssign::SExt:
1161 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1162 break;
1163 case CCValAssign::ZExt:
1164 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1165 break;
1166 case CCValAssign::AExt:
1167 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1168 break;
1169 }
1170
1171 // Arguments that can be passed on register must be kept at
1172 // RegsToPass vector
1173 if (VA.isRegLoc()) {
1174 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1175 } else {
1176 assert(VA.isMemLoc());
1177
1178 int Offset = VA.getLocMemOffset();
1179
1180 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1181 Chain, Arg,
1182 DAG.getConstant(Offset/4, dl,
1183 MVT::i32)));
1184 }
1185 }
1186
1187 // Transform all store nodes into one single node because
1188 // all store nodes are independent of each other.
1189 if (!MemOpChains.empty())
1190 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1191
1192 // Build a sequence of copy-to-reg nodes chained together with token
1193 // chain and flag operands which copy the outgoing args into registers.
1194 // The InFlag in necessary since all emitted instructions must be
1195 // stuck together.
1196 SDValue InFlag;
1197 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1198 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1199 RegsToPass[i].second, InFlag);
1200 InFlag = Chain.getValue(1);
1201 }
1202
1203 // If the callee is a GlobalAddress node (quite common, every direct call is)
1204 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1205 // Likewise ExternalSymbol -> TargetExternalSymbol.
1206 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1207 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1208 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1209 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1210
1211 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1212 // = Chain, Callee, Reg#1, Reg#2, ...
1213 //
1214 // Returns a chain & a flag for retval copy to use.
1215 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1216 SmallVector<SDValue, 8> Ops;
1217 Ops.push_back(Chain);
1218 Ops.push_back(Callee);
1219
1220 // Add argument registers to the end of the list so that they are
1221 // known live into the call.
1222 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1223 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1224 RegsToPass[i].second.getValueType()));
1225
1226 if (InFlag.getNode())
1227 Ops.push_back(InFlag);
1228
1229 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1230 InFlag = Chain.getValue(1);
1231
1232 // Create the CALLSEQ_END node.
1233 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
1234 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
1235 InFlag = Chain.getValue(1);
1236
1237 // Handle result values, copying them out of physregs into vregs that we
1238 // return.
1239 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1240 }
1241
1242 //===----------------------------------------------------------------------===//
1243 // Formal Arguments Calling Convention Implementation
1244 //===----------------------------------------------------------------------===//
1245
1246 namespace {
1247 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1248 }
1249
1250 /// XCore formal arguments implementation
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const1251 SDValue XCoreTargetLowering::LowerFormalArguments(
1252 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1253 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1254 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1255 switch (CallConv)
1256 {
1257 default:
1258 llvm_unreachable("Unsupported calling convention");
1259 case CallingConv::C:
1260 case CallingConv::Fast:
1261 return LowerCCCArguments(Chain, CallConv, isVarArg,
1262 Ins, dl, DAG, InVals);
1263 }
1264 }
1265
1266 /// LowerCCCArguments - transform physical registers into
1267 /// virtual registers and generate load operations for
1268 /// arguments places on the stack.
1269 /// TODO: sret
LowerCCCArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const1270 SDValue XCoreTargetLowering::LowerCCCArguments(
1271 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1272 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1273 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1274 MachineFunction &MF = DAG.getMachineFunction();
1275 MachineFrameInfo *MFI = MF.getFrameInfo();
1276 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1277 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1278
1279 // Assign locations to all of the incoming arguments.
1280 SmallVector<CCValAssign, 16> ArgLocs;
1281 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1282 *DAG.getContext());
1283
1284 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1285
1286 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1287
1288 unsigned LRSaveSize = StackSlotSize;
1289
1290 if (!isVarArg)
1291 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1292
1293 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1294 // scheduler clobbering a register before it has been copied.
1295 // The stages are:
1296 // 1. CopyFromReg (and load) arg & vararg registers.
1297 // 2. Chain CopyFromReg nodes into a TokenFactor.
1298 // 3. Memcpy 'byVal' args & push final InVals.
1299 // 4. Chain mem ops nodes into a TokenFactor.
1300 SmallVector<SDValue, 4> CFRegNode;
1301 SmallVector<ArgDataPair, 4> ArgData;
1302 SmallVector<SDValue, 4> MemOps;
1303
1304 // 1a. CopyFromReg (and load) arg registers.
1305 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1306
1307 CCValAssign &VA = ArgLocs[i];
1308 SDValue ArgIn;
1309
1310 if (VA.isRegLoc()) {
1311 // Arguments passed in registers
1312 EVT RegVT = VA.getLocVT();
1313 switch (RegVT.getSimpleVT().SimpleTy) {
1314 default:
1315 {
1316 #ifndef NDEBUG
1317 errs() << "LowerFormalArguments Unhandled argument type: "
1318 << RegVT.getEVTString() << "\n";
1319 #endif
1320 llvm_unreachable(nullptr);
1321 }
1322 case MVT::i32:
1323 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1324 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1325 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1326 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1327 }
1328 } else {
1329 // sanity check
1330 assert(VA.isMemLoc());
1331 // Load the argument to a virtual register
1332 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1333 if (ObjSize > StackSlotSize) {
1334 errs() << "LowerFormalArguments Unhandled argument type: "
1335 << EVT(VA.getLocVT()).getEVTString()
1336 << "\n";
1337 }
1338 // Create the frame index object for this incoming parameter...
1339 int FI = MFI->CreateFixedObject(ObjSize,
1340 LRSaveSize + VA.getLocMemOffset(),
1341 true);
1342
1343 // Create the SelectionDAG nodes corresponding to a load
1344 //from this parameter
1345 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1346 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1347 MachinePointerInfo::getFixedStack(MF, FI), false,
1348 false, false, 0);
1349 }
1350 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1351 ArgData.push_back(ADP);
1352 }
1353
1354 // 1b. CopyFromReg vararg registers.
1355 if (isVarArg) {
1356 // Argument registers
1357 static const MCPhysReg ArgRegs[] = {
1358 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1359 };
1360 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1361 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs);
1362 if (FirstVAReg < array_lengthof(ArgRegs)) {
1363 int offset = 0;
1364 // Save remaining registers, storing higher register numbers at a higher
1365 // address
1366 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1367 // Create a stack slot
1368 int FI = MFI->CreateFixedObject(4, offset, true);
1369 if (i == (int)FirstVAReg) {
1370 XFI->setVarArgsFrameIndex(FI);
1371 }
1372 offset -= StackSlotSize;
1373 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1374 // Move argument from phys reg -> virt reg
1375 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1376 RegInfo.addLiveIn(ArgRegs[i], VReg);
1377 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1378 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1379 // Move argument from virt reg -> stack
1380 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1381 MachinePointerInfo(), false, false, 0);
1382 MemOps.push_back(Store);
1383 }
1384 } else {
1385 // This will point to the next argument passed via stack.
1386 XFI->setVarArgsFrameIndex(
1387 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1388 true));
1389 }
1390 }
1391
1392 // 2. chain CopyFromReg nodes into a TokenFactor.
1393 if (!CFRegNode.empty())
1394 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1395
1396 // 3. Memcpy 'byVal' args & push final InVals.
1397 // Aggregates passed "byVal" need to be copied by the callee.
1398 // The callee will use a pointer to this copy, rather than the original
1399 // pointer.
1400 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1401 ArgDE = ArgData.end();
1402 ArgDI != ArgDE; ++ArgDI) {
1403 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1404 unsigned Size = ArgDI->Flags.getByValSize();
1405 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1406 // Create a new object on the stack and copy the pointee into it.
1407 int FI = MFI->CreateStackObject(Size, Align, false);
1408 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1409 InVals.push_back(FIN);
1410 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1411 DAG.getConstant(Size, dl, MVT::i32),
1412 Align, false, false, false,
1413 MachinePointerInfo(),
1414 MachinePointerInfo()));
1415 } else {
1416 InVals.push_back(ArgDI->SDV);
1417 }
1418 }
1419
1420 // 4, chain mem ops nodes into a TokenFactor.
1421 if (!MemOps.empty()) {
1422 MemOps.push_back(Chain);
1423 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1424 }
1425
1426 return Chain;
1427 }
1428
1429 //===----------------------------------------------------------------------===//
1430 // Return Value Calling Convention Implementation
1431 //===----------------------------------------------------------------------===//
1432
1433 bool XCoreTargetLowering::
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const1434 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1435 bool isVarArg,
1436 const SmallVectorImpl<ISD::OutputArg> &Outs,
1437 LLVMContext &Context) const {
1438 SmallVector<CCValAssign, 16> RVLocs;
1439 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1440 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1441 return false;
1442 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1443 return false;
1444 return true;
1445 }
1446
1447 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const1448 XCoreTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1449 bool isVarArg,
1450 const SmallVectorImpl<ISD::OutputArg> &Outs,
1451 const SmallVectorImpl<SDValue> &OutVals,
1452 const SDLoc &dl, SelectionDAG &DAG) const {
1453
1454 XCoreFunctionInfo *XFI =
1455 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1456 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1457
1458 // CCValAssign - represent the assignment of
1459 // the return value to a location
1460 SmallVector<CCValAssign, 16> RVLocs;
1461
1462 // CCState - Info about the registers and stack slot.
1463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1464 *DAG.getContext());
1465
1466 // Analyze return values.
1467 if (!isVarArg)
1468 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1469
1470 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1471
1472 SDValue Flag;
1473 SmallVector<SDValue, 4> RetOps(1, Chain);
1474
1475 // Return on XCore is always a "retsp 0"
1476 RetOps.push_back(DAG.getConstant(0, dl, MVT::i32));
1477
1478 SmallVector<SDValue, 4> MemOpChains;
1479 // Handle return values that must be copied to memory.
1480 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1481 CCValAssign &VA = RVLocs[i];
1482 if (VA.isRegLoc())
1483 continue;
1484 assert(VA.isMemLoc());
1485 if (isVarArg) {
1486 report_fatal_error("Can't return value from vararg function in memory");
1487 }
1488
1489 int Offset = VA.getLocMemOffset();
1490 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1491 // Create the frame index object for the memory location.
1492 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1493
1494 // Create a SelectionDAG node corresponding to a store
1495 // to this memory location.
1496 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1497 MemOpChains.push_back(DAG.getStore(
1498 Chain, dl, OutVals[i], FIN,
1499 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
1500 false, 0));
1501 }
1502
1503 // Transform all store nodes into one single node because
1504 // all stores are independent of each other.
1505 if (!MemOpChains.empty())
1506 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1507
1508 // Now handle return values copied to registers.
1509 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1510 CCValAssign &VA = RVLocs[i];
1511 if (!VA.isRegLoc())
1512 continue;
1513 // Copy the result values into the output registers.
1514 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1515
1516 // guarantee that all emitted copies are
1517 // stuck together, avoiding something bad
1518 Flag = Chain.getValue(1);
1519 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1520 }
1521
1522 RetOps[0] = Chain; // Update chain.
1523
1524 // Add the flag if we have it.
1525 if (Flag.getNode())
1526 RetOps.push_back(Flag);
1527
1528 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1529 }
1530
1531 //===----------------------------------------------------------------------===//
1532 // Other Lowering Code
1533 //===----------------------------------------------------------------------===//
1534
1535 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const1536 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1537 MachineBasicBlock *BB) const {
1538 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1539 DebugLoc dl = MI.getDebugLoc();
1540 assert((MI.getOpcode() == XCore::SELECT_CC) &&
1541 "Unexpected instr type to insert");
1542
1543 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1544 // control-flow pattern. The incoming instruction knows the destination vreg
1545 // to set, the condition code register to branch on, the true/false values to
1546 // select between, and a branch opcode to use.
1547 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1548 MachineFunction::iterator It = ++BB->getIterator();
1549
1550 // thisMBB:
1551 // ...
1552 // TrueVal = ...
1553 // cmpTY ccX, r1, r2
1554 // bCC copy1MBB
1555 // fallthrough --> copy0MBB
1556 MachineBasicBlock *thisMBB = BB;
1557 MachineFunction *F = BB->getParent();
1558 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1559 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1560 F->insert(It, copy0MBB);
1561 F->insert(It, sinkMBB);
1562
1563 // Transfer the remainder of BB and its successor edges to sinkMBB.
1564 sinkMBB->splice(sinkMBB->begin(), BB,
1565 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1566 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1567
1568 // Next, add the true and fallthrough blocks as its successors.
1569 BB->addSuccessor(copy0MBB);
1570 BB->addSuccessor(sinkMBB);
1571
1572 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1573 .addReg(MI.getOperand(1).getReg())
1574 .addMBB(sinkMBB);
1575
1576 // copy0MBB:
1577 // %FalseValue = ...
1578 // # fallthrough to sinkMBB
1579 BB = copy0MBB;
1580
1581 // Update machine-CFG edges
1582 BB->addSuccessor(sinkMBB);
1583
1584 // sinkMBB:
1585 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1586 // ...
1587 BB = sinkMBB;
1588 BuildMI(*BB, BB->begin(), dl, TII.get(XCore::PHI), MI.getOperand(0).getReg())
1589 .addReg(MI.getOperand(3).getReg())
1590 .addMBB(copy0MBB)
1591 .addReg(MI.getOperand(2).getReg())
1592 .addMBB(thisMBB);
1593
1594 MI.eraseFromParent(); // The pseudo instruction is gone now.
1595 return BB;
1596 }
1597
1598 //===----------------------------------------------------------------------===//
1599 // Target Optimization Hooks
1600 //===----------------------------------------------------------------------===//
1601
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const1602 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1603 DAGCombinerInfo &DCI) const {
1604 SelectionDAG &DAG = DCI.DAG;
1605 SDLoc dl(N);
1606 switch (N->getOpcode()) {
1607 default: break;
1608 case ISD::INTRINSIC_VOID:
1609 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1610 case Intrinsic::xcore_outt:
1611 case Intrinsic::xcore_outct:
1612 case Intrinsic::xcore_chkct: {
1613 SDValue OutVal = N->getOperand(3);
1614 // These instructions ignore the high bits.
1615 if (OutVal.hasOneUse()) {
1616 unsigned BitWidth = OutVal.getValueSizeInBits();
1617 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1618 APInt KnownZero, KnownOne;
1619 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1620 !DCI.isBeforeLegalizeOps());
1621 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1622 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1623 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1624 TLO))
1625 DCI.CommitTargetLoweringOpt(TLO);
1626 }
1627 break;
1628 }
1629 case Intrinsic::xcore_setpt: {
1630 SDValue Time = N->getOperand(3);
1631 // This instruction ignores the high bits.
1632 if (Time.hasOneUse()) {
1633 unsigned BitWidth = Time.getValueSizeInBits();
1634 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1635 APInt KnownZero, KnownOne;
1636 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1637 !DCI.isBeforeLegalizeOps());
1638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1639 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1640 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1641 TLO))
1642 DCI.CommitTargetLoweringOpt(TLO);
1643 }
1644 break;
1645 }
1646 }
1647 break;
1648 case XCoreISD::LADD: {
1649 SDValue N0 = N->getOperand(0);
1650 SDValue N1 = N->getOperand(1);
1651 SDValue N2 = N->getOperand(2);
1652 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1653 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1654 EVT VT = N0.getValueType();
1655
1656 // canonicalize constant to RHS
1657 if (N0C && !N1C)
1658 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1659
1660 // fold (ladd 0, 0, x) -> 0, x & 1
1661 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1662 SDValue Carry = DAG.getConstant(0, dl, VT);
1663 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1664 DAG.getConstant(1, dl, VT));
1665 SDValue Ops[] = { Result, Carry };
1666 return DAG.getMergeValues(Ops, dl);
1667 }
1668
1669 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1670 // low bit set
1671 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1672 APInt KnownZero, KnownOne;
1673 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1674 VT.getSizeInBits() - 1);
1675 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1676 if ((KnownZero & Mask) == Mask) {
1677 SDValue Carry = DAG.getConstant(0, dl, VT);
1678 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1679 SDValue Ops[] = { Result, Carry };
1680 return DAG.getMergeValues(Ops, dl);
1681 }
1682 }
1683 }
1684 break;
1685 case XCoreISD::LSUB: {
1686 SDValue N0 = N->getOperand(0);
1687 SDValue N1 = N->getOperand(1);
1688 SDValue N2 = N->getOperand(2);
1689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1691 EVT VT = N0.getValueType();
1692
1693 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1694 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1695 APInt KnownZero, KnownOne;
1696 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1697 VT.getSizeInBits() - 1);
1698 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1699 if ((KnownZero & Mask) == Mask) {
1700 SDValue Borrow = N2;
1701 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1702 DAG.getConstant(0, dl, VT), N2);
1703 SDValue Ops[] = { Result, Borrow };
1704 return DAG.getMergeValues(Ops, dl);
1705 }
1706 }
1707
1708 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1709 // low bit set
1710 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1711 APInt KnownZero, KnownOne;
1712 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1713 VT.getSizeInBits() - 1);
1714 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1715 if ((KnownZero & Mask) == Mask) {
1716 SDValue Borrow = DAG.getConstant(0, dl, VT);
1717 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1718 SDValue Ops[] = { Result, Borrow };
1719 return DAG.getMergeValues(Ops, dl);
1720 }
1721 }
1722 }
1723 break;
1724 case XCoreISD::LMUL: {
1725 SDValue N0 = N->getOperand(0);
1726 SDValue N1 = N->getOperand(1);
1727 SDValue N2 = N->getOperand(2);
1728 SDValue N3 = N->getOperand(3);
1729 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1730 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1731 EVT VT = N0.getValueType();
1732 // Canonicalize multiplicative constant to RHS. If both multiplicative
1733 // operands are constant canonicalize smallest to RHS.
1734 if ((N0C && !N1C) ||
1735 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1736 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1737 N1, N0, N2, N3);
1738
1739 // lmul(x, 0, a, b)
1740 if (N1C && N1C->isNullValue()) {
1741 // If the high result is unused fold to add(a, b)
1742 if (N->hasNUsesOfValue(0, 0)) {
1743 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1744 SDValue Ops[] = { Lo, Lo };
1745 return DAG.getMergeValues(Ops, dl);
1746 }
1747 // Otherwise fold to ladd(a, b, 0)
1748 SDValue Result =
1749 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1750 SDValue Carry(Result.getNode(), 1);
1751 SDValue Ops[] = { Carry, Result };
1752 return DAG.getMergeValues(Ops, dl);
1753 }
1754 }
1755 break;
1756 case ISD::ADD: {
1757 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1758 // lmul(x, y, a, b). The high result of lmul will be ignored.
1759 // This is only profitable if the intermediate results are unused
1760 // elsewhere.
1761 SDValue Mul0, Mul1, Addend0, Addend1;
1762 if (N->getValueType(0) == MVT::i32 &&
1763 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1764 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1765 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1766 Mul1, Addend0, Addend1);
1767 SDValue Result(Ignored.getNode(), 1);
1768 return Result;
1769 }
1770 APInt HighMask = APInt::getHighBitsSet(64, 32);
1771 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1772 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1773 // before type legalization as it is messy to match the operands after
1774 // that.
1775 if (N->getValueType(0) == MVT::i64 &&
1776 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1777 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1778 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1779 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1780 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1781 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1782 Mul0, DAG.getConstant(0, dl, MVT::i32));
1783 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1784 Mul1, DAG.getConstant(0, dl, MVT::i32));
1785 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1786 Addend0, DAG.getConstant(0, dl, MVT::i32));
1787 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1788 Addend1, DAG.getConstant(0, dl, MVT::i32));
1789 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1790 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1791 Addend0L, Addend1L);
1792 SDValue Lo(Hi.getNode(), 1);
1793 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1794 }
1795 }
1796 break;
1797 case ISD::STORE: {
1798 // Replace unaligned store of unaligned load with memmove.
1799 StoreSDNode *ST = cast<StoreSDNode>(N);
1800 if (!DCI.isBeforeLegalize() ||
1801 allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1802 ST->getAddressSpace(),
1803 ST->getAlignment()) ||
1804 ST->isVolatile() || ST->isIndexed()) {
1805 break;
1806 }
1807 SDValue Chain = ST->getChain();
1808
1809 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1810 assert((StoreBits % 8) == 0 &&
1811 "Store size in bits must be a multiple of 8");
1812 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
1813 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1814 unsigned Alignment = ST->getAlignment();
1815 if (Alignment >= ABIAlignment) {
1816 break;
1817 }
1818
1819 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1820 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1821 LD->getAlignment() == Alignment &&
1822 !LD->isVolatile() && !LD->isIndexed() &&
1823 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1824 bool isTail = isInTailCallPosition(DAG, ST, Chain);
1825 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1826 LD->getBasePtr(),
1827 DAG.getConstant(StoreBits/8, dl, MVT::i32),
1828 Alignment, false, isTail, ST->getPointerInfo(),
1829 LD->getPointerInfo());
1830 }
1831 }
1832 break;
1833 }
1834 }
1835 return SDValue();
1836 }
1837
computeKnownBitsForTargetNode(const SDValue Op,APInt & KnownZero,APInt & KnownOne,const SelectionDAG & DAG,unsigned Depth) const1838 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1839 APInt &KnownZero,
1840 APInt &KnownOne,
1841 const SelectionDAG &DAG,
1842 unsigned Depth) const {
1843 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1844 switch (Op.getOpcode()) {
1845 default: break;
1846 case XCoreISD::LADD:
1847 case XCoreISD::LSUB:
1848 if (Op.getResNo() == 1) {
1849 // Top bits of carry / borrow are clear.
1850 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1851 KnownZero.getBitWidth() - 1);
1852 }
1853 break;
1854 case ISD::INTRINSIC_W_CHAIN:
1855 {
1856 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1857 switch (IntNo) {
1858 case Intrinsic::xcore_getts:
1859 // High bits are known to be zero.
1860 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1861 KnownZero.getBitWidth() - 16);
1862 break;
1863 case Intrinsic::xcore_int:
1864 case Intrinsic::xcore_inct:
1865 // High bits are known to be zero.
1866 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1867 KnownZero.getBitWidth() - 8);
1868 break;
1869 case Intrinsic::xcore_testct:
1870 // Result is either 0 or 1.
1871 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1872 KnownZero.getBitWidth() - 1);
1873 break;
1874 case Intrinsic::xcore_testwct:
1875 // Result is in the range 0 - 4.
1876 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1877 KnownZero.getBitWidth() - 3);
1878 break;
1879 }
1880 }
1881 break;
1882 }
1883 }
1884
1885 //===----------------------------------------------------------------------===//
1886 // Addressing mode description hooks
1887 //===----------------------------------------------------------------------===//
1888
isImmUs(int64_t val)1889 static inline bool isImmUs(int64_t val)
1890 {
1891 return (val >= 0 && val <= 11);
1892 }
1893
isImmUs2(int64_t val)1894 static inline bool isImmUs2(int64_t val)
1895 {
1896 return (val%2 == 0 && isImmUs(val/2));
1897 }
1898
isImmUs4(int64_t val)1899 static inline bool isImmUs4(int64_t val)
1900 {
1901 return (val%4 == 0 && isImmUs(val/4));
1902 }
1903
1904 /// isLegalAddressingMode - Return true if the addressing mode represented
1905 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const1906 bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1907 const AddrMode &AM, Type *Ty,
1908 unsigned AS) const {
1909 if (Ty->getTypeID() == Type::VoidTyID)
1910 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1911
1912 unsigned Size = DL.getTypeAllocSize(Ty);
1913 if (AM.BaseGV) {
1914 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1915 AM.BaseOffs%4 == 0;
1916 }
1917
1918 switch (Size) {
1919 case 1:
1920 // reg + imm
1921 if (AM.Scale == 0) {
1922 return isImmUs(AM.BaseOffs);
1923 }
1924 // reg + reg
1925 return AM.Scale == 1 && AM.BaseOffs == 0;
1926 case 2:
1927 case 3:
1928 // reg + imm
1929 if (AM.Scale == 0) {
1930 return isImmUs2(AM.BaseOffs);
1931 }
1932 // reg + reg<<1
1933 return AM.Scale == 2 && AM.BaseOffs == 0;
1934 default:
1935 // reg + imm
1936 if (AM.Scale == 0) {
1937 return isImmUs4(AM.BaseOffs);
1938 }
1939 // reg + reg<<2
1940 return AM.Scale == 4 && AM.BaseOffs == 0;
1941 }
1942 }
1943
1944 //===----------------------------------------------------------------------===//
1945 // XCore Inline Assembly Support
1946 //===----------------------------------------------------------------------===//
1947
1948 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const1949 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1950 StringRef Constraint,
1951 MVT VT) const {
1952 if (Constraint.size() == 1) {
1953 switch (Constraint[0]) {
1954 default : break;
1955 case 'r':
1956 return std::make_pair(0U, &XCore::GRRegsRegClass);
1957 }
1958 }
1959 // Use the default implementation in TargetLowering to convert the register
1960 // constraint into a member of a register class.
1961 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1962 }
1963