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