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