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