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