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