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