Remove unused STL header includes.
[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 #define DEBUG_TYPE "xcore-lower"
15
16 #include "XCoreISelLowering.h"
17 #include "XCoreMachineFunctionInfo.h"
18 #include "XCore.h"
19 #include "XCoreTargetObjectFile.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreSubtarget.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/GlobalAlias.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAGISel.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/VectorExtras.h"
40 using namespace llvm;
41
42 const char *XCoreTargetLowering::
43 getTargetNodeName(unsigned Opcode) const
44 {
45   switch (Opcode)
46   {
47     case XCoreISD::BL                : return "XCoreISD::BL";
48     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
49     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
50     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
51     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
52     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
53     case XCoreISD::LADD              : return "XCoreISD::LADD";
54     case XCoreISD::LSUB              : return "XCoreISD::LSUB";
55     case XCoreISD::LMUL              : return "XCoreISD::LMUL";
56     case XCoreISD::MACCU             : return "XCoreISD::MACCU";
57     case XCoreISD::MACCS             : return "XCoreISD::MACCS";
58     case XCoreISD::BR_JT             : return "XCoreISD::BR_JT";
59     case XCoreISD::BR_JT32           : return "XCoreISD::BR_JT32";
60     default                          : return NULL;
61   }
62 }
63
64 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
65   : TargetLowering(XTM, new XCoreTargetObjectFile()),
66     TM(XTM),
67     Subtarget(*XTM.getSubtargetImpl()) {
68
69   // Set up the register classes.
70   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
71
72   // Compute derived properties from the register classes
73   computeRegisterProperties();
74
75   // Division is expensive
76   setIntDivIsCheap(false);
77
78   setStackPointerRegisterToSaveRestore(XCore::SP);
79
80   setSchedulingPreference(Sched::RegPressure);
81
82   // Use i32 for setcc operations results (slt, sgt, ...).
83   setBooleanContents(ZeroOrOneBooleanContent);
84
85   // XCore does not have the NodeTypes below.
86   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
87   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
88   setOperationAction(ISD::ADDC, MVT::i32, Expand);
89   setOperationAction(ISD::ADDE, MVT::i32, Expand);
90   setOperationAction(ISD::SUBC, MVT::i32, Expand);
91   setOperationAction(ISD::SUBE, MVT::i32, Expand);
92
93   // Stop the combiner recombining select and set_cc
94   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
95
96   // 64bit
97   setOperationAction(ISD::ADD, MVT::i64, Custom);
98   setOperationAction(ISD::SUB, MVT::i64, Custom);
99   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
100   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
101   setOperationAction(ISD::MULHS, MVT::i32, Expand);
102   setOperationAction(ISD::MULHU, MVT::i32, Expand);
103   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
104   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
105   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
106
107   // Bit Manipulation
108   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
109   setOperationAction(ISD::ROTL , MVT::i32, Expand);
110   setOperationAction(ISD::ROTR , MVT::i32, Expand);
111
112   setOperationAction(ISD::TRAP, MVT::Other, Legal);
113
114   // Jump tables.
115   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
116
117   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
118   setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
119
120   // Thread Local Storage
121   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
122
123   // Conversion of i64 -> double produces constantpool nodes
124   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
125
126   // Loads
127   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
128   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
129   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
130
131   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
132   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
133
134   // Custom expand misaligned loads / stores.
135   setOperationAction(ISD::LOAD, MVT::i32, Custom);
136   setOperationAction(ISD::STORE, MVT::i32, Custom);
137
138   // Varargs
139   setOperationAction(ISD::VAEND, MVT::Other, Expand);
140   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
141   setOperationAction(ISD::VAARG, MVT::Other, Custom);
142   setOperationAction(ISD::VASTART, MVT::Other, Custom);
143
144   // Dynamic stack
145   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
146   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
147   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
148
149   // TRAMPOLINE is custom lowered.
150   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
151
152   maxStoresPerMemset = maxStoresPerMemsetOptSize = 4;
153   maxStoresPerMemmove = maxStoresPerMemmoveOptSize
154     = maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 2;
155
156   // We have target-specific dag combine patterns for the following nodes:
157   setTargetDAGCombine(ISD::STORE);
158   setTargetDAGCombine(ISD::ADD);
159 }
160
161 SDValue XCoreTargetLowering::
162 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
163   switch (Op.getOpcode())
164   {
165   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
166   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
167   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
168   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
169   case ISD::BR_JT:            return LowerBR_JT(Op, DAG);
170   case ISD::LOAD:             return LowerLOAD(Op, DAG);
171   case ISD::STORE:            return LowerSTORE(Op, DAG);
172   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
173   case ISD::VAARG:            return LowerVAARG(Op, DAG);
174   case ISD::VASTART:          return LowerVASTART(Op, DAG);
175   case ISD::SMUL_LOHI:        return LowerSMUL_LOHI(Op, DAG);
176   case ISD::UMUL_LOHI:        return LowerUMUL_LOHI(Op, DAG);
177   // FIXME: Remove these when LegalizeDAGTypes lands.
178   case ISD::ADD:
179   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
180   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
181   case ISD::TRAMPOLINE:       return LowerTRAMPOLINE(Op, DAG);
182   default:
183     llvm_unreachable("unimplemented operand");
184     return SDValue();
185   }
186 }
187
188 /// ReplaceNodeResults - Replace the results of node with an illegal result
189 /// type with new values built out of custom code.
190 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
191                                              SmallVectorImpl<SDValue>&Results,
192                                              SelectionDAG &DAG) const {
193   switch (N->getOpcode()) {
194   default:
195     llvm_unreachable("Don't know how to custom expand this!");
196     return;
197   case ISD::ADD:
198   case ISD::SUB:
199     Results.push_back(ExpandADDSUB(N, DAG));
200     return;
201   }
202 }
203
204 /// getFunctionAlignment - Return the Log2 alignment of this function.
205 unsigned XCoreTargetLowering::
206 getFunctionAlignment(const Function *) const {
207   return 1;
208 }
209
210 //===----------------------------------------------------------------------===//
211 //  Misc Lower Operation implementation
212 //===----------------------------------------------------------------------===//
213
214 SDValue XCoreTargetLowering::
215 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
216 {
217   DebugLoc dl = Op.getDebugLoc();
218   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
219                              Op.getOperand(3), Op.getOperand(4));
220   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
221                      Op.getOperand(1));
222 }
223
224 SDValue XCoreTargetLowering::
225 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
226                         SelectionDAG &DAG) const
227 {
228   // FIXME there is no actual debug info here
229   DebugLoc dl = GA.getDebugLoc();
230   if (isa<Function>(GV)) {
231     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
232   }
233   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
234   if (!GVar) {
235     // If GV is an alias then use the aliasee to determine constness
236     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
237       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
238   }
239   bool isConst = GVar && GVar->isConstant();
240   if (isConst) {
241     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
242   }
243   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
244 }
245
246 SDValue XCoreTargetLowering::
247 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
248 {
249   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
250   SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
251   // If it's a debug information descriptor, don't mess with it.
252   if (DAG.isVerifiedDebugInfoDesc(Op))
253     return GA;
254   return getGlobalAddressWrapper(GA, GV, DAG);
255 }
256
257 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
258   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
259                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
260 }
261
262 static inline bool isZeroLengthArray(const Type *Ty) {
263   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
264   return AT && (AT->getNumElements() == 0);
265 }
266
267 SDValue XCoreTargetLowering::
268 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
269 {
270   // FIXME there isn't really debug info here
271   DebugLoc dl = Op.getDebugLoc();
272   // transform to label + getid() * size
273   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
274   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
275   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
276   if (!GVar) {
277     // If GV is an alias then use the aliasee to determine size
278     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
279       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
280   }
281   if (! GVar) {
282     llvm_unreachable("Thread local object not a GlobalVariable?");
283     return SDValue();
284   }
285   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
286   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
287 #ifndef NDEBUG
288     errs() << "Size of thread local object " << GVar->getName()
289            << " is unknown\n";
290 #endif
291     llvm_unreachable(0);
292   }
293   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
294   const TargetData *TD = TM.getTargetData();
295   unsigned Size = TD->getTypeAllocSize(Ty);
296   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
297                        DAG.getConstant(Size, MVT::i32));
298   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
299 }
300
301 SDValue XCoreTargetLowering::
302 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
303 {
304   DebugLoc DL = Op.getDebugLoc();
305
306   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
307   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
308
309   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
310 }
311
312 SDValue XCoreTargetLowering::
313 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
314 {
315   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
316   // FIXME there isn't really debug info here
317   DebugLoc dl = CP->getDebugLoc();
318   EVT PtrVT = Op.getValueType();
319   SDValue Res;
320   if (CP->isMachineConstantPoolEntry()) {
321     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
322                                     CP->getAlignment());
323   } else {
324     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
325                                     CP->getAlignment());
326   }
327   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
328 }
329
330 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
331   return MachineJumpTableInfo::EK_Inline;
332 }
333
334 SDValue XCoreTargetLowering::
335 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
336 {
337   SDValue Chain = Op.getOperand(0);
338   SDValue Table = Op.getOperand(1);
339   SDValue Index = Op.getOperand(2);
340   DebugLoc dl = Op.getDebugLoc();
341   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
342   unsigned JTI = JT->getIndex();
343   MachineFunction &MF = DAG.getMachineFunction();
344   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
345   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
346
347   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
348   if (NumEntries <= 32) {
349     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
350   }
351   assert((NumEntries >> 31) == 0);
352   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
353                                     DAG.getConstant(1, MVT::i32));
354   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
355                      ScaledIndex);
356 }
357
358 static bool
359 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
360                                     int64_t &Offset)
361 {
362   if (Addr.getOpcode() != ISD::ADD) {
363     return false;
364   }
365   ConstantSDNode *CN = 0;
366   if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
367     return false;
368   }
369   int64_t off = CN->getSExtValue();
370   const SDValue &Base = Addr.getOperand(0);
371   const SDValue *Root = &Base;
372   if (Base.getOpcode() == ISD::ADD &&
373       Base.getOperand(1).getOpcode() == ISD::SHL) {
374     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
375                                                       .getOperand(1));
376     if (CN && (CN->getSExtValue() >= 2)) {
377       Root = &Base.getOperand(0);
378     }
379   }
380   if (isa<FrameIndexSDNode>(*Root)) {
381     // All frame indicies are word aligned
382     AlignedBase = Base;
383     Offset = off;
384     return true;
385   }
386   if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
387       Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
388     // All dp / cp relative addresses are word aligned
389     AlignedBase = Base;
390     Offset = off;
391     return true;
392   }
393   return false;
394 }
395
396 SDValue XCoreTargetLowering::
397 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
398   LoadSDNode *LD = cast<LoadSDNode>(Op);
399   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
400          "Unexpected extension type");
401   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
402   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
403     return SDValue();
404
405   unsigned ABIAlignment = getTargetData()->
406     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
407   // Leave aligned load alone.
408   if (LD->getAlignment() >= ABIAlignment)
409     return SDValue();
410
411   SDValue Chain = LD->getChain();
412   SDValue BasePtr = LD->getBasePtr();
413   DebugLoc DL = Op.getDebugLoc();
414
415   SDValue Base;
416   int64_t Offset;
417   if (!LD->isVolatile() &&
418       IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
419     if (Offset % 4 == 0) {
420       // We've managed to infer better alignment information than the load
421       // already has. Use an aligned load.
422       //
423       return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
424                          MachinePointerInfo(),
425                          false, false, 0);
426     }
427     // Lower to
428     // ldw low, base[offset >> 2]
429     // ldw high, base[(offset >> 2) + 1]
430     // shr low_shifted, low, (offset & 0x3) * 8
431     // shl high_shifted, high, 32 - (offset & 0x3) * 8
432     // or result, low_shifted, high_shifted
433     SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
434     SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
435     SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
436     SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
437
438     SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
439     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
440
441     SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
442                               LowAddr, MachinePointerInfo(), false, false, 0);
443     SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
444                                HighAddr, MachinePointerInfo(), false, false, 0);
445     SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
446     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
447     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
448     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
449                              High.getValue(1));
450     SDValue Ops[] = { Result, Chain };
451     return DAG.getMergeValues(Ops, 2, DL);
452   }
453
454   if (LD->getAlignment() == 2) {
455     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
456                                  BasePtr, LD->getPointerInfo(), MVT::i16,
457                                  LD->isVolatile(), LD->isNonTemporal(), 2);
458     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
459                                    DAG.getConstant(2, MVT::i32));
460     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
461                                   HighAddr,
462                                   LD->getPointerInfo().getWithOffset(2),
463                                   MVT::i16, LD->isVolatile(),
464                                   LD->isNonTemporal(), 2);
465     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
466                                       DAG.getConstant(16, MVT::i32));
467     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
468     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
469                              High.getValue(1));
470     SDValue Ops[] = { Result, Chain };
471     return DAG.getMergeValues(Ops, 2, DL);
472   }
473
474   // Lower to a call to __misaligned_load(BasePtr).
475   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
476   TargetLowering::ArgListTy Args;
477   TargetLowering::ArgListEntry Entry;
478
479   Entry.Ty = IntPtrTy;
480   Entry.Node = BasePtr;
481   Args.push_back(Entry);
482
483   std::pair<SDValue, SDValue> CallResult =
484         LowerCallTo(Chain, IntPtrTy, false, false,
485                     false, false, 0, CallingConv::C, false,
486                     /*isReturnValueUsed=*/true,
487                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
488                     Args, DAG, DL);
489
490   SDValue Ops[] =
491     { CallResult.first, CallResult.second };
492
493   return DAG.getMergeValues(Ops, 2, DL);
494 }
495
496 SDValue XCoreTargetLowering::
497 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
498 {
499   StoreSDNode *ST = cast<StoreSDNode>(Op);
500   assert(!ST->isTruncatingStore() && "Unexpected store type");
501   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
502   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
503     return SDValue();
504   }
505   unsigned ABIAlignment = getTargetData()->
506     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
507   // Leave aligned store alone.
508   if (ST->getAlignment() >= ABIAlignment) {
509     return SDValue();
510   }
511   SDValue Chain = ST->getChain();
512   SDValue BasePtr = ST->getBasePtr();
513   SDValue Value = ST->getValue();
514   DebugLoc dl = Op.getDebugLoc();
515
516   if (ST->getAlignment() == 2) {
517     SDValue Low = Value;
518     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
519                                       DAG.getConstant(16, MVT::i32));
520     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
521                                          ST->getPointerInfo(), MVT::i16,
522                                          ST->isVolatile(), ST->isNonTemporal(),
523                                          2);
524     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
525                                    DAG.getConstant(2, MVT::i32));
526     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
527                                           ST->getPointerInfo().getWithOffset(2),
528                                           MVT::i16, ST->isVolatile(),
529                                           ST->isNonTemporal(), 2);
530     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
531   }
532
533   // Lower to a call to __misaligned_store(BasePtr, Value).
534   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
535   TargetLowering::ArgListTy Args;
536   TargetLowering::ArgListEntry Entry;
537
538   Entry.Ty = IntPtrTy;
539   Entry.Node = BasePtr;
540   Args.push_back(Entry);
541
542   Entry.Node = Value;
543   Args.push_back(Entry);
544
545   std::pair<SDValue, SDValue> CallResult =
546         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
547                     false, false, 0, CallingConv::C, false,
548                     /*isReturnValueUsed=*/true,
549                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
550                     Args, DAG, dl);
551
552   return CallResult.second;
553 }
554
555 SDValue XCoreTargetLowering::
556 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
557 {
558   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
559          "Unexpected operand to lower!");
560   DebugLoc dl = Op.getDebugLoc();
561   SDValue LHS = Op.getOperand(0);
562   SDValue RHS = Op.getOperand(1);
563   SDValue Zero = DAG.getConstant(0, MVT::i32);
564   SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
565                            DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
566                            LHS, RHS);
567   SDValue Lo(Hi.getNode(), 1);
568   SDValue Ops[] = { Lo, Hi };
569   return DAG.getMergeValues(Ops, 2, dl);
570 }
571
572 SDValue XCoreTargetLowering::
573 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
574 {
575   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
576          "Unexpected operand to lower!");
577   DebugLoc dl = Op.getDebugLoc();
578   SDValue LHS = Op.getOperand(0);
579   SDValue RHS = Op.getOperand(1);
580   SDValue Zero = DAG.getConstant(0, MVT::i32);
581   SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
582                            DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
583                            Zero, Zero);
584   SDValue Lo(Hi.getNode(), 1);
585   SDValue Ops[] = { Lo, Hi };
586   return DAG.getMergeValues(Ops, 2, dl);
587 }
588
589 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
590 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
591 /// each intermediate result in the calculation must also have a single use.
592 /// If the Op is in the correct form the constituent parts are written to Mul0,
593 /// Mul1, Addend0 and Addend1.
594 static bool
595 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
596             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
597 {
598   if (Op.getOpcode() != ISD::ADD)
599     return false;
600   SDValue N0 = Op.getOperand(0);
601   SDValue N1 = Op.getOperand(1);
602   SDValue AddOp;
603   SDValue OtherOp;
604   if (N0.getOpcode() == ISD::ADD) {
605     AddOp = N0;
606     OtherOp = N1;
607   } else if (N1.getOpcode() == ISD::ADD) {
608     AddOp = N1;
609     OtherOp = N0;
610   } else {
611     return false;
612   }
613   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
614     return false;
615   if (OtherOp.getOpcode() == ISD::MUL) {
616     // add(add(a,b),mul(x,y))
617     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
618       return false;
619     Mul0 = OtherOp.getOperand(0);
620     Mul1 = OtherOp.getOperand(1);
621     Addend0 = AddOp.getOperand(0);
622     Addend1 = AddOp.getOperand(1);
623     return true;
624   }
625   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
626     // add(add(mul(x,y),a),b)
627     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
628       return false;
629     Mul0 = AddOp.getOperand(0).getOperand(0);
630     Mul1 = AddOp.getOperand(0).getOperand(1);
631     Addend0 = AddOp.getOperand(1);
632     Addend1 = OtherOp;
633     return true;
634   }
635   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
636     // add(add(a,mul(x,y)),b)
637     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
638       return false;
639     Mul0 = AddOp.getOperand(1).getOperand(0);
640     Mul1 = AddOp.getOperand(1).getOperand(1);
641     Addend0 = AddOp.getOperand(0);
642     Addend1 = OtherOp;
643     return true;
644   }
645   return false;
646 }
647
648 SDValue XCoreTargetLowering::
649 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
650 {
651   SDValue Mul;
652   SDValue Other;
653   if (N->getOperand(0).getOpcode() == ISD::MUL) {
654     Mul = N->getOperand(0);
655     Other = N->getOperand(1);
656   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
657     Mul = N->getOperand(1);
658     Other = N->getOperand(0);
659   } else {
660     return SDValue();
661   }
662   DebugLoc dl = N->getDebugLoc();
663   SDValue LL, RL, AddendL, AddendH;
664   LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
665                    Mul.getOperand(0),  DAG.getConstant(0, MVT::i32));
666   RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
667                    Mul.getOperand(1),  DAG.getConstant(0, MVT::i32));
668   AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
669                         Other,  DAG.getConstant(0, MVT::i32));
670   AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
671                         Other,  DAG.getConstant(1, MVT::i32));
672   APInt HighMask = APInt::getHighBitsSet(64, 32);
673   unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
674   unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
675   if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
676       DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
677     // The inputs are both zero-extended.
678     SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
679                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
680                              AddendL, LL, RL);
681     SDValue Lo(Hi.getNode(), 1);
682     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
683   }
684   if (LHSSB > 32 && RHSSB > 32) {
685     // The inputs are both sign-extended.
686     SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
687                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
688                              AddendL, LL, RL);
689     SDValue Lo(Hi.getNode(), 1);
690     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
691   }
692   SDValue LH, RH;
693   LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
694                    Mul.getOperand(0),  DAG.getConstant(1, MVT::i32));
695   RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
696                    Mul.getOperand(1),  DAG.getConstant(1, MVT::i32));
697   SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
698                            DAG.getVTList(MVT::i32, MVT::i32), AddendH,
699                            AddendL, LL, RL);
700   SDValue Lo(Hi.getNode(), 1);
701   RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
702   LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
703   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
704   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
705   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
706 }
707
708 SDValue XCoreTargetLowering::
709 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
710 {
711   assert(N->getValueType(0) == MVT::i64 &&
712          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
713         "Unknown operand to lower!");
714
715   if (N->getOpcode() == ISD::ADD) {
716     SDValue Result = TryExpandADDWithMul(N, DAG);
717     if (Result.getNode() != 0)
718       return Result;
719   }
720
721   DebugLoc dl = N->getDebugLoc();
722
723   // Extract components
724   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
725                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
726   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
727                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
728   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
729                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
730   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
731                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
732
733   // Expand
734   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
735                                                    XCoreISD::LSUB;
736   SDValue Zero = DAG.getConstant(0, MVT::i32);
737   SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
738                                   LHSL, RHSL, Zero);
739   SDValue Lo(Carry.getNode(), 1);
740
741   SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
742                                   LHSH, RHSH, Carry);
743   SDValue Hi(Ignored.getNode(), 1);
744   // Merge the pieces
745   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
746 }
747
748 SDValue XCoreTargetLowering::
749 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
750 {
751   llvm_unreachable("unimplemented");
752   // FIX Arguments passed by reference need a extra dereference.
753   SDNode *Node = Op.getNode();
754   DebugLoc dl = Node->getDebugLoc();
755   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
756   EVT VT = Node->getValueType(0);
757   SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
758                                Node->getOperand(1), MachinePointerInfo(V),
759                                false, false, 0);
760   // Increment the pointer, VAList, to the next vararg
761   SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
762                      DAG.getConstant(VT.getSizeInBits(),
763                                      getPointerTy()));
764   // Store the incremented VAList to the legalized pointer
765   Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1),
766                       MachinePointerInfo(V), false, false, 0);
767   // Load the actual argument out of the pointer VAList
768   return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
769                      false, false, 0);
770 }
771
772 SDValue XCoreTargetLowering::
773 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
774 {
775   DebugLoc dl = Op.getDebugLoc();
776   // vastart stores the address of the VarArgsFrameIndex slot into the
777   // memory location argument
778   MachineFunction &MF = DAG.getMachineFunction();
779   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
780   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
781   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
782                       MachinePointerInfo(), false, false, 0);
783 }
784
785 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
786                                             SelectionDAG &DAG) const {
787   DebugLoc dl = Op.getDebugLoc();
788   // Depths > 0 not supported yet!
789   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
790     return SDValue();
791
792   MachineFunction &MF = DAG.getMachineFunction();
793   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
794   return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
795                             RegInfo->getFrameRegister(MF), MVT::i32);
796 }
797
798 SDValue XCoreTargetLowering::
799 LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
800   SDValue Chain = Op.getOperand(0);
801   SDValue Trmp = Op.getOperand(1); // trampoline
802   SDValue FPtr = Op.getOperand(2); // nested function
803   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
804
805   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
806
807   // .align 4
808   // LDAPF_u10 r11, nest
809   // LDW_2rus r11, r11[0]
810   // STWSP_ru6 r11, sp[0]
811   // LDAPF_u10 r11, fptr
812   // LDW_2rus r11, r11[0]
813   // BAU_1r r11
814   // nest:
815   // .word nest
816   // fptr:
817   // .word fptr
818   SDValue OutChains[5];
819
820   SDValue Addr = Trmp;
821
822   DebugLoc dl = Op.getDebugLoc();
823   OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
824                               Addr, MachinePointerInfo(TrmpAddr), false, false,
825                               0);
826
827   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
828                      DAG.getConstant(4, MVT::i32));
829   OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
830                               Addr, MachinePointerInfo(TrmpAddr, 4), false,
831                               false, 0);
832
833   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
834                      DAG.getConstant(8, MVT::i32));
835   OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
836                               Addr, MachinePointerInfo(TrmpAddr, 8), false,
837                               false, 0);
838
839   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
840                      DAG.getConstant(12, MVT::i32));
841   OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
842                               MachinePointerInfo(TrmpAddr, 12), false, false,
843                               0);
844
845   Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
846                      DAG.getConstant(16, MVT::i32));
847   OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
848                               MachinePointerInfo(TrmpAddr, 16), false, false,
849                               0);
850
851   SDValue Ops[] =
852     { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5) };
853   return DAG.getMergeValues(Ops, 2, dl);
854 }
855
856 //===----------------------------------------------------------------------===//
857 //                      Calling Convention Implementation
858 //===----------------------------------------------------------------------===//
859
860 #include "XCoreGenCallingConv.inc"
861
862 //===----------------------------------------------------------------------===//
863 //                  Call Calling Convention Implementation
864 //===----------------------------------------------------------------------===//
865
866 /// XCore call implementation
867 SDValue
868 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
869                                CallingConv::ID CallConv, bool isVarArg,
870                                bool &isTailCall,
871                                const SmallVectorImpl<ISD::OutputArg> &Outs,
872                                const SmallVectorImpl<SDValue> &OutVals,
873                                const SmallVectorImpl<ISD::InputArg> &Ins,
874                                DebugLoc dl, SelectionDAG &DAG,
875                                SmallVectorImpl<SDValue> &InVals) const {
876   // XCore target does not yet support tail call optimization.
877   isTailCall = false;
878
879   // For now, only CallingConv::C implemented
880   switch (CallConv)
881   {
882     default:
883       llvm_unreachable("Unsupported calling convention");
884     case CallingConv::Fast:
885     case CallingConv::C:
886       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
887                             Outs, OutVals, Ins, dl, DAG, InVals);
888   }
889 }
890
891 /// LowerCCCCallTo - functions arguments are copied from virtual
892 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
893 /// CALLSEQ_END are emitted.
894 /// TODO: isTailCall, sret.
895 SDValue
896 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
897                                     CallingConv::ID CallConv, bool isVarArg,
898                                     bool isTailCall,
899                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
900                                     const SmallVectorImpl<SDValue> &OutVals,
901                                     const SmallVectorImpl<ISD::InputArg> &Ins,
902                                     DebugLoc dl, SelectionDAG &DAG,
903                                     SmallVectorImpl<SDValue> &InVals) const {
904
905   // Analyze operands of the call, assigning locations to each operand.
906   SmallVector<CCValAssign, 16> ArgLocs;
907   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
908                  ArgLocs, *DAG.getContext());
909
910   // The ABI dictates there should be one stack slot available to the callee
911   // on function entry (for saving lr).
912   CCInfo.AllocateStack(4, 4);
913
914   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
915
916   // Get a count of how many bytes are to be pushed on the stack.
917   unsigned NumBytes = CCInfo.getNextStackOffset();
918
919   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
920                                  getPointerTy(), true));
921
922   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
923   SmallVector<SDValue, 12> MemOpChains;
924
925   // Walk the register/memloc assignments, inserting copies/loads.
926   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
927     CCValAssign &VA = ArgLocs[i];
928     SDValue Arg = OutVals[i];
929
930     // Promote the value if needed.
931     switch (VA.getLocInfo()) {
932       default: llvm_unreachable("Unknown loc info!");
933       case CCValAssign::Full: break;
934       case CCValAssign::SExt:
935         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
936         break;
937       case CCValAssign::ZExt:
938         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
939         break;
940       case CCValAssign::AExt:
941         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
942         break;
943     }
944
945     // Arguments that can be passed on register must be kept at
946     // RegsToPass vector
947     if (VA.isRegLoc()) {
948       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
949     } else {
950       assert(VA.isMemLoc());
951
952       int Offset = VA.getLocMemOffset();
953
954       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
955                                         Chain, Arg,
956                                         DAG.getConstant(Offset/4, MVT::i32)));
957     }
958   }
959
960   // Transform all store nodes into one single node because
961   // all store nodes are independent of each other.
962   if (!MemOpChains.empty())
963     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
964                         &MemOpChains[0], MemOpChains.size());
965
966   // Build a sequence of copy-to-reg nodes chained together with token
967   // chain and flag operands which copy the outgoing args into registers.
968   // The InFlag in necessary since all emitted instructions must be
969   // stuck together.
970   SDValue InFlag;
971   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
972     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
973                              RegsToPass[i].second, InFlag);
974     InFlag = Chain.getValue(1);
975   }
976
977   // If the callee is a GlobalAddress node (quite common, every direct call is)
978   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
979   // Likewise ExternalSymbol -> TargetExternalSymbol.
980   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
981     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
982   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
983     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
984
985   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
986   //             = Chain, Callee, Reg#1, Reg#2, ...
987   //
988   // Returns a chain & a flag for retval copy to use.
989   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
990   SmallVector<SDValue, 8> Ops;
991   Ops.push_back(Chain);
992   Ops.push_back(Callee);
993
994   // Add argument registers to the end of the list so that they are
995   // known live into the call.
996   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
997     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
998                                   RegsToPass[i].second.getValueType()));
999
1000   if (InFlag.getNode())
1001     Ops.push_back(InFlag);
1002
1003   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1004   InFlag = Chain.getValue(1);
1005
1006   // Create the CALLSEQ_END node.
1007   Chain = DAG.getCALLSEQ_END(Chain,
1008                              DAG.getConstant(NumBytes, getPointerTy(), true),
1009                              DAG.getConstant(0, getPointerTy(), true),
1010                              InFlag);
1011   InFlag = Chain.getValue(1);
1012
1013   // Handle result values, copying them out of physregs into vregs that we
1014   // return.
1015   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1016                          Ins, dl, DAG, InVals);
1017 }
1018
1019 /// LowerCallResult - Lower the result values of a call into the
1020 /// appropriate copies out of appropriate physical registers.
1021 SDValue
1022 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1023                                      CallingConv::ID CallConv, bool isVarArg,
1024                                      const SmallVectorImpl<ISD::InputArg> &Ins,
1025                                      DebugLoc dl, SelectionDAG &DAG,
1026                                      SmallVectorImpl<SDValue> &InVals) const {
1027
1028   // Assign locations to each value returned by this call.
1029   SmallVector<CCValAssign, 16> RVLocs;
1030   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1031                  RVLocs, *DAG.getContext());
1032
1033   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1034
1035   // Copy all of the result registers out of their specified physreg.
1036   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1037     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1038                                  RVLocs[i].getValVT(), InFlag).getValue(1);
1039     InFlag = Chain.getValue(2);
1040     InVals.push_back(Chain.getValue(0));
1041   }
1042
1043   return Chain;
1044 }
1045
1046 //===----------------------------------------------------------------------===//
1047 //             Formal Arguments Calling Convention Implementation
1048 //===----------------------------------------------------------------------===//
1049
1050 /// XCore formal arguments implementation
1051 SDValue
1052 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1053                                           CallingConv::ID CallConv,
1054                                           bool isVarArg,
1055                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1056                                           DebugLoc dl,
1057                                           SelectionDAG &DAG,
1058                                           SmallVectorImpl<SDValue> &InVals)
1059                                             const {
1060   switch (CallConv)
1061   {
1062     default:
1063       llvm_unreachable("Unsupported calling convention");
1064     case CallingConv::C:
1065     case CallingConv::Fast:
1066       return LowerCCCArguments(Chain, CallConv, isVarArg,
1067                                Ins, dl, DAG, InVals);
1068   }
1069 }
1070
1071 /// LowerCCCArguments - transform physical registers into
1072 /// virtual registers and generate load operations for
1073 /// arguments places on the stack.
1074 /// TODO: sret
1075 SDValue
1076 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1077                                        CallingConv::ID CallConv,
1078                                        bool isVarArg,
1079                                        const SmallVectorImpl<ISD::InputArg>
1080                                          &Ins,
1081                                        DebugLoc dl,
1082                                        SelectionDAG &DAG,
1083                                        SmallVectorImpl<SDValue> &InVals) const {
1084   MachineFunction &MF = DAG.getMachineFunction();
1085   MachineFrameInfo *MFI = MF.getFrameInfo();
1086   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1087
1088   // Assign locations to all of the incoming arguments.
1089   SmallVector<CCValAssign, 16> ArgLocs;
1090   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1091                  ArgLocs, *DAG.getContext());
1092
1093   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1094
1095   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1096
1097   unsigned LRSaveSize = StackSlotSize;
1098
1099   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1100
1101     CCValAssign &VA = ArgLocs[i];
1102
1103     if (VA.isRegLoc()) {
1104       // Arguments passed in registers
1105       EVT RegVT = VA.getLocVT();
1106       switch (RegVT.getSimpleVT().SimpleTy) {
1107       default:
1108         {
1109 #ifndef NDEBUG
1110           errs() << "LowerFormalArguments Unhandled argument type: "
1111                  << RegVT.getSimpleVT().SimpleTy << "\n";
1112 #endif
1113           llvm_unreachable(0);
1114         }
1115       case MVT::i32:
1116         unsigned VReg = RegInfo.createVirtualRegister(
1117                           XCore::GRRegsRegisterClass);
1118         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1119         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1120       }
1121     } else {
1122       // sanity check
1123       assert(VA.isMemLoc());
1124       // Load the argument to a virtual register
1125       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1126       if (ObjSize > StackSlotSize) {
1127         errs() << "LowerFormalArguments Unhandled argument type: "
1128                << EVT(VA.getLocVT()).getEVTString()
1129                << "\n";
1130       }
1131       // Create the frame index object for this incoming parameter...
1132       int FI = MFI->CreateFixedObject(ObjSize,
1133                                       LRSaveSize + VA.getLocMemOffset(),
1134                                       true);
1135
1136       // Create the SelectionDAG nodes corresponding to a load
1137       //from this parameter
1138       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1139       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1140                                    MachinePointerInfo::getFixedStack(FI),
1141                                    false, false, 0));
1142     }
1143   }
1144
1145   if (isVarArg) {
1146     /* Argument registers */
1147     static const unsigned ArgRegs[] = {
1148       XCore::R0, XCore::R1, XCore::R2, XCore::R3
1149     };
1150     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1151     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1152                                                      array_lengthof(ArgRegs));
1153     if (FirstVAReg < array_lengthof(ArgRegs)) {
1154       SmallVector<SDValue, 4> MemOps;
1155       int offset = 0;
1156       // Save remaining registers, storing higher register numbers at a higher
1157       // address
1158       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
1159         // Create a stack slot
1160         int FI = MFI->CreateFixedObject(4, offset, true);
1161         if (i == FirstVAReg) {
1162           XFI->setVarArgsFrameIndex(FI);
1163         }
1164         offset -= StackSlotSize;
1165         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1166         // Move argument from phys reg -> virt reg
1167         unsigned VReg = RegInfo.createVirtualRegister(
1168                           XCore::GRRegsRegisterClass);
1169         RegInfo.addLiveIn(ArgRegs[i], VReg);
1170         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1171         // Move argument from virt reg -> stack
1172         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1173                                      MachinePointerInfo(), false, false, 0);
1174         MemOps.push_back(Store);
1175       }
1176       if (!MemOps.empty())
1177         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1178                             &MemOps[0], MemOps.size());
1179     } else {
1180       // This will point to the next argument passed via stack.
1181       XFI->setVarArgsFrameIndex(
1182         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1183                                true));
1184     }
1185   }
1186
1187   return Chain;
1188 }
1189
1190 //===----------------------------------------------------------------------===//
1191 //               Return Value Calling Convention Implementation
1192 //===----------------------------------------------------------------------===//
1193
1194 bool XCoreTargetLowering::
1195 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1196                const SmallVectorImpl<ISD::OutputArg> &Outs,
1197                LLVMContext &Context) const {
1198   SmallVector<CCValAssign, 16> RVLocs;
1199   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1200                  RVLocs, Context);
1201   return CCInfo.CheckReturn(Outs, RetCC_XCore);
1202 }
1203
1204 SDValue
1205 XCoreTargetLowering::LowerReturn(SDValue Chain,
1206                                  CallingConv::ID CallConv, bool isVarArg,
1207                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1208                                  const SmallVectorImpl<SDValue> &OutVals,
1209                                  DebugLoc dl, SelectionDAG &DAG) const {
1210
1211   // CCValAssign - represent the assignment of
1212   // the return value to a location
1213   SmallVector<CCValAssign, 16> RVLocs;
1214
1215   // CCState - Info about the registers and stack slot.
1216   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1217                  RVLocs, *DAG.getContext());
1218
1219   // Analize return values.
1220   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1221
1222   // If this is the first return lowered for this function, add
1223   // the regs to the liveout set for the function.
1224   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1225     for (unsigned i = 0; i != RVLocs.size(); ++i)
1226       if (RVLocs[i].isRegLoc())
1227         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1228   }
1229
1230   SDValue Flag;
1231
1232   // Copy the result values into the output registers.
1233   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1234     CCValAssign &VA = RVLocs[i];
1235     assert(VA.isRegLoc() && "Can only return in registers!");
1236
1237     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1238                              OutVals[i], Flag);
1239
1240     // guarantee that all emitted copies are
1241     // stuck together, avoiding something bad
1242     Flag = Chain.getValue(1);
1243   }
1244
1245   // Return on XCore is always a "retsp 0"
1246   if (Flag.getNode())
1247     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1248                        Chain, DAG.getConstant(0, MVT::i32), Flag);
1249   else // Return Void
1250     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1251                        Chain, DAG.getConstant(0, MVT::i32));
1252 }
1253
1254 //===----------------------------------------------------------------------===//
1255 //  Other Lowering Code
1256 //===----------------------------------------------------------------------===//
1257
1258 MachineBasicBlock *
1259 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1260                                                  MachineBasicBlock *BB) const {
1261   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1262   DebugLoc dl = MI->getDebugLoc();
1263   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1264          "Unexpected instr type to insert");
1265
1266   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1267   // control-flow pattern.  The incoming instruction knows the destination vreg
1268   // to set, the condition code register to branch on, the true/false values to
1269   // select between, and a branch opcode to use.
1270   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1271   MachineFunction::iterator It = BB;
1272   ++It;
1273
1274   //  thisMBB:
1275   //  ...
1276   //   TrueVal = ...
1277   //   cmpTY ccX, r1, r2
1278   //   bCC copy1MBB
1279   //   fallthrough --> copy0MBB
1280   MachineBasicBlock *thisMBB = BB;
1281   MachineFunction *F = BB->getParent();
1282   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1283   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1284   F->insert(It, copy0MBB);
1285   F->insert(It, sinkMBB);
1286
1287   // Transfer the remainder of BB and its successor edges to sinkMBB.
1288   sinkMBB->splice(sinkMBB->begin(), BB,
1289                   llvm::next(MachineBasicBlock::iterator(MI)),
1290                   BB->end());
1291   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1292
1293   // Next, add the true and fallthrough blocks as its successors.
1294   BB->addSuccessor(copy0MBB);
1295   BB->addSuccessor(sinkMBB);
1296
1297   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1298     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1299
1300   //  copy0MBB:
1301   //   %FalseValue = ...
1302   //   # fallthrough to sinkMBB
1303   BB = copy0MBB;
1304
1305   // Update machine-CFG edges
1306   BB->addSuccessor(sinkMBB);
1307
1308   //  sinkMBB:
1309   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1310   //  ...
1311   BB = sinkMBB;
1312   BuildMI(*BB, BB->begin(), dl,
1313           TII.get(XCore::PHI), MI->getOperand(0).getReg())
1314     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1315     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1316
1317   MI->eraseFromParent();   // The pseudo instruction is gone now.
1318   return BB;
1319 }
1320
1321 //===----------------------------------------------------------------------===//
1322 // Target Optimization Hooks
1323 //===----------------------------------------------------------------------===//
1324
1325 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1326                                              DAGCombinerInfo &DCI) const {
1327   SelectionDAG &DAG = DCI.DAG;
1328   DebugLoc dl = N->getDebugLoc();
1329   switch (N->getOpcode()) {
1330   default: break;
1331   case XCoreISD::LADD: {
1332     SDValue N0 = N->getOperand(0);
1333     SDValue N1 = N->getOperand(1);
1334     SDValue N2 = N->getOperand(2);
1335     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1336     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1337     EVT VT = N0.getValueType();
1338
1339     // canonicalize constant to RHS
1340     if (N0C && !N1C)
1341       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1342
1343     // fold (ladd 0, 0, x) -> 0, x & 1
1344     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1345       SDValue Carry = DAG.getConstant(0, VT);
1346       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1347                                    DAG.getConstant(1, VT));
1348       SDValue Ops [] = { Carry, Result };
1349       return DAG.getMergeValues(Ops, 2, dl);
1350     }
1351
1352     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1353     // low bit set
1354     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1355       APInt KnownZero, KnownOne;
1356       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1357                                          VT.getSizeInBits() - 1);
1358       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1359       if (KnownZero == Mask) {
1360         SDValue Carry = DAG.getConstant(0, VT);
1361         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1362         SDValue Ops [] = { Carry, Result };
1363         return DAG.getMergeValues(Ops, 2, dl);
1364       }
1365     }
1366   }
1367   break;
1368   case XCoreISD::LSUB: {
1369     SDValue N0 = N->getOperand(0);
1370     SDValue N1 = N->getOperand(1);
1371     SDValue N2 = N->getOperand(2);
1372     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1373     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1374     EVT VT = N0.getValueType();
1375
1376     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1377     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1378       APInt KnownZero, KnownOne;
1379       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1380                                          VT.getSizeInBits() - 1);
1381       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1382       if (KnownZero == Mask) {
1383         SDValue Borrow = N2;
1384         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1385                                      DAG.getConstant(0, VT), N2);
1386         SDValue Ops [] = { Borrow, Result };
1387         return DAG.getMergeValues(Ops, 2, dl);
1388       }
1389     }
1390
1391     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1392     // low bit set
1393     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1394       APInt KnownZero, KnownOne;
1395       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1396                                          VT.getSizeInBits() - 1);
1397       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1398       if (KnownZero == Mask) {
1399         SDValue Borrow = DAG.getConstant(0, VT);
1400         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1401         SDValue Ops [] = { Borrow, Result };
1402         return DAG.getMergeValues(Ops, 2, dl);
1403       }
1404     }
1405   }
1406   break;
1407   case XCoreISD::LMUL: {
1408     SDValue N0 = N->getOperand(0);
1409     SDValue N1 = N->getOperand(1);
1410     SDValue N2 = N->getOperand(2);
1411     SDValue N3 = N->getOperand(3);
1412     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1413     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1414     EVT VT = N0.getValueType();
1415     // Canonicalize multiplicative constant to RHS. If both multiplicative
1416     // operands are constant canonicalize smallest to RHS.
1417     if ((N0C && !N1C) ||
1418         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1419       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT), N1, N0, N2, N3);
1420
1421     // lmul(x, 0, a, b)
1422     if (N1C && N1C->isNullValue()) {
1423       // If the high result is unused fold to add(a, b)
1424       if (N->hasNUsesOfValue(0, 0)) {
1425         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1426         SDValue Ops [] = { Lo, Lo };
1427         return DAG.getMergeValues(Ops, 2, dl);
1428       }
1429       // Otherwise fold to ladd(a, b, 0)
1430       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1431     }
1432   }
1433   break;
1434   case ISD::ADD: {
1435     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1436     // lmul(x, y, a, b). The high result of lmul will be ignored.
1437     // This is only profitable if the intermediate results are unused
1438     // elsewhere.
1439     SDValue Mul0, Mul1, Addend0, Addend1;
1440     if (N->getValueType(0) == MVT::i32 &&
1441         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1442       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1443                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1444                                     Mul1, Addend0, Addend1);
1445       SDValue Result(Ignored.getNode(), 1);
1446       return Result;
1447     }
1448     APInt HighMask = APInt::getHighBitsSet(64, 32);
1449     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1450     // lmul(x, y, a, b) if all operands are zero-extended. We do this
1451     // before type legalization as it is messy to match the operands after
1452     // that.
1453     if (N->getValueType(0) == MVT::i64 &&
1454         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1455         DAG.MaskedValueIsZero(Mul0, HighMask) &&
1456         DAG.MaskedValueIsZero(Mul1, HighMask) &&
1457         DAG.MaskedValueIsZero(Addend0, HighMask) &&
1458         DAG.MaskedValueIsZero(Addend1, HighMask)) {
1459       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1460                                   Mul0, DAG.getConstant(0, MVT::i32));
1461       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1462                                   Mul1, DAG.getConstant(0, MVT::i32));
1463       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1464                                      Addend0, DAG.getConstant(0, MVT::i32));
1465       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1466                                      Addend1, DAG.getConstant(0, MVT::i32));
1467       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1468                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1469                                Addend0L, Addend1L);
1470       SDValue Lo(Hi.getNode(), 1);
1471       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1472     }
1473   }
1474   break;
1475   case ISD::STORE: {
1476     // Replace unaligned store of unaligned load with memmove.
1477     StoreSDNode *ST  = cast<StoreSDNode>(N);
1478     if (!DCI.isBeforeLegalize() ||
1479         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1480         ST->isVolatile() || ST->isIndexed()) {
1481       break;
1482     }
1483     SDValue Chain = ST->getChain();
1484
1485     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1486     if (StoreBits % 8) {
1487       break;
1488     }
1489     unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1490         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1491     unsigned Alignment = ST->getAlignment();
1492     if (Alignment >= ABIAlignment) {
1493       break;
1494     }
1495
1496     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1497       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1498         LD->getAlignment() == Alignment &&
1499         !LD->isVolatile() && !LD->isIndexed() &&
1500         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1501         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1502                               LD->getBasePtr(),
1503                               DAG.getConstant(StoreBits/8, MVT::i32),
1504                               Alignment, false, ST->getPointerInfo(),
1505                               LD->getPointerInfo());
1506       }
1507     }
1508     break;
1509   }
1510   }
1511   return SDValue();
1512 }
1513
1514 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1515                                                          const APInt &Mask,
1516                                                          APInt &KnownZero,
1517                                                          APInt &KnownOne,
1518                                                          const SelectionDAG &DAG,
1519                                                          unsigned Depth) const {
1520   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1521   switch (Op.getOpcode()) {
1522   default: break;
1523   case XCoreISD::LADD:
1524   case XCoreISD::LSUB:
1525     if (Op.getResNo() == 0) {
1526       // Top bits of carry / borrow are clear.
1527       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1528                                         Mask.getBitWidth() - 1);
1529       KnownZero &= Mask;
1530     }
1531     break;
1532   }
1533 }
1534
1535 //===----------------------------------------------------------------------===//
1536 //  Addressing mode description hooks
1537 //===----------------------------------------------------------------------===//
1538
1539 static inline bool isImmUs(int64_t val)
1540 {
1541   return (val >= 0 && val <= 11);
1542 }
1543
1544 static inline bool isImmUs2(int64_t val)
1545 {
1546   return (val%2 == 0 && isImmUs(val/2));
1547 }
1548
1549 static inline bool isImmUs4(int64_t val)
1550 {
1551   return (val%4 == 0 && isImmUs(val/4));
1552 }
1553
1554 /// isLegalAddressingMode - Return true if the addressing mode represented
1555 /// by AM is legal for this target, for a load/store of the specified type.
1556 bool
1557 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1558                                               const Type *Ty) const {
1559   if (Ty->getTypeID() == Type::VoidTyID)
1560     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1561
1562   const TargetData *TD = TM.getTargetData();
1563   unsigned Size = TD->getTypeAllocSize(Ty);
1564   if (AM.BaseGV) {
1565     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1566                  AM.BaseOffs%4 == 0;
1567   }
1568
1569   switch (Size) {
1570   case 1:
1571     // reg + imm
1572     if (AM.Scale == 0) {
1573       return isImmUs(AM.BaseOffs);
1574     }
1575     // reg + reg
1576     return AM.Scale == 1 && AM.BaseOffs == 0;
1577   case 2:
1578   case 3:
1579     // reg + imm
1580     if (AM.Scale == 0) {
1581       return isImmUs2(AM.BaseOffs);
1582     }
1583     // reg + reg<<1
1584     return AM.Scale == 2 && AM.BaseOffs == 0;
1585   default:
1586     // reg + imm
1587     if (AM.Scale == 0) {
1588       return isImmUs4(AM.BaseOffs);
1589     }
1590     // reg + reg<<2
1591     return AM.Scale == 4 && AM.BaseOffs == 0;
1592   }
1593
1594   return false;
1595 }
1596
1597 //===----------------------------------------------------------------------===//
1598 //                           XCore Inline Assembly Support
1599 //===----------------------------------------------------------------------===//
1600
1601 std::vector<unsigned> XCoreTargetLowering::
1602 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1603                                   EVT VT) const
1604 {
1605   if (Constraint.size() != 1)
1606     return std::vector<unsigned>();
1607
1608   switch (Constraint[0]) {
1609     default : break;
1610     case 'r':
1611       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2,
1612                                    XCore::R3, XCore::R4,  XCore::R5,
1613                                    XCore::R6, XCore::R7,  XCore::R8,
1614                                    XCore::R9, XCore::R10, XCore::R11, 0);
1615       break;
1616   }
1617   return std::vector<unsigned>();
1618 }