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