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