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