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