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