Lower the threshold at which memcpy / memmove / memset stop being expanded
[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 "XCoreTargetMachine.h"
20 #include "XCoreSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/ADT/VectorExtras.h"
37 #include <queue>
38 #include <set>
39 using namespace llvm;
40
41 const char *XCoreTargetLowering::
42 getTargetNodeName(unsigned Opcode) const 
43 {
44   switch (Opcode) 
45   {
46     case XCoreISD::BL                : return "XCoreISD::BL";
47     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
48     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
49     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
50     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
51     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
52     default                           : return NULL;
53   }
54 }
55
56 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
57   : TargetLowering(XTM),
58     TM(XTM),
59     Subtarget(*XTM.getSubtargetImpl()) {
60
61   // Set up the register classes.
62   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
63
64   // Compute derived properties from the register classes
65   computeRegisterProperties();
66
67   // Division is expensive
68   setIntDivIsCheap(false);
69
70   setShiftAmountType(MVT::i32);
71   // shl X, 32 == 0
72   setShiftAmountFlavor(Extend);
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   // RET must be custom lowered, to meet ABI requirements
117   setOperationAction(ISD::RET,           MVT::Other, Custom);
118
119   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
120   
121   // Thread Local Storage
122   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
123   
124   // Conversion of i64 -> double produces constantpool nodes
125   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
126
127   // Loads
128   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
129   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
130   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
131
132   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
133   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
134
135   // Custom expand misaligned loads / stores.
136   setOperationAction(ISD::LOAD, MVT::i32, Custom);
137   setOperationAction(ISD::STORE, MVT::i32, Custom);
138
139   // Varargs
140   setOperationAction(ISD::VAEND, MVT::Other, Expand);
141   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
142   setOperationAction(ISD::VAARG, MVT::Other, Custom);
143   setOperationAction(ISD::VASTART, MVT::Other, Custom);
144   
145   // Dynamic stack
146   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
147   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
148   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
149   
150   // Debug
151   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
152   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
153
154   maxStoresPerMemset = 4;
155   maxStoresPerMemmove = maxStoresPerMemcpy = 2;
156 }
157
158 SDValue XCoreTargetLowering::
159 LowerOperation(SDValue Op, SelectionDAG &DAG) {
160   switch (Op.getOpcode()) 
161   {
162   case ISD::CALL:             return LowerCALL(Op, DAG);
163   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
164   case ISD::RET:              return LowerRET(Op, DAG);
165   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
166   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
167   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
168   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
169   case ISD::LOAD:             return LowerLOAD(Op, DAG);
170   case ISD::STORE:            return LowerSTORE(Op, DAG);
171   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
172   case ISD::VAARG:            return LowerVAARG(Op, DAG);
173   case ISD::VASTART:          return LowerVASTART(Op, DAG);
174   // FIXME: Remove these when LegalizeDAGTypes lands.
175   case ISD::ADD:
176   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
177   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
178   default:
179     llvm_unreachable("unimplemented operand");
180     return SDValue();
181   }
182 }
183
184 /// ReplaceNodeResults - Replace the results of node with an illegal result
185 /// type with new values built out of custom code.
186 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
187                                              SmallVectorImpl<SDValue>&Results,
188                                              SelectionDAG &DAG) {
189   switch (N->getOpcode()) {
190   default:
191     llvm_unreachable("Don't know how to custom expand this!");
192     return;
193   case ISD::ADD:
194   case ISD::SUB:
195     Results.push_back(ExpandADDSUB(N, DAG));
196     return;
197   }
198 }
199
200 /// getFunctionAlignment - Return the Log2 alignment of this function.
201 unsigned XCoreTargetLowering::
202 getFunctionAlignment(const Function *) const {
203   return 1;
204 }
205
206 //===----------------------------------------------------------------------===//
207 //  Misc Lower Operation implementation
208 //===----------------------------------------------------------------------===//
209
210 SDValue XCoreTargetLowering::
211 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
212 {
213   DebugLoc dl = Op.getDebugLoc();
214   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
215                              Op.getOperand(3), Op.getOperand(4));
216   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
217                      Op.getOperand(1));
218 }
219
220 SDValue XCoreTargetLowering::
221 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
222 {
223   // FIXME there is no actual debug info here
224   DebugLoc dl = GA.getDebugLoc();
225   if (isa<Function>(GV)) {
226     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
227   } else if (!Subtarget.isXS1A()) {
228     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
229     if (!GVar) {
230       // If GV is an alias then use the aliasee to determine constness
231       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
232         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
233     }
234     bool isConst = GVar && GVar->isConstant();
235     if (isConst) {
236       return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
237     }
238   }
239   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
240 }
241
242 SDValue XCoreTargetLowering::
243 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
244 {
245   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
246   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
247   // If it's a debug information descriptor, don't mess with it.
248   if (DAG.isVerifiedDebugInfoDesc(Op))
249     return GA;
250   return getGlobalAddressWrapper(GA, GV, DAG);
251 }
252
253 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
254   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
255                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
256 }
257
258 static inline bool isZeroLengthArray(const Type *Ty) {
259   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
260   return AT && (AT->getNumElements() == 0);
261 }
262
263 SDValue XCoreTargetLowering::
264 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
265 {
266   // FIXME there isn't really debug info here
267   DebugLoc dl = Op.getDebugLoc();
268   // transform to label + getid() * size
269   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
270   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
271   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
272   if (!GVar) {
273     // If GV is an alias then use the aliasee to determine size
274     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
275       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
276   }
277   if (! GVar) {
278     llvm_unreachable("Thread local object not a GlobalVariable?");
279     return SDValue();
280   }
281   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
282   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
283 #ifndef NDEBUG
284     cerr << "Size of thread local object " << GVar->getName()
285         << " is unknown\n";
286 #endif
287     llvm_unreachable(0);
288   }
289   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
290   const TargetData *TD = TM.getTargetData();
291   unsigned Size = TD->getTypeAllocSize(Ty);
292   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
293                        DAG.getConstant(Size, MVT::i32));
294   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
295 }
296
297 SDValue XCoreTargetLowering::
298 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
299 {
300   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
301   // FIXME there isn't really debug info here
302   DebugLoc dl = CP->getDebugLoc();
303   if (Subtarget.isXS1A()) {
304     llvm_unreachable("Lowering of constant pool unimplemented");
305     return SDValue();
306   } else {
307     MVT PtrVT = Op.getValueType();
308     SDValue Res;
309     if (CP->isMachineConstantPoolEntry()) {
310       Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
311                                       CP->getAlignment());
312     } else {
313       Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
314                                       CP->getAlignment());
315     }
316     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
317   }
318 }
319
320 SDValue XCoreTargetLowering::
321 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
322 {
323   // FIXME there isn't really debug info here
324   DebugLoc dl = Op.getDebugLoc();
325   MVT PtrVT = Op.getValueType();
326   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
327   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
328   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
329 }
330
331 static bool
332 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
333                                     int64_t &Offset)
334 {
335   if (Addr.getOpcode() != ISD::ADD) {
336     return false;
337   }
338   ConstantSDNode *CN = 0;
339   if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
340     return false;
341   }
342   int64_t off = CN->getSExtValue();
343   const SDValue &Base = Addr.getOperand(0);
344   const SDValue *Root = &Base;
345   if (Base.getOpcode() == ISD::ADD &&
346       Base.getOperand(1).getOpcode() == ISD::SHL) {
347     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
348                                                       .getOperand(1));
349     if (CN && (CN->getSExtValue() >= 2)) {
350       Root = &Base.getOperand(0);
351     }
352   }
353   if (isa<FrameIndexSDNode>(*Root)) {
354     // All frame indicies are word aligned
355     AlignedBase = Base;
356     Offset = off;
357     return true;
358   }
359   if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
360       Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
361     // All dp / cp relative addresses are word aligned
362     AlignedBase = Base;
363     Offset = off;
364     return true;
365   }
366   return false;
367 }
368
369 SDValue XCoreTargetLowering::
370 LowerLOAD(SDValue Op, SelectionDAG &DAG)
371 {
372   LoadSDNode *LD = cast<LoadSDNode>(Op);
373   assert(LD->getExtensionType() == ISD::NON_EXTLOAD && "Unexpected extension type");
374   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load MVT");
375   if (allowsUnalignedMemoryAccesses()) {
376     return SDValue();
377   }
378   unsigned ABIAlignment = getTargetData()->
379     getABITypeAlignment(LD->getMemoryVT().getTypeForMVT(*DAG.getContext()));
380   // Leave aligned load alone.
381   if (LD->getAlignment() >= ABIAlignment) {
382     return SDValue();
383   }
384   SDValue Chain = LD->getChain();
385   SDValue BasePtr = LD->getBasePtr();
386   DebugLoc dl = Op.getDebugLoc();
387   
388   SDValue Base;
389   int64_t Offset;
390   if (!LD->isVolatile() &&
391       IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
392     if (Offset % 4 == 0) {
393       // We've managed to infer better alignment information than the load
394       // already has. Use an aligned load.
395       return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
396     }
397     // Lower to
398     // ldw low, base[offset >> 2]
399     // ldw high, base[(offset >> 2) + 1]
400     // shr low_shifted, low, (offset & 0x3) * 8
401     // shl high_shifted, high, 32 - (offset & 0x3) * 8
402     // or result, low_shifted, high_shifted
403     SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
404     SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
405     SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
406     SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
407     
408     SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
409     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
410     
411     SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
412                                LowAddr, NULL, 4);
413     SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
414                                HighAddr, NULL, 4);
415     SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
416     SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
417     SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
418     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
419                              High.getValue(1));
420     SDValue Ops[] = { Result, Chain };
421     return DAG.getMergeValues(Ops, 2, dl);
422   }
423   
424   if (LD->getAlignment() == 2) {
425     int SVOffset = LD->getSrcValueOffset();
426     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
427                                  BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
428                                  LD->isVolatile(), 2);
429     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
430                                    DAG.getConstant(2, MVT::i32));
431     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
432                                   HighAddr, LD->getSrcValue(), SVOffset + 2,
433                                   MVT::i16, LD->isVolatile(), 2);
434     SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
435                                       DAG.getConstant(16, MVT::i32));
436     SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
437     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
438                              High.getValue(1));
439     SDValue Ops[] = { Result, Chain };
440     return DAG.getMergeValues(Ops, 2, dl);
441   }
442   
443   // Lower to a call to __misaligned_load(BasePtr).
444   const Type *IntPtrTy = getTargetData()->getIntPtrType();
445   TargetLowering::ArgListTy Args;
446   TargetLowering::ArgListEntry Entry;
447   
448   Entry.Ty = IntPtrTy;
449   Entry.Node = BasePtr;
450   Args.push_back(Entry);
451   
452   std::pair<SDValue, SDValue> CallResult =
453         LowerCallTo(Chain, IntPtrTy, false, false,
454                     false, false, 0, CallingConv::C, false,
455                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
456                     Args, DAG, dl);
457
458   SDValue Ops[] =
459     { CallResult.first, CallResult.second };
460
461   return DAG.getMergeValues(Ops, 2, dl);
462 }
463
464 SDValue XCoreTargetLowering::
465 LowerSTORE(SDValue Op, SelectionDAG &DAG)
466 {
467   StoreSDNode *ST = cast<StoreSDNode>(Op);
468   assert(!ST->isTruncatingStore() && "Unexpected store type");
469   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store MVT");
470   if (allowsUnalignedMemoryAccesses()) {
471     return SDValue();
472   }
473   unsigned ABIAlignment = getTargetData()->
474     getABITypeAlignment(ST->getMemoryVT().getTypeForMVT(*DAG.getContext()));
475   // Leave aligned store alone.
476   if (ST->getAlignment() >= ABIAlignment) {
477     return SDValue();
478   }
479   SDValue Chain = ST->getChain();
480   SDValue BasePtr = ST->getBasePtr();
481   SDValue Value = ST->getValue();
482   DebugLoc dl = Op.getDebugLoc();
483   
484   if (ST->getAlignment() == 2) {
485     int SVOffset = ST->getSrcValueOffset();
486     SDValue Low = Value;
487     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
488                                       DAG.getConstant(16, MVT::i32));
489     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
490                                          ST->getSrcValue(), SVOffset, MVT::i16,
491                                          ST->isVolatile(), 2);
492     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
493                                    DAG.getConstant(2, MVT::i32));
494     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
495                                           ST->getSrcValue(), SVOffset + 2,
496                                           MVT::i16, ST->isVolatile(), 2);
497     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
498   }
499   
500   // Lower to a call to __misaligned_store(BasePtr, Value).
501   const Type *IntPtrTy = getTargetData()->getIntPtrType();
502   TargetLowering::ArgListTy Args;
503   TargetLowering::ArgListEntry Entry;
504   
505   Entry.Ty = IntPtrTy;
506   Entry.Node = BasePtr;
507   Args.push_back(Entry);
508   
509   Entry.Node = Value;
510   Args.push_back(Entry);
511   
512   std::pair<SDValue, SDValue> CallResult =
513         LowerCallTo(Chain, Type::VoidTy, false, false,
514                     false, false, 0, CallingConv::C, false,
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   MVT 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 //  The lower operations present on calling convention works on this order:
605 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
606 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
607 //      LowerRET (virt regs --> phys regs)
608 //      LowerCALL (phys regs --> virt regs)
609 //
610 //===----------------------------------------------------------------------===//
611
612 #include "XCoreGenCallingConv.inc"
613
614 //===----------------------------------------------------------------------===//
615 //                  CALL Calling Convention Implementation
616 //===----------------------------------------------------------------------===//
617
618 /// XCore custom CALL implementation
619 SDValue XCoreTargetLowering::
620 LowerCALL(SDValue Op, SelectionDAG &DAG)
621 {
622   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
623   unsigned CallingConv = TheCall->getCallingConv();
624   // For now, only CallingConv::C implemented
625   switch (CallingConv) 
626   {
627     default:
628       llvm_unreachable("Unsupported calling convention");
629     case CallingConv::Fast:
630     case CallingConv::C:
631       return LowerCCCCallTo(Op, DAG, CallingConv);
632   }
633 }
634
635 /// LowerCCCCallTo - functions arguments are copied from virtual
636 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
637 /// CALLSEQ_END are emitted.
638 /// TODO: isTailCall, sret.
639 SDValue XCoreTargetLowering::
640 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC) 
641 {
642   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
643   SDValue Chain  = TheCall->getChain();
644   SDValue Callee = TheCall->getCallee();
645   bool isVarArg  = TheCall->isVarArg();
646   DebugLoc dl = Op.getDebugLoc();
647
648   // Analyze operands of the call, assigning locations to each operand.
649   SmallVector<CCValAssign, 16> ArgLocs;
650   CCState CCInfo(CC, isVarArg, getTargetMachine(), 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(TheCall, 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
671     // Arguments start after the 5 first operands of ISD::CALL
672     SDValue Arg = TheCall->getArg(i);
673
674     // Promote the value if needed.
675     switch (VA.getLocInfo()) {
676       default: llvm_unreachable("Unknown loc info!");
677       case CCValAssign::Full: break;
678       case CCValAssign::SExt:
679         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
680         break;
681       case CCValAssign::ZExt:
682         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
683         break;
684       case CCValAssign::AExt:
685         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
686         break;
687     }
688     
689     // Arguments that can be passed on register must be kept at 
690     // RegsToPass vector
691     if (VA.isRegLoc()) {
692       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
693     } else {
694       assert(VA.isMemLoc());
695
696       int Offset = VA.getLocMemOffset();
697
698       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other, 
699                                         Chain, Arg,
700                                         DAG.getConstant(Offset/4, MVT::i32)));
701     }
702   }
703
704   // Transform all store nodes into one single node because
705   // all store nodes are independent of each other.
706   if (!MemOpChains.empty())
707     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
708                         &MemOpChains[0], MemOpChains.size());
709
710   // Build a sequence of copy-to-reg nodes chained together with token 
711   // chain and flag operands which copy the outgoing args into registers.
712   // The InFlag in necessary since all emited instructions must be
713   // stuck together.
714   SDValue InFlag;
715   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
716     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
717                              RegsToPass[i].second, InFlag);
718     InFlag = Chain.getValue(1);
719   }
720
721   // If the callee is a GlobalAddress node (quite common, every direct call is)
722   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
723   // Likewise ExternalSymbol -> TargetExternalSymbol.
724   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
725     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
726   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
727     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
728
729   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
730   //             = Chain, Callee, Reg#1, Reg#2, ...  
731   //
732   // Returns a chain & a flag for retval copy to use.
733   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
734   SmallVector<SDValue, 8> Ops;
735   Ops.push_back(Chain);
736   Ops.push_back(Callee);
737
738   // Add argument registers to the end of the list so that they are 
739   // known live into the call.
740   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
741     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
742                                   RegsToPass[i].second.getValueType()));
743
744   if (InFlag.getNode())
745     Ops.push_back(InFlag);
746
747   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
748   InFlag = Chain.getValue(1);
749
750   // Create the CALLSEQ_END node.
751   Chain = DAG.getCALLSEQ_END(Chain,
752                              DAG.getConstant(NumBytes, getPointerTy(), true),
753                              DAG.getConstant(0, getPointerTy(), true),
754                              InFlag);
755   InFlag = Chain.getValue(1);
756
757   // Handle result values, copying them out of physregs into vregs that we
758   // return.
759   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
760                  Op.getResNo());
761 }
762
763 /// LowerCallResult - Lower the result values of an ISD::CALL into the
764 /// appropriate copies out of appropriate physical registers.  This assumes that
765 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
766 /// being lowered. Returns a SDNode with the same number of values as the 
767 /// ISD::CALL.
768 SDNode *XCoreTargetLowering::
769 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
770         unsigned CallingConv, SelectionDAG &DAG) {
771   bool isVarArg = TheCall->isVarArg();
772   DebugLoc dl = TheCall->getDebugLoc();
773
774   // Assign locations to each value returned by this call.
775   SmallVector<CCValAssign, 16> RVLocs;
776   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
777                  RVLocs, DAG.getContext());
778
779   CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
780   SmallVector<SDValue, 8> ResultVals;
781
782   // Copy all of the result registers out of their specified physreg.
783   for (unsigned i = 0; i != RVLocs.size(); ++i) {
784     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
785                                  RVLocs[i].getValVT(), InFlag).getValue(1);
786     InFlag = Chain.getValue(2);
787     ResultVals.push_back(Chain.getValue(0));
788   }
789
790   ResultVals.push_back(Chain);
791
792   // Merge everything together with a MERGE_VALUES node.
793   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
794                      &ResultVals[0], ResultVals.size()).getNode();
795 }
796
797 //===----------------------------------------------------------------------===//
798 //             FORMAL_ARGUMENTS Calling Convention Implementation
799 //===----------------------------------------------------------------------===//
800
801 /// XCore custom FORMAL_ARGUMENTS implementation
802 SDValue XCoreTargetLowering::
803 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) 
804 {
805   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
806   switch(CC) 
807   {
808     default:
809       llvm_unreachable("Unsupported calling convention");
810     case CallingConv::C:
811     case CallingConv::Fast:
812       return LowerCCCArguments(Op, DAG);
813   }
814 }
815
816 /// LowerCCCArguments - transform physical registers into
817 /// virtual registers and generate load operations for
818 /// arguments places on the stack.
819 /// TODO: sret
820 SDValue XCoreTargetLowering::
821 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
822 {
823   MachineFunction &MF = DAG.getMachineFunction();
824   MachineFrameInfo *MFI = MF.getFrameInfo();
825   MachineRegisterInfo &RegInfo = MF.getRegInfo();
826   SDValue Root = Op.getOperand(0);
827   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
828   unsigned CC = MF.getFunction()->getCallingConv();
829   DebugLoc dl = Op.getDebugLoc();
830
831   // Assign locations to all of the incoming arguments.
832   SmallVector<CCValAssign, 16> ArgLocs;
833   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
834
835   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
836
837   unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
838
839   SmallVector<SDValue, 16> ArgValues;
840   
841   unsigned LRSaveSize = StackSlotSize;
842   
843   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
844
845     CCValAssign &VA = ArgLocs[i];
846     
847     if (VA.isRegLoc()) {
848       // Arguments passed in registers
849       MVT RegVT = VA.getLocVT();
850       switch (RegVT.getSimpleVT()) {
851       default:
852         {
853 #ifndef NDEBUG
854           cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
855                << RegVT.getSimpleVT() << "\n";
856 #endif
857           llvm_unreachable(0);
858         }
859       case MVT::i32:
860         unsigned VReg = RegInfo.createVirtualRegister(
861                           XCore::GRRegsRegisterClass);
862         RegInfo.addLiveIn(VA.getLocReg(), VReg);
863         ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
864       }
865     } else {
866       // sanity check
867       assert(VA.isMemLoc());
868       // Load the argument to a virtual register
869       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
870       if (ObjSize > StackSlotSize) {
871         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
872              << VA.getLocVT().getSimpleVT()
873              << "\n";
874       }
875       // Create the frame index object for this incoming parameter...
876       int FI = MFI->CreateFixedObject(ObjSize,
877                                       LRSaveSize + VA.getLocMemOffset());
878
879       // Create the SelectionDAG nodes corresponding to a load
880       //from this parameter
881       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
882       ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
883     }
884   }
885   
886   if (isVarArg) {
887     /* Argument registers */
888     static const unsigned ArgRegs[] = {
889       XCore::R0, XCore::R1, XCore::R2, XCore::R3
890     };
891     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
892     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
893                                                      array_lengthof(ArgRegs));
894     if (FirstVAReg < array_lengthof(ArgRegs)) {
895       SmallVector<SDValue, 4> MemOps;
896       int offset = 0;
897       // Save remaining registers, storing higher register numbers at a higher
898       // address
899       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
900         // Create a stack slot
901         int FI = MFI->CreateFixedObject(4, offset);
902         if (i == FirstVAReg) {
903           XFI->setVarArgsFrameIndex(FI);
904         }
905         offset -= StackSlotSize;
906         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
907         // Move argument from phys reg -> virt reg
908         unsigned VReg = RegInfo.createVirtualRegister(
909                           XCore::GRRegsRegisterClass);
910         RegInfo.addLiveIn(ArgRegs[i], VReg);
911         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
912         // Move argument from virt reg -> stack
913         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
914         MemOps.push_back(Store);
915       }
916       if (!MemOps.empty())
917         Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
918                            &MemOps[0], MemOps.size());
919     } else {
920       // This will point to the next argument passed via stack.
921       XFI->setVarArgsFrameIndex(
922           MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
923     }
924   }
925   
926   ArgValues.push_back(Root);
927
928   // Return the new list of results.
929   std::vector<MVT> RetVT(Op.getNode()->value_begin(),
930                                     Op.getNode()->value_end());
931   return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT, 
932                      &ArgValues[0], ArgValues.size());
933 }
934
935 //===----------------------------------------------------------------------===//
936 //               Return Value Calling Convention Implementation
937 //===----------------------------------------------------------------------===//
938
939 SDValue XCoreTargetLowering::
940 LowerRET(SDValue Op, SelectionDAG &DAG)
941 {
942   // CCValAssign - represent the assignment of
943   // the return value to a location
944   SmallVector<CCValAssign, 16> RVLocs;
945   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
946   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
947   DebugLoc dl = Op.getDebugLoc();
948
949   // CCState - Info about the registers and stack slot.
950   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, DAG.getContext());
951
952   // Analize return values of ISD::RET
953   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
954
955   // If this is the first return lowered for this function, add 
956   // the regs to the liveout set for the function.
957   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
958     for (unsigned i = 0; i != RVLocs.size(); ++i)
959       if (RVLocs[i].isRegLoc())
960         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
961   }
962
963   // The chain is always operand #0
964   SDValue Chain = Op.getOperand(0);
965   SDValue Flag;
966
967   // Copy the result values into the output registers.
968   for (unsigned i = 0; i != RVLocs.size(); ++i) {
969     CCValAssign &VA = RVLocs[i];
970     assert(VA.isRegLoc() && "Can only return in registers!");
971
972     // ISD::RET => ret chain, (regnum1,val1), ...
973     // So i*2+1 index only the regnums
974     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
975                              Op.getOperand(i*2+1), Flag);
976
977     // guarantee that all emitted copies are
978     // stuck together, avoiding something bad
979     Flag = Chain.getValue(1);
980   }
981
982   // Return on XCore is always a "retsp 0"
983   if (Flag.getNode())
984     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
985                        Chain, DAG.getConstant(0, MVT::i32), Flag);
986   else // Return Void
987     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
988                        Chain, DAG.getConstant(0, MVT::i32));
989 }
990
991 //===----------------------------------------------------------------------===//
992 //  Other Lowering Code
993 //===----------------------------------------------------------------------===//
994
995 MachineBasicBlock *
996 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
997                                                  MachineBasicBlock *BB) const {
998   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
999   DebugLoc dl = MI->getDebugLoc();
1000   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1001          "Unexpected instr type to insert");
1002   
1003   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1004   // control-flow pattern.  The incoming instruction knows the destination vreg
1005   // to set, the condition code register to branch on, the true/false values to
1006   // select between, and a branch opcode to use.
1007   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1008   MachineFunction::iterator It = BB;
1009   ++It;
1010   
1011   //  thisMBB:
1012   //  ...
1013   //   TrueVal = ...
1014   //   cmpTY ccX, r1, r2
1015   //   bCC copy1MBB
1016   //   fallthrough --> copy0MBB
1017   MachineBasicBlock *thisMBB = BB;
1018   MachineFunction *F = BB->getParent();
1019   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1020   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1021   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1022     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1023   F->insert(It, copy0MBB);
1024   F->insert(It, sinkMBB);
1025   // Update machine-CFG edges by transferring all successors of the current
1026   // block to the new block which will contain the Phi node for the select.
1027   sinkMBB->transferSuccessors(BB);
1028   // Next, add the true and fallthrough blocks as its successors.
1029   BB->addSuccessor(copy0MBB);
1030   BB->addSuccessor(sinkMBB);
1031   
1032   //  copy0MBB:
1033   //   %FalseValue = ...
1034   //   # fallthrough to sinkMBB
1035   BB = copy0MBB;
1036   
1037   // Update machine-CFG edges
1038   BB->addSuccessor(sinkMBB);
1039   
1040   //  sinkMBB:
1041   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1042   //  ...
1043   BB = sinkMBB;
1044   BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1045     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1046     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1047   
1048   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1049   return BB;
1050 }
1051
1052 //===----------------------------------------------------------------------===//
1053 //  Addressing mode description hooks
1054 //===----------------------------------------------------------------------===//
1055
1056 static inline bool isImmUs(int64_t val)
1057 {
1058   return (val >= 0 && val <= 11);
1059 }
1060
1061 static inline bool isImmUs2(int64_t val)
1062 {
1063   return (val%2 == 0 && isImmUs(val/2));
1064 }
1065
1066 static inline bool isImmUs4(int64_t val)
1067 {
1068   return (val%4 == 0 && isImmUs(val/4));
1069 }
1070
1071 /// isLegalAddressingMode - Return true if the addressing mode represented
1072 /// by AM is legal for this target, for a load/store of the specified type.
1073 bool
1074 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
1075                                               const Type *Ty) const {
1076   const TargetData *TD = TM.getTargetData();
1077   unsigned Size = TD->getTypeAllocSize(Ty);
1078   if (AM.BaseGV) {
1079     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1080                  AM.BaseOffs%4 == 0;
1081   }
1082   
1083   switch (Size) {
1084   case 1:
1085     // reg + imm
1086     if (AM.Scale == 0) {
1087       return isImmUs(AM.BaseOffs);
1088     }
1089     // reg + reg
1090     return AM.Scale == 1 && AM.BaseOffs == 0;
1091   case 2:
1092   case 3:
1093     // reg + imm
1094     if (AM.Scale == 0) {
1095       return isImmUs2(AM.BaseOffs);
1096     }
1097     // reg + reg<<1
1098     return AM.Scale == 2 && AM.BaseOffs == 0;
1099   default:
1100     // reg + imm
1101     if (AM.Scale == 0) {
1102       return isImmUs4(AM.BaseOffs);
1103     }
1104     // reg + reg<<2
1105     return AM.Scale == 4 && AM.BaseOffs == 0;
1106   }
1107   
1108   return false;
1109 }
1110
1111 //===----------------------------------------------------------------------===//
1112 //                           XCore Inline Assembly Support
1113 //===----------------------------------------------------------------------===//
1114
1115 std::vector<unsigned> XCoreTargetLowering::
1116 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1117                                   MVT VT) const 
1118 {
1119   if (Constraint.size() != 1)
1120     return std::vector<unsigned>();
1121
1122   switch (Constraint[0]) {
1123     default : break;
1124     case 'r':
1125       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
1126                                    XCore::R3, XCore::R4,  XCore::R5, 
1127                                    XCore::R6, XCore::R7,  XCore::R8, 
1128                                    XCore::R9, XCore::R10, XCore::R11, 0);
1129       break;
1130   }
1131   return std::vector<unsigned>();
1132 }