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