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