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