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