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