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