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