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::LMUL              : return "XCoreISD::LMUL";
58     case XCoreISD::MACCU             : return "XCoreISD::MACCU";
59     case XCoreISD::MACCS             : return "XCoreISD::MACCS";
60     case XCoreISD::BR_JT             : return "XCoreISD::BR_JT";
61     case XCoreISD::BR_JT32           : return "XCoreISD::BR_JT32";
62     default                          : return NULL;
63   }
64 }
65 
66 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
67   : TargetLowering(XTM, new XCoreTargetObjectFile()),
68     TM(XTM),
69     Subtarget(*XTM.getSubtargetImpl()) {
70 
71   // Set up the register classes.
72   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
73 
74   // Compute derived properties from the register classes
75   computeRegisterProperties();
76 
77   // Division is expensive
78   setIntDivIsCheap(false);
79 
80   setShiftAmountType(MVT::i32);
81   setStackPointerRegisterToSaveRestore(XCore::SP);
82 
83   setSchedulingPreference(Sched::RegPressure);
84 
85   // Use i32 for setcc operations results (slt, sgt, ...).
86   setBooleanContents(ZeroOrOneBooleanContent);
87 
88   // XCore does not have the NodeTypes below.
89   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
90   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
91   setOperationAction(ISD::ADDC, MVT::i32, Expand);
92   setOperationAction(ISD::ADDE, MVT::i32, Expand);
93   setOperationAction(ISD::SUBC, MVT::i32, Expand);
94   setOperationAction(ISD::SUBE, MVT::i32, Expand);
95 
96   // Stop the combiner recombining select and set_cc
97   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
98 
99   // 64bit
100   setOperationAction(ISD::ADD, MVT::i64, Custom);
101   setOperationAction(ISD::SUB, MVT::i64, Custom);
102   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
103   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
104   setOperationAction(ISD::MULHS, MVT::i32, Expand);
105   setOperationAction(ISD::MULHU, MVT::i32, Expand);
106   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
107   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
108   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
109 
110   // Bit Manipulation
111   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
112   setOperationAction(ISD::ROTL , MVT::i32, Expand);
113   setOperationAction(ISD::ROTR , MVT::i32, Expand);
114 
115   setOperationAction(ISD::TRAP, MVT::Other, Legal);
116 
117   // Jump tables.
118   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
119 
120   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
121   setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
122 
123   // Thread Local Storage
124   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
125 
126   // Conversion of i64 -> double produces constantpool nodes
127   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
128 
129   // Loads
130   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
131   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
132   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133 
134   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
135   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
136 
137   // Custom expand misaligned loads / stores.
138   setOperationAction(ISD::LOAD, MVT::i32, Custom);
139   setOperationAction(ISD::STORE, MVT::i32, Custom);
140 
141   // Varargs
142   setOperationAction(ISD::VAEND, MVT::Other, Expand);
143   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
144   setOperationAction(ISD::VAARG, MVT::Other, Custom);
145   setOperationAction(ISD::VASTART, MVT::Other, Custom);
146 
147   // Dynamic stack
148   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
149   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
150   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
151 
152   maxStoresPerMemset = maxStoresPerMemsetOptSize = 4;
153   maxStoresPerMemmove = maxStoresPerMemmoveOptSize
154     = maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 2;
155 
156   // We have target-specific dag combine patterns for the following nodes:
157   setTargetDAGCombine(ISD::STORE);
158   setTargetDAGCombine(ISD::ADD);
159 }
160 
161 SDValue XCoreTargetLowering::
162 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
163   switch (Op.getOpcode())
164   {
165   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
166   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
167   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
168   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
169   case ISD::BR_JT:            return LowerBR_JT(Op, DAG);
170   case ISD::LOAD:             return LowerLOAD(Op, DAG);
171   case ISD::STORE:            return LowerSTORE(Op, DAG);
172   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
173   case ISD::VAARG:            return LowerVAARG(Op, DAG);
174   case ISD::VASTART:          return LowerVASTART(Op, DAG);
175   case ISD::SMUL_LOHI:        return LowerSMUL_LOHI(Op, DAG);
176   case ISD::UMUL_LOHI:        return LowerUMUL_LOHI(Op, DAG);
177   // FIXME: Remove these when LegalizeDAGTypes lands.
178   case ISD::ADD:
179   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
180   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
181   default:
182     llvm_unreachable("unimplemented operand");
183     return SDValue();
184   }
185 }
186 
187 /// ReplaceNodeResults - Replace the results of node with an illegal result
188 /// type with new values built out of custom code.
189 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
190                                              SmallVectorImpl<SDValue>&Results,
191                                              SelectionDAG &DAG) const {
192   switch (N->getOpcode()) {
193   default:
194     llvm_unreachable("Don't know how to custom expand this!");
195     return;
196   case ISD::ADD:
197   case ISD::SUB:
198     Results.push_back(ExpandADDSUB(N, DAG));
199     return;
200   }
201 }
202 
203 /// getFunctionAlignment - Return the Log2 alignment of this function.
204 unsigned XCoreTargetLowering::
205 getFunctionAlignment(const Function *) const {
206   return 1;
207 }
208 
209 //===----------------------------------------------------------------------===//
210 //  Misc Lower Operation implementation
211 //===----------------------------------------------------------------------===//
212 
213 SDValue XCoreTargetLowering::
214 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
215 {
216   DebugLoc dl = Op.getDebugLoc();
217   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
218                              Op.getOperand(3), Op.getOperand(4));
219   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
220                      Op.getOperand(1));
221 }
222 
223 SDValue XCoreTargetLowering::
224 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
225                         SelectionDAG &DAG) const
226 {
227   // FIXME there is no actual debug info here
228   DebugLoc dl = GA.getDebugLoc();
229   if (isa<Function>(GV)) {
230     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
231   }
232   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
233   if (!GVar) {
234     // If GV is an alias then use the aliasee to determine constness
235     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
236       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
237   }
238   bool isConst = GVar && GVar->isConstant();
239   if (isConst) {
240     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
241   }
242   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
243 }
244 
245 SDValue XCoreTargetLowering::
246 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
247 {
248   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
249   SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
250   // If it's a debug information descriptor, don't mess with it.
251   if (DAG.isVerifiedDebugInfoDesc(Op))
252     return GA;
253   return getGlobalAddressWrapper(GA, GV, DAG);
254 }
255 
256 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
257   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
258                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
259 }
260 
261 static inline bool isZeroLengthArray(const Type *Ty) {
262   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
263   return AT && (AT->getNumElements() == 0);
264 }
265 
266 SDValue XCoreTargetLowering::
267 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
268 {
269   // FIXME there isn't really debug info here
270   DebugLoc dl = Op.getDebugLoc();
271   // transform to label + getid() * size
272   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
273   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
274   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
275   if (!GVar) {
276     // If GV is an alias then use the aliasee to determine size
277     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
278       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
279   }
280   if (! GVar) {
281     llvm_unreachable("Thread local object not a GlobalVariable?");
282     return SDValue();
283   }
284   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
285   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
286 #ifndef NDEBUG
287     errs() << "Size of thread local object " << GVar->getName()
288            << " is unknown\n";
289 #endif
290     llvm_unreachable(0);
291   }
292   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
293   const TargetData *TD = TM.getTargetData();
294   unsigned Size = TD->getTypeAllocSize(Ty);
295   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
296                        DAG.getConstant(Size, MVT::i32));
297   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
298 }
299 
300 SDValue XCoreTargetLowering::
301 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
302 {
303   DebugLoc DL = Op.getDebugLoc();
304 
305   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
306   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
307 
308   return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
309 }
310 
311 SDValue XCoreTargetLowering::
312 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
313 {
314   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
315   // FIXME there isn't really debug info here
316   DebugLoc dl = CP->getDebugLoc();
317   EVT PtrVT = Op.getValueType();
318   SDValue Res;
319   if (CP->isMachineConstantPoolEntry()) {
320     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
321                                     CP->getAlignment());
322   } else {
323     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
324                                     CP->getAlignment());
325   }
326   return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
327 }
328 
329 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
330   return MachineJumpTableInfo::EK_Inline;
331 }
332 
333 SDValue XCoreTargetLowering::
334 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
335 {
336   SDValue Chain = Op.getOperand(0);
337   SDValue Table = Op.getOperand(1);
338   SDValue Index = Op.getOperand(2);
339   DebugLoc dl = Op.getDebugLoc();
340   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
341   unsigned JTI = JT->getIndex();
342   MachineFunction &MF = DAG.getMachineFunction();
343   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
344   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
345 
346   unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
347   if (NumEntries <= 32) {
348     return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
349   }
350   assert((NumEntries >> 31) == 0);
351   SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
352                                     DAG.getConstant(1, MVT::i32));
353   return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
354                      ScaledIndex);
355 }
356 
357 static bool
358 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
359                                     int64_t &Offset)
360 {
361   if (Addr.getOpcode() != ISD::ADD) {
362     return false;
363   }
364   ConstantSDNode *CN = 0;
365   if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
366     return false;
367   }
368   int64_t off = CN->getSExtValue();
369   const SDValue &Base = Addr.getOperand(0);
370   const SDValue *Root = &Base;
371   if (Base.getOpcode() == ISD::ADD &&
372       Base.getOperand(1).getOpcode() == ISD::SHL) {
373     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
374                                                       .getOperand(1));
375     if (CN && (CN->getSExtValue() >= 2)) {
376       Root = &Base.getOperand(0);
377     }
378   }
379   if (isa<FrameIndexSDNode>(*Root)) {
380     // All frame indicies are word aligned
381     AlignedBase = Base;
382     Offset = off;
383     return true;
384   }
385   if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
386       Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
387     // All dp / cp relative addresses are word aligned
388     AlignedBase = Base;
389     Offset = off;
390     return true;
391   }
392   return false;
393 }
394 
395 SDValue XCoreTargetLowering::
396 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
397   LoadSDNode *LD = cast<LoadSDNode>(Op);
398   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
399          "Unexpected extension type");
400   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
401   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
402     return SDValue();
403 
404   unsigned ABIAlignment = getTargetData()->
405     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
406   // Leave aligned load alone.
407   if (LD->getAlignment() >= ABIAlignment)
408     return SDValue();
409 
410   SDValue Chain = LD->getChain();
411   SDValue BasePtr = LD->getBasePtr();
412   DebugLoc DL = Op.getDebugLoc();
413 
414   SDValue Base;
415   int64_t Offset;
416   if (!LD->isVolatile() &&
417       IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
418     if (Offset % 4 == 0) {
419       // We've managed to infer better alignment information than the load
420       // already has. Use an aligned load.
421       //
422       return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
423                          MachinePointerInfo(),
424                          false, false, 0);
425     }
426     // Lower to
427     // ldw low, base[offset >> 2]
428     // ldw high, base[(offset >> 2) + 1]
429     // shr low_shifted, low, (offset & 0x3) * 8
430     // shl high_shifted, high, 32 - (offset & 0x3) * 8
431     // or result, low_shifted, high_shifted
432     SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
433     SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
434     SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
435     SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
436 
437     SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
438     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
439 
440     SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
441                               LowAddr, MachinePointerInfo(), false, false, 0);
442     SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
443                                HighAddr, MachinePointerInfo(), false, false, 0);
444     SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
445     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
446     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
447     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
448                              High.getValue(1));
449     SDValue Ops[] = { Result, Chain };
450     return DAG.getMergeValues(Ops, 2, DL);
451   }
452 
453   if (LD->getAlignment() == 2) {
454     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, MVT::i32, DL, Chain,
455                                  BasePtr, LD->getPointerInfo(), MVT::i16,
456                                  LD->isVolatile(), LD->isNonTemporal(), 2);
457     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
458                                    DAG.getConstant(2, MVT::i32));
459     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, MVT::i32, DL, Chain,
460                                   HighAddr,
461                                   LD->getPointerInfo().getWithOffset(2),
462                                   MVT::i16, LD->isVolatile(),
463                                   LD->isNonTemporal(), 2);
464     SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
465                                       DAG.getConstant(16, MVT::i32));
466     SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
467     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
468                              High.getValue(1));
469     SDValue Ops[] = { Result, Chain };
470     return DAG.getMergeValues(Ops, 2, DL);
471   }
472 
473   // Lower to a call to __misaligned_load(BasePtr).
474   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
475   TargetLowering::ArgListTy Args;
476   TargetLowering::ArgListEntry Entry;
477 
478   Entry.Ty = IntPtrTy;
479   Entry.Node = BasePtr;
480   Args.push_back(Entry);
481 
482   std::pair<SDValue, SDValue> CallResult =
483         LowerCallTo(Chain, IntPtrTy, false, false,
484                     false, false, 0, CallingConv::C, false,
485                     /*isReturnValueUsed=*/true,
486                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
487                     Args, DAG, DL);
488 
489   SDValue Ops[] =
490     { CallResult.first, CallResult.second };
491 
492   return DAG.getMergeValues(Ops, 2, DL);
493 }
494 
495 SDValue XCoreTargetLowering::
496 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
497 {
498   StoreSDNode *ST = cast<StoreSDNode>(Op);
499   assert(!ST->isTruncatingStore() && "Unexpected store type");
500   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
501   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
502     return SDValue();
503   }
504   unsigned ABIAlignment = getTargetData()->
505     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
506   // Leave aligned store alone.
507   if (ST->getAlignment() >= ABIAlignment) {
508     return SDValue();
509   }
510   SDValue Chain = ST->getChain();
511   SDValue BasePtr = ST->getBasePtr();
512   SDValue Value = ST->getValue();
513   DebugLoc dl = Op.getDebugLoc();
514 
515   if (ST->getAlignment() == 2) {
516     SDValue Low = Value;
517     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
518                                       DAG.getConstant(16, MVT::i32));
519     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
520                                          ST->getPointerInfo(), MVT::i16,
521                                          ST->isVolatile(), ST->isNonTemporal(),
522                                          2);
523     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
524                                    DAG.getConstant(2, MVT::i32));
525     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
526                                           ST->getPointerInfo().getWithOffset(2),
527                                           MVT::i16, ST->isVolatile(),
528                                           ST->isNonTemporal(), 2);
529     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
530   }
531 
532   // Lower to a call to __misaligned_store(BasePtr, Value).
533   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
534   TargetLowering::ArgListTy Args;
535   TargetLowering::ArgListEntry Entry;
536 
537   Entry.Ty = IntPtrTy;
538   Entry.Node = BasePtr;
539   Args.push_back(Entry);
540 
541   Entry.Node = Value;
542   Args.push_back(Entry);
543 
544   std::pair<SDValue, SDValue> CallResult =
545         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
546                     false, false, 0, CallingConv::C, false,
547                     /*isReturnValueUsed=*/true,
548                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
549                     Args, DAG, dl);
550 
551   return CallResult.second;
552 }
553 
554 SDValue XCoreTargetLowering::
555 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
556 {
557   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
558          "Unexpected operand to lower!");
559   DebugLoc dl = Op.getDebugLoc();
560   SDValue LHS = Op.getOperand(0);
561   SDValue RHS = Op.getOperand(1);
562   SDValue Zero = DAG.getConstant(0, MVT::i32);
563   SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
564                            DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
565                            LHS, RHS);
566   SDValue Lo(Hi.getNode(), 1);
567   SDValue Ops[] = { Lo, Hi };
568   return DAG.getMergeValues(Ops, 2, dl);
569 }
570 
571 SDValue XCoreTargetLowering::
572 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
573 {
574   assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
575          "Unexpected operand to lower!");
576   DebugLoc dl = Op.getDebugLoc();
577   SDValue LHS = Op.getOperand(0);
578   SDValue RHS = Op.getOperand(1);
579   SDValue Zero = DAG.getConstant(0, MVT::i32);
580   SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
581                            DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
582                            Zero, Zero);
583   SDValue Lo(Hi.getNode(), 1);
584   SDValue Ops[] = { Lo, Hi };
585   return DAG.getMergeValues(Ops, 2, dl);
586 }
587 
588 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
589 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
590 /// each intermediate result in the calculation must also have a single use.
591 /// If the Op is in the correct form the constituent parts are written to Mul0,
592 /// Mul1, Addend0 and Addend1.
593 static bool
594 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
595             SDValue &Addend1, bool requireIntermediatesHaveOneUse)
596 {
597   if (Op.getOpcode() != ISD::ADD)
598     return false;
599   SDValue N0 = Op.getOperand(0);
600   SDValue N1 = Op.getOperand(1);
601   SDValue AddOp;
602   SDValue OtherOp;
603   if (N0.getOpcode() == ISD::ADD) {
604     AddOp = N0;
605     OtherOp = N1;
606   } else if (N1.getOpcode() == ISD::ADD) {
607     AddOp = N1;
608     OtherOp = N0;
609   } else {
610     return false;
611   }
612   if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
613     return false;
614   if (OtherOp.getOpcode() == ISD::MUL) {
615     // add(add(a,b),mul(x,y))
616     if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
617       return false;
618     Mul0 = OtherOp.getOperand(0);
619     Mul1 = OtherOp.getOperand(1);
620     Addend0 = AddOp.getOperand(0);
621     Addend1 = AddOp.getOperand(1);
622     return true;
623   }
624   if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
625     // add(add(mul(x,y),a),b)
626     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
627       return false;
628     Mul0 = AddOp.getOperand(0).getOperand(0);
629     Mul1 = AddOp.getOperand(0).getOperand(1);
630     Addend0 = AddOp.getOperand(1);
631     Addend1 = OtherOp;
632     return true;
633   }
634   if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
635     // add(add(a,mul(x,y)),b)
636     if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
637       return false;
638     Mul0 = AddOp.getOperand(1).getOperand(0);
639     Mul1 = AddOp.getOperand(1).getOperand(1);
640     Addend0 = AddOp.getOperand(0);
641     Addend1 = OtherOp;
642     return true;
643   }
644   return false;
645 }
646 
647 SDValue XCoreTargetLowering::
648 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
649 {
650   SDValue Mul;
651   SDValue Other;
652   if (N->getOperand(0).getOpcode() == ISD::MUL) {
653     Mul = N->getOperand(0);
654     Other = N->getOperand(1);
655   } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
656     Mul = N->getOperand(1);
657     Other = N->getOperand(0);
658   } else {
659     return SDValue();
660   }
661   DebugLoc dl = N->getDebugLoc();
662   SDValue LL, RL, AddendL, AddendH;
663   LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
664                    Mul.getOperand(0),  DAG.getConstant(0, MVT::i32));
665   RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
666                    Mul.getOperand(1),  DAG.getConstant(0, MVT::i32));
667   AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
668                         Other,  DAG.getConstant(0, MVT::i32));
669   AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
670                         Other,  DAG.getConstant(1, MVT::i32));
671   APInt HighMask = APInt::getHighBitsSet(64, 32);
672   unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
673   unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
674   if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
675       DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
676     // The inputs are both zero-extended.
677     SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
678                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
679                              AddendL, LL, RL);
680     SDValue Lo(Hi.getNode(), 1);
681     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
682   }
683   if (LHSSB > 32 && RHSSB > 32) {
684     // The inputs are both sign-extended.
685     SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
686                              DAG.getVTList(MVT::i32, MVT::i32), AddendH,
687                              AddendL, LL, RL);
688     SDValue Lo(Hi.getNode(), 1);
689     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
690   }
691   SDValue LH, RH;
692   LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
693                    Mul.getOperand(0),  DAG.getConstant(1, MVT::i32));
694   RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
695                    Mul.getOperand(1),  DAG.getConstant(1, MVT::i32));
696   SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
697                            DAG.getVTList(MVT::i32, MVT::i32), AddendH,
698                            AddendL, LL, RL);
699   SDValue Lo(Hi.getNode(), 1);
700   RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
701   LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
702   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
703   Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
704   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
705 }
706 
707 SDValue XCoreTargetLowering::
708 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
709 {
710   assert(N->getValueType(0) == MVT::i64 &&
711          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
712         "Unknown operand to lower!");
713 
714   if (N->getOpcode() == ISD::ADD) {
715     SDValue Result = TryExpandADDWithMul(N, DAG);
716     if (Result.getNode() != 0)
717       return Result;
718   }
719 
720   DebugLoc dl = N->getDebugLoc();
721 
722   // Extract components
723   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
724                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
725   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
726                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
727   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
728                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
729   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
730                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
731 
732   // Expand
733   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
734                                                    XCoreISD::LSUB;
735   SDValue Zero = DAG.getConstant(0, MVT::i32);
736   SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
737                                   LHSL, RHSL, Zero);
738   SDValue Lo(Carry.getNode(), 1);
739 
740   SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
741                                   LHSH, RHSH, Carry);
742   SDValue Hi(Ignored.getNode(), 1);
743   // Merge the pieces
744   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
745 }
746 
747 SDValue XCoreTargetLowering::
748 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
749 {
750   llvm_unreachable("unimplemented");
751   // FIX Arguments passed by reference need a extra dereference.
752   SDNode *Node = Op.getNode();
753   DebugLoc dl = Node->getDebugLoc();
754   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
755   EVT VT = Node->getValueType(0);
756   SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
757                                Node->getOperand(1), MachinePointerInfo(V),
758                                false, false, 0);
759   // Increment the pointer, VAList, to the next vararg
760   SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
761                      DAG.getConstant(VT.getSizeInBits(),
762                                      getPointerTy()));
763   // Store the incremented VAList to the legalized pointer
764   Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1),
765                       MachinePointerInfo(V), false, false, 0);
766   // Load the actual argument out of the pointer VAList
767   return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
768                      false, false, 0);
769 }
770 
771 SDValue XCoreTargetLowering::
772 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
773 {
774   DebugLoc dl = Op.getDebugLoc();
775   // vastart stores the address of the VarArgsFrameIndex slot into the
776   // memory location argument
777   MachineFunction &MF = DAG.getMachineFunction();
778   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
779   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
780   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
781                       MachinePointerInfo(), false, false, 0);
782 }
783 
784 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
785                                             SelectionDAG &DAG) const {
786   DebugLoc dl = Op.getDebugLoc();
787   // Depths > 0 not supported yet!
788   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
789     return SDValue();
790 
791   MachineFunction &MF = DAG.getMachineFunction();
792   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
793   return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
794                             RegInfo->getFrameRegister(MF), MVT::i32);
795 }
796 
797 //===----------------------------------------------------------------------===//
798 //                      Calling Convention Implementation
799 //===----------------------------------------------------------------------===//
800 
801 #include "XCoreGenCallingConv.inc"
802 
803 //===----------------------------------------------------------------------===//
804 //                  Call Calling Convention Implementation
805 //===----------------------------------------------------------------------===//
806 
807 /// XCore call implementation
808 SDValue
809 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
810                                CallingConv::ID CallConv, bool isVarArg,
811                                bool &isTailCall,
812                                const SmallVectorImpl<ISD::OutputArg> &Outs,
813                                const SmallVectorImpl<SDValue> &OutVals,
814                                const SmallVectorImpl<ISD::InputArg> &Ins,
815                                DebugLoc dl, SelectionDAG &DAG,
816                                SmallVectorImpl<SDValue> &InVals) const {
817   // XCore target does not yet support tail call optimization.
818   isTailCall = false;
819 
820   // For now, only CallingConv::C implemented
821   switch (CallConv)
822   {
823     default:
824       llvm_unreachable("Unsupported calling convention");
825     case CallingConv::Fast:
826     case CallingConv::C:
827       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
828                             Outs, OutVals, Ins, dl, DAG, InVals);
829   }
830 }
831 
832 /// LowerCCCCallTo - functions arguments are copied from virtual
833 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
834 /// CALLSEQ_END are emitted.
835 /// TODO: isTailCall, sret.
836 SDValue
837 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
838                                     CallingConv::ID CallConv, bool isVarArg,
839                                     bool isTailCall,
840                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
841                                     const SmallVectorImpl<SDValue> &OutVals,
842                                     const SmallVectorImpl<ISD::InputArg> &Ins,
843                                     DebugLoc dl, SelectionDAG &DAG,
844                                     SmallVectorImpl<SDValue> &InVals) const {
845 
846   // Analyze operands of the call, assigning locations to each operand.
847   SmallVector<CCValAssign, 16> ArgLocs;
848   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
849                  ArgLocs, *DAG.getContext());
850 
851   // The ABI dictates there should be one stack slot available to the callee
852   // on function entry (for saving lr).
853   CCInfo.AllocateStack(4, 4);
854 
855   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
856 
857   // Get a count of how many bytes are to be pushed on the stack.
858   unsigned NumBytes = CCInfo.getNextStackOffset();
859 
860   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
861                                  getPointerTy(), true));
862 
863   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
864   SmallVector<SDValue, 12> MemOpChains;
865 
866   // Walk the register/memloc assignments, inserting copies/loads.
867   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
868     CCValAssign &VA = ArgLocs[i];
869     SDValue Arg = OutVals[i];
870 
871     // Promote the value if needed.
872     switch (VA.getLocInfo()) {
873       default: llvm_unreachable("Unknown loc info!");
874       case CCValAssign::Full: break;
875       case CCValAssign::SExt:
876         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
877         break;
878       case CCValAssign::ZExt:
879         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
880         break;
881       case CCValAssign::AExt:
882         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
883         break;
884     }
885 
886     // Arguments that can be passed on register must be kept at
887     // RegsToPass vector
888     if (VA.isRegLoc()) {
889       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
890     } else {
891       assert(VA.isMemLoc());
892 
893       int Offset = VA.getLocMemOffset();
894 
895       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
896                                         Chain, Arg,
897                                         DAG.getConstant(Offset/4, MVT::i32)));
898     }
899   }
900 
901   // Transform all store nodes into one single node because
902   // all store nodes are independent of each other.
903   if (!MemOpChains.empty())
904     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
905                         &MemOpChains[0], MemOpChains.size());
906 
907   // Build a sequence of copy-to-reg nodes chained together with token
908   // chain and flag operands which copy the outgoing args into registers.
909   // The InFlag in necessary since all emited instructions must be
910   // stuck together.
911   SDValue InFlag;
912   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
913     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
914                              RegsToPass[i].second, InFlag);
915     InFlag = Chain.getValue(1);
916   }
917 
918   // If the callee is a GlobalAddress node (quite common, every direct call is)
919   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
920   // Likewise ExternalSymbol -> TargetExternalSymbol.
921   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
922     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
923   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
924     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
925 
926   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
927   //             = Chain, Callee, Reg#1, Reg#2, ...
928   //
929   // Returns a chain & a flag for retval copy to use.
930   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
931   SmallVector<SDValue, 8> Ops;
932   Ops.push_back(Chain);
933   Ops.push_back(Callee);
934 
935   // Add argument registers to the end of the list so that they are
936   // known live into the call.
937   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
938     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
939                                   RegsToPass[i].second.getValueType()));
940 
941   if (InFlag.getNode())
942     Ops.push_back(InFlag);
943 
944   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
945   InFlag = Chain.getValue(1);
946 
947   // Create the CALLSEQ_END node.
948   Chain = DAG.getCALLSEQ_END(Chain,
949                              DAG.getConstant(NumBytes, getPointerTy(), true),
950                              DAG.getConstant(0, getPointerTy(), true),
951                              InFlag);
952   InFlag = Chain.getValue(1);
953 
954   // Handle result values, copying them out of physregs into vregs that we
955   // return.
956   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
957                          Ins, dl, DAG, InVals);
958 }
959 
960 /// LowerCallResult - Lower the result values of a call into the
961 /// appropriate copies out of appropriate physical registers.
962 SDValue
963 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
964                                      CallingConv::ID CallConv, bool isVarArg,
965                                      const SmallVectorImpl<ISD::InputArg> &Ins,
966                                      DebugLoc dl, SelectionDAG &DAG,
967                                      SmallVectorImpl<SDValue> &InVals) const {
968 
969   // Assign locations to each value returned by this call.
970   SmallVector<CCValAssign, 16> RVLocs;
971   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
972                  RVLocs, *DAG.getContext());
973 
974   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
975 
976   // Copy all of the result registers out of their specified physreg.
977   for (unsigned i = 0; i != RVLocs.size(); ++i) {
978     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
979                                  RVLocs[i].getValVT(), InFlag).getValue(1);
980     InFlag = Chain.getValue(2);
981     InVals.push_back(Chain.getValue(0));
982   }
983 
984   return Chain;
985 }
986 
987 //===----------------------------------------------------------------------===//
988 //             Formal Arguments Calling Convention Implementation
989 //===----------------------------------------------------------------------===//
990 
991 /// XCore formal arguments implementation
992 SDValue
993 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
994                                           CallingConv::ID CallConv,
995                                           bool isVarArg,
996                                       const SmallVectorImpl<ISD::InputArg> &Ins,
997                                           DebugLoc dl,
998                                           SelectionDAG &DAG,
999                                           SmallVectorImpl<SDValue> &InVals)
1000                                             const {
1001   switch (CallConv)
1002   {
1003     default:
1004       llvm_unreachable("Unsupported calling convention");
1005     case CallingConv::C:
1006     case CallingConv::Fast:
1007       return LowerCCCArguments(Chain, CallConv, isVarArg,
1008                                Ins, dl, DAG, InVals);
1009   }
1010 }
1011 
1012 /// LowerCCCArguments - transform physical registers into
1013 /// virtual registers and generate load operations for
1014 /// arguments places on the stack.
1015 /// TODO: sret
1016 SDValue
1017 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1018                                        CallingConv::ID CallConv,
1019                                        bool isVarArg,
1020                                        const SmallVectorImpl<ISD::InputArg>
1021                                          &Ins,
1022                                        DebugLoc dl,
1023                                        SelectionDAG &DAG,
1024                                        SmallVectorImpl<SDValue> &InVals) const {
1025   MachineFunction &MF = DAG.getMachineFunction();
1026   MachineFrameInfo *MFI = MF.getFrameInfo();
1027   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1028 
1029   // Assign locations to all of the incoming arguments.
1030   SmallVector<CCValAssign, 16> ArgLocs;
1031   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1032                  ArgLocs, *DAG.getContext());
1033 
1034   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1035 
1036   unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1037 
1038   unsigned LRSaveSize = StackSlotSize;
1039 
1040   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1041 
1042     CCValAssign &VA = ArgLocs[i];
1043 
1044     if (VA.isRegLoc()) {
1045       // Arguments passed in registers
1046       EVT RegVT = VA.getLocVT();
1047       switch (RegVT.getSimpleVT().SimpleTy) {
1048       default:
1049         {
1050 #ifndef NDEBUG
1051           errs() << "LowerFormalArguments Unhandled argument type: "
1052                  << RegVT.getSimpleVT().SimpleTy << "\n";
1053 #endif
1054           llvm_unreachable(0);
1055         }
1056       case MVT::i32:
1057         unsigned VReg = RegInfo.createVirtualRegister(
1058                           XCore::GRRegsRegisterClass);
1059         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1060         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1061       }
1062     } else {
1063       // sanity check
1064       assert(VA.isMemLoc());
1065       // Load the argument to a virtual register
1066       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1067       if (ObjSize > StackSlotSize) {
1068         errs() << "LowerFormalArguments Unhandled argument type: "
1069                << EVT(VA.getLocVT()).getEVTString()
1070                << "\n";
1071       }
1072       // Create the frame index object for this incoming parameter...
1073       int FI = MFI->CreateFixedObject(ObjSize,
1074                                       LRSaveSize + VA.getLocMemOffset(),
1075                                       true);
1076 
1077       // Create the SelectionDAG nodes corresponding to a load
1078       //from this parameter
1079       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1080       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1081                                    MachinePointerInfo::getFixedStack(FI),
1082                                    false, false, 0));
1083     }
1084   }
1085 
1086   if (isVarArg) {
1087     /* Argument registers */
1088     static const unsigned ArgRegs[] = {
1089       XCore::R0, XCore::R1, XCore::R2, XCore::R3
1090     };
1091     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1092     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1093                                                      array_lengthof(ArgRegs));
1094     if (FirstVAReg < array_lengthof(ArgRegs)) {
1095       SmallVector<SDValue, 4> MemOps;
1096       int offset = 0;
1097       // Save remaining registers, storing higher register numbers at a higher
1098       // address
1099       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
1100         // Create a stack slot
1101         int FI = MFI->CreateFixedObject(4, offset, true);
1102         if (i == FirstVAReg) {
1103           XFI->setVarArgsFrameIndex(FI);
1104         }
1105         offset -= StackSlotSize;
1106         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1107         // Move argument from phys reg -> virt reg
1108         unsigned VReg = RegInfo.createVirtualRegister(
1109                           XCore::GRRegsRegisterClass);
1110         RegInfo.addLiveIn(ArgRegs[i], VReg);
1111         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1112         // Move argument from virt reg -> stack
1113         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1114                                      MachinePointerInfo(), false, false, 0);
1115         MemOps.push_back(Store);
1116       }
1117       if (!MemOps.empty())
1118         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1119                             &MemOps[0], MemOps.size());
1120     } else {
1121       // This will point to the next argument passed via stack.
1122       XFI->setVarArgsFrameIndex(
1123         MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1124                                true));
1125     }
1126   }
1127 
1128   return Chain;
1129 }
1130 
1131 //===----------------------------------------------------------------------===//
1132 //               Return Value Calling Convention Implementation
1133 //===----------------------------------------------------------------------===//
1134 
1135 bool XCoreTargetLowering::
1136 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1137                const SmallVectorImpl<ISD::OutputArg> &Outs,
1138                LLVMContext &Context) const {
1139   SmallVector<CCValAssign, 16> RVLocs;
1140   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1141                  RVLocs, Context);
1142   return CCInfo.CheckReturn(Outs, RetCC_XCore);
1143 }
1144 
1145 SDValue
1146 XCoreTargetLowering::LowerReturn(SDValue Chain,
1147                                  CallingConv::ID CallConv, bool isVarArg,
1148                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1149                                  const SmallVectorImpl<SDValue> &OutVals,
1150                                  DebugLoc dl, SelectionDAG &DAG) const {
1151 
1152   // CCValAssign - represent the assignment of
1153   // the return value to a location
1154   SmallVector<CCValAssign, 16> RVLocs;
1155 
1156   // CCState - Info about the registers and stack slot.
1157   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1158                  RVLocs, *DAG.getContext());
1159 
1160   // Analize return values.
1161   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1162 
1163   // If this is the first return lowered for this function, add
1164   // the regs to the liveout set for the function.
1165   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1166     for (unsigned i = 0; i != RVLocs.size(); ++i)
1167       if (RVLocs[i].isRegLoc())
1168         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1169   }
1170 
1171   SDValue Flag;
1172 
1173   // Copy the result values into the output registers.
1174   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1175     CCValAssign &VA = RVLocs[i];
1176     assert(VA.isRegLoc() && "Can only return in registers!");
1177 
1178     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1179                              OutVals[i], Flag);
1180 
1181     // guarantee that all emitted copies are
1182     // stuck together, avoiding something bad
1183     Flag = Chain.getValue(1);
1184   }
1185 
1186   // Return on XCore is always a "retsp 0"
1187   if (Flag.getNode())
1188     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1189                        Chain, DAG.getConstant(0, MVT::i32), Flag);
1190   else // Return Void
1191     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1192                        Chain, DAG.getConstant(0, MVT::i32));
1193 }
1194 
1195 //===----------------------------------------------------------------------===//
1196 //  Other Lowering Code
1197 //===----------------------------------------------------------------------===//
1198 
1199 MachineBasicBlock *
1200 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1201                                                  MachineBasicBlock *BB) const {
1202   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1203   DebugLoc dl = MI->getDebugLoc();
1204   assert((MI->getOpcode() == XCore::SELECT_CC) &&
1205          "Unexpected instr type to insert");
1206 
1207   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1208   // control-flow pattern.  The incoming instruction knows the destination vreg
1209   // to set, the condition code register to branch on, the true/false values to
1210   // select between, and a branch opcode to use.
1211   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1212   MachineFunction::iterator It = BB;
1213   ++It;
1214 
1215   //  thisMBB:
1216   //  ...
1217   //   TrueVal = ...
1218   //   cmpTY ccX, r1, r2
1219   //   bCC copy1MBB
1220   //   fallthrough --> copy0MBB
1221   MachineBasicBlock *thisMBB = BB;
1222   MachineFunction *F = BB->getParent();
1223   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1224   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1225   F->insert(It, copy0MBB);
1226   F->insert(It, sinkMBB);
1227 
1228   // Transfer the remainder of BB and its successor edges to sinkMBB.
1229   sinkMBB->splice(sinkMBB->begin(), BB,
1230                   llvm::next(MachineBasicBlock::iterator(MI)),
1231                   BB->end());
1232   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1233 
1234   // Next, add the true and fallthrough blocks as its successors.
1235   BB->addSuccessor(copy0MBB);
1236   BB->addSuccessor(sinkMBB);
1237 
1238   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1239     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1240 
1241   //  copy0MBB:
1242   //   %FalseValue = ...
1243   //   # fallthrough to sinkMBB
1244   BB = copy0MBB;
1245 
1246   // Update machine-CFG edges
1247   BB->addSuccessor(sinkMBB);
1248 
1249   //  sinkMBB:
1250   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1251   //  ...
1252   BB = sinkMBB;
1253   BuildMI(*BB, BB->begin(), dl,
1254           TII.get(XCore::PHI), MI->getOperand(0).getReg())
1255     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1256     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1257 
1258   MI->eraseFromParent();   // The pseudo instruction is gone now.
1259   return BB;
1260 }
1261 
1262 //===----------------------------------------------------------------------===//
1263 // Target Optimization Hooks
1264 //===----------------------------------------------------------------------===//
1265 
1266 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1267                                              DAGCombinerInfo &DCI) const {
1268   SelectionDAG &DAG = DCI.DAG;
1269   DebugLoc dl = N->getDebugLoc();
1270   switch (N->getOpcode()) {
1271   default: break;
1272   case XCoreISD::LADD: {
1273     SDValue N0 = N->getOperand(0);
1274     SDValue N1 = N->getOperand(1);
1275     SDValue N2 = N->getOperand(2);
1276     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1277     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1278     EVT VT = N0.getValueType();
1279 
1280     // canonicalize constant to RHS
1281     if (N0C && !N1C)
1282       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1283 
1284     // fold (ladd 0, 0, x) -> 0, x & 1
1285     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1286       SDValue Carry = DAG.getConstant(0, VT);
1287       SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1288                                    DAG.getConstant(1, VT));
1289       SDValue Ops [] = { Carry, Result };
1290       return DAG.getMergeValues(Ops, 2, dl);
1291     }
1292 
1293     // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1294     // low bit set
1295     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1296       APInt KnownZero, KnownOne;
1297       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1298                                          VT.getSizeInBits() - 1);
1299       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1300       if (KnownZero == Mask) {
1301         SDValue Carry = DAG.getConstant(0, VT);
1302         SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1303         SDValue Ops [] = { Carry, Result };
1304         return DAG.getMergeValues(Ops, 2, dl);
1305       }
1306     }
1307   }
1308   break;
1309   case XCoreISD::LSUB: {
1310     SDValue N0 = N->getOperand(0);
1311     SDValue N1 = N->getOperand(1);
1312     SDValue N2 = N->getOperand(2);
1313     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1314     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1315     EVT VT = N0.getValueType();
1316 
1317     // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1318     if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1319       APInt KnownZero, KnownOne;
1320       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1321                                          VT.getSizeInBits() - 1);
1322       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1323       if (KnownZero == Mask) {
1324         SDValue Borrow = N2;
1325         SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1326                                      DAG.getConstant(0, VT), N2);
1327         SDValue Ops [] = { Borrow, Result };
1328         return DAG.getMergeValues(Ops, 2, dl);
1329       }
1330     }
1331 
1332     // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1333     // low bit set
1334     if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1335       APInt KnownZero, KnownOne;
1336       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1337                                          VT.getSizeInBits() - 1);
1338       DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1339       if (KnownZero == Mask) {
1340         SDValue Borrow = DAG.getConstant(0, VT);
1341         SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1342         SDValue Ops [] = { Borrow, Result };
1343         return DAG.getMergeValues(Ops, 2, dl);
1344       }
1345     }
1346   }
1347   break;
1348   case XCoreISD::LMUL: {
1349     SDValue N0 = N->getOperand(0);
1350     SDValue N1 = N->getOperand(1);
1351     SDValue N2 = N->getOperand(2);
1352     SDValue N3 = N->getOperand(3);
1353     ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1354     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1355     EVT VT = N0.getValueType();
1356     // Canonicalize multiplicative constant to RHS. If both multiplicative
1357     // operands are constant canonicalize smallest to RHS.
1358     if ((N0C && !N1C) ||
1359         (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1360       return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT), N1, N0, N2, N3);
1361 
1362     // lmul(x, 0, a, b)
1363     if (N1C && N1C->isNullValue()) {
1364       // If the high result is unused fold to add(a, b)
1365       if (N->hasNUsesOfValue(0, 0)) {
1366         SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1367         SDValue Ops [] = { Lo, Lo };
1368         return DAG.getMergeValues(Ops, 2, dl);
1369       }
1370       // Otherwise fold to ladd(a, b, 0)
1371       return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1372     }
1373   }
1374   break;
1375   case ISD::ADD: {
1376     // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1377     // lmul(x, y, a, b). The high result of lmul will be ignored.
1378     // This is only profitable if the intermediate results are unused
1379     // elsewhere.
1380     SDValue Mul0, Mul1, Addend0, Addend1;
1381     if (N->getValueType(0) == MVT::i32 &&
1382         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1383       SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1384                                     DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1385                                     Mul1, Addend0, Addend1);
1386       SDValue Result(Ignored.getNode(), 1);
1387       return Result;
1388     }
1389     APInt HighMask = APInt::getHighBitsSet(64, 32);
1390     // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1391     // lmul(x, y, a, b) if all operands are zero-extended. We do this
1392     // before type legalization as it is messy to match the operands after
1393     // that.
1394     if (N->getValueType(0) == MVT::i64 &&
1395         isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1396         DAG.MaskedValueIsZero(Mul0, HighMask) &&
1397         DAG.MaskedValueIsZero(Mul1, HighMask) &&
1398         DAG.MaskedValueIsZero(Addend0, HighMask) &&
1399         DAG.MaskedValueIsZero(Addend1, HighMask)) {
1400       SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1401                                   Mul0, DAG.getConstant(0, MVT::i32));
1402       SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1403                                   Mul1, DAG.getConstant(0, MVT::i32));
1404       SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1405                                      Addend0, DAG.getConstant(0, MVT::i32));
1406       SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1407                                      Addend1, DAG.getConstant(0, MVT::i32));
1408       SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1409                                DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1410                                Addend0L, Addend1L);
1411       SDValue Lo(Hi.getNode(), 1);
1412       return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1413     }
1414   }
1415   break;
1416   case ISD::STORE: {
1417     // Replace unaligned store of unaligned load with memmove.
1418     StoreSDNode *ST  = cast<StoreSDNode>(N);
1419     if (!DCI.isBeforeLegalize() ||
1420         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1421         ST->isVolatile() || ST->isIndexed()) {
1422       break;
1423     }
1424     SDValue Chain = ST->getChain();
1425 
1426     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1427     if (StoreBits % 8) {
1428       break;
1429     }
1430     unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1431         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1432     unsigned Alignment = ST->getAlignment();
1433     if (Alignment >= ABIAlignment) {
1434       break;
1435     }
1436 
1437     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1438       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1439         LD->getAlignment() == Alignment &&
1440         !LD->isVolatile() && !LD->isIndexed() &&
1441         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1442         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1443                               LD->getBasePtr(),
1444                               DAG.getConstant(StoreBits/8, MVT::i32),
1445                               Alignment, false, ST->getPointerInfo(),
1446                               LD->getPointerInfo());
1447       }
1448     }
1449     break;
1450   }
1451   }
1452   return SDValue();
1453 }
1454 
1455 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1456                                                          const APInt &Mask,
1457                                                          APInt &KnownZero,
1458                                                          APInt &KnownOne,
1459                                                          const SelectionDAG &DAG,
1460                                                          unsigned Depth) const {
1461   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1462   switch (Op.getOpcode()) {
1463   default: break;
1464   case XCoreISD::LADD:
1465   case XCoreISD::LSUB:
1466     if (Op.getResNo() == 0) {
1467       // Top bits of carry / borrow are clear.
1468       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1469                                         Mask.getBitWidth() - 1);
1470       KnownZero &= Mask;
1471     }
1472     break;
1473   }
1474 }
1475 
1476 //===----------------------------------------------------------------------===//
1477 //  Addressing mode description hooks
1478 //===----------------------------------------------------------------------===//
1479 
1480 static inline bool isImmUs(int64_t val)
1481 {
1482   return (val >= 0 && val <= 11);
1483 }
1484 
1485 static inline bool isImmUs2(int64_t val)
1486 {
1487   return (val%2 == 0 && isImmUs(val/2));
1488 }
1489 
1490 static inline bool isImmUs4(int64_t val)
1491 {
1492   return (val%4 == 0 && isImmUs(val/4));
1493 }
1494 
1495 /// isLegalAddressingMode - Return true if the addressing mode represented
1496 /// by AM is legal for this target, for a load/store of the specified type.
1497 bool
1498 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1499                                               const Type *Ty) const {
1500   if (Ty->getTypeID() == Type::VoidTyID)
1501     return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1502 
1503   const TargetData *TD = TM.getTargetData();
1504   unsigned Size = TD->getTypeAllocSize(Ty);
1505   if (AM.BaseGV) {
1506     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1507                  AM.BaseOffs%4 == 0;
1508   }
1509 
1510   switch (Size) {
1511   case 1:
1512     // reg + imm
1513     if (AM.Scale == 0) {
1514       return isImmUs(AM.BaseOffs);
1515     }
1516     // reg + reg
1517     return AM.Scale == 1 && AM.BaseOffs == 0;
1518   case 2:
1519   case 3:
1520     // reg + imm
1521     if (AM.Scale == 0) {
1522       return isImmUs2(AM.BaseOffs);
1523     }
1524     // reg + reg<<1
1525     return AM.Scale == 2 && AM.BaseOffs == 0;
1526   default:
1527     // reg + imm
1528     if (AM.Scale == 0) {
1529       return isImmUs4(AM.BaseOffs);
1530     }
1531     // reg + reg<<2
1532     return AM.Scale == 4 && AM.BaseOffs == 0;
1533   }
1534 
1535   return false;
1536 }
1537 
1538 //===----------------------------------------------------------------------===//
1539 //                           XCore Inline Assembly Support
1540 //===----------------------------------------------------------------------===//
1541 
1542 std::vector<unsigned> XCoreTargetLowering::
1543 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1544                                   EVT VT) const
1545 {
1546   if (Constraint.size() != 1)
1547     return std::vector<unsigned>();
1548 
1549   switch (Constraint[0]) {
1550     default : break;
1551     case 'r':
1552       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2,
1553                                    XCore::R3, XCore::R4,  XCore::R5,
1554                                    XCore::R6, XCore::R7,  XCore::R8,
1555                                    XCore::R9, XCore::R10, XCore::R11, 0);
1556       break;
1557   }
1558   return std::vector<unsigned>();
1559 }
1560