assert(0) -> LLVM_UNREACHABLE.
[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 "XCoreMachineFunctionInfo.h"
18 #include "XCore.h"
19 #include "XCoreTargetMachine.h"
20 #include "XCoreSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/ADT/VectorExtras.h"
37 #include <queue>
38 #include <set>
39 using namespace llvm;
40
41 const char *XCoreTargetLowering::
42 getTargetNodeName(unsigned Opcode) const 
43 {
44   switch (Opcode) 
45   {
46     case XCoreISD::BL                : return "XCoreISD::BL";
47     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
48     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
49     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
50     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
51     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
52     default                           : return NULL;
53   }
54 }
55
56 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
57   : TargetLowering(XTM),
58     TM(XTM),
59     Subtarget(*XTM.getSubtargetImpl()) {
60
61   // Set up the register classes.
62   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
63
64   // Compute derived properties from the register classes
65   computeRegisterProperties();
66
67   // Division is expensive
68   setIntDivIsCheap(false);
69
70   setShiftAmountType(MVT::i32);
71   // shl X, 32 == 0
72   setShiftAmountFlavor(Extend);
73   setStackPointerRegisterToSaveRestore(XCore::SP);
74
75   setSchedulingPreference(SchedulingForRegPressure);
76
77   // Use i32 for setcc operations results (slt, sgt, ...).
78   setBooleanContents(ZeroOrOneBooleanContent);
79
80   // XCore does not have the NodeTypes below.
81   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
82   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
83   setOperationAction(ISD::ADDC, MVT::i32, Expand);
84   setOperationAction(ISD::ADDE, MVT::i32, Expand);
85   setOperationAction(ISD::SUBC, MVT::i32, Expand);
86   setOperationAction(ISD::SUBE, MVT::i32, Expand);
87
88   // Stop the combiner recombining select and set_cc
89   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
90   
91   // 64bit
92   if (!Subtarget.isXS1A()) {
93     setOperationAction(ISD::ADD, MVT::i64, Custom);
94     setOperationAction(ISD::SUB, MVT::i64, Custom);
95   }
96   if (Subtarget.isXS1A()) {
97     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
98   }
99   setOperationAction(ISD::MULHS, MVT::i32, Expand);
100   setOperationAction(ISD::MULHU, MVT::i32, Expand);
101   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
102   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
103   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
104   
105   // Bit Manipulation
106   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
107   setOperationAction(ISD::ROTL , MVT::i32, Expand);
108   setOperationAction(ISD::ROTR , MVT::i32, Expand);
109   
110   setOperationAction(ISD::TRAP, MVT::Other, Legal);
111   
112   // Expand jump tables for now
113   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
114   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
115
116   // RET must be custom lowered, to meet ABI requirements
117   setOperationAction(ISD::RET,           MVT::Other, Custom);
118
119   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
120   
121   // Thread Local Storage
122   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
123   
124   // Conversion of i64 -> double produces constantpool nodes
125   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
126
127   // Loads
128   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
129   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
130   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
131
132   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
133   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
134   
135   // Varargs
136   setOperationAction(ISD::VAEND, MVT::Other, Expand);
137   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
138   setOperationAction(ISD::VAARG, MVT::Other, Custom);
139   setOperationAction(ISD::VASTART, MVT::Other, Custom);
140   
141   // Dynamic stack
142   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
143   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
144   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
145   
146   // Debug
147   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
148   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
149 }
150
151 SDValue XCoreTargetLowering::
152 LowerOperation(SDValue Op, SelectionDAG &DAG) {
153   switch (Op.getOpcode()) 
154   {
155   case ISD::CALL:             return LowerCALL(Op, DAG);
156   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
157   case ISD::RET:              return LowerRET(Op, DAG);
158   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
159   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
160   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
161   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
162   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
163   case ISD::VAARG:            return LowerVAARG(Op, DAG);
164   case ISD::VASTART:          return LowerVASTART(Op, DAG);
165   // FIXME: Remove these when LegalizeDAGTypes lands.
166   case ISD::ADD:
167   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
168   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
169   default:
170     LLVM_UNREACHABLE("unimplemented operand");
171     return SDValue();
172   }
173 }
174
175 /// ReplaceNodeResults - Replace the results of node with an illegal result
176 /// type with new values built out of custom code.
177 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
178                                              SmallVectorImpl<SDValue>&Results,
179                                              SelectionDAG &DAG) {
180   switch (N->getOpcode()) {
181   default:
182     LLVM_UNREACHABLE("Don't know how to custom expand this!");
183     return;
184   case ISD::ADD:
185   case ISD::SUB:
186     Results.push_back(ExpandADDSUB(N, DAG));
187     return;
188   }
189 }
190
191 /// getFunctionAlignment - Return the Log2 alignment of this function.
192 unsigned XCoreTargetLowering::
193 getFunctionAlignment(const Function *) const {
194   return 1;
195 }
196
197 //===----------------------------------------------------------------------===//
198 //  Misc Lower Operation implementation
199 //===----------------------------------------------------------------------===//
200
201 SDValue XCoreTargetLowering::
202 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
203 {
204   DebugLoc dl = Op.getDebugLoc();
205   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
206                              Op.getOperand(3), Op.getOperand(4));
207   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
208                      Op.getOperand(1));
209 }
210
211 SDValue XCoreTargetLowering::
212 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
213 {
214   // FIXME there is no actual debug info here
215   DebugLoc dl = GA.getDebugLoc();
216   if (isa<Function>(GV)) {
217     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
218   } else if (!Subtarget.isXS1A()) {
219     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
220     if (!GVar) {
221       // If GV is an alias then use the aliasee to determine constness
222       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
223         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
224     }
225     bool isConst = GVar && GVar->isConstant();
226     if (isConst) {
227       return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
228     }
229   }
230   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
231 }
232
233 SDValue XCoreTargetLowering::
234 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
235 {
236   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
237   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
238   // If it's a debug information descriptor, don't mess with it.
239   if (DAG.isVerifiedDebugInfoDesc(Op))
240     return GA;
241   return getGlobalAddressWrapper(GA, GV, DAG);
242 }
243
244 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
245   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
246                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
247 }
248
249 static inline bool isZeroLengthArray(const Type *Ty) {
250   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
251   return AT && (AT->getNumElements() == 0);
252 }
253
254 SDValue XCoreTargetLowering::
255 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
256 {
257   // FIXME there isn't really debug info here
258   DebugLoc dl = Op.getDebugLoc();
259   // transform to label + getid() * size
260   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
261   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
262   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
263   if (!GVar) {
264     // If GV is an alias then use the aliasee to determine size
265     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
266       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
267   }
268   if (! GVar) {
269     LLVM_UNREACHABLE("Thread local object not a GlobalVariable?");
270     return SDValue();
271   }
272   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
273   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
274 #ifndef NDEBUG
275     cerr << "Size of thread local object " << GVar->getName()
276         << " is unknown\n";
277 #endif
278     llvm_unreachable();
279   }
280   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
281   const TargetData *TD = TM.getTargetData();
282   unsigned Size = TD->getTypeAllocSize(Ty);
283   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
284                        DAG.getConstant(Size, MVT::i32));
285   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
286 }
287
288 SDValue XCoreTargetLowering::
289 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
290 {
291   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
292   // FIXME there isn't really debug info here
293   DebugLoc dl = CP->getDebugLoc();
294   if (Subtarget.isXS1A()) {
295     LLVM_UNREACHABLE("Lowering of constant pool unimplemented");
296     return SDValue();
297   } else {
298     MVT PtrVT = Op.getValueType();
299     SDValue Res;
300     if (CP->isMachineConstantPoolEntry()) {
301       Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
302                                       CP->getAlignment());
303     } else {
304       Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
305                                       CP->getAlignment());
306     }
307     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
308   }
309 }
310
311 SDValue XCoreTargetLowering::
312 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
313 {
314   // FIXME there isn't really debug info here
315   DebugLoc dl = Op.getDebugLoc();
316   MVT PtrVT = Op.getValueType();
317   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
318   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
319   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
320 }
321
322 SDValue XCoreTargetLowering::
323 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
324 {
325   assert(N->getValueType(0) == MVT::i64 &&
326          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
327         "Unknown operand to lower!");
328   assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
329   DebugLoc dl = N->getDebugLoc();
330   
331   // Extract components
332   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
333                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
334   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
335                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
336   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
337                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
338   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
339                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
340   
341   // Expand
342   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
343                                                    XCoreISD::LSUB;
344   SDValue Zero = DAG.getConstant(0, MVT::i32);
345   SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
346                                   LHSL, RHSL, Zero);
347   SDValue Lo(Carry.getNode(), 1);
348   
349   SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
350                                   LHSH, RHSH, Carry);
351   SDValue Hi(Ignored.getNode(), 1);
352   // Merge the pieces
353   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
354 }
355
356 SDValue XCoreTargetLowering::
357 LowerVAARG(SDValue Op, SelectionDAG &DAG)
358 {
359   LLVM_UNREACHABLE("unimplemented");
360   // FIX Arguments passed by reference need a extra dereference.
361   SDNode *Node = Op.getNode();
362   DebugLoc dl = Node->getDebugLoc();
363   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
364   MVT VT = Node->getValueType(0);
365   SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
366                                Node->getOperand(1), V, 0);
367   // Increment the pointer, VAList, to the next vararg
368   SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList, 
369                      DAG.getConstant(VT.getSizeInBits(), 
370                                      getPointerTy()));
371   // Store the incremented VAList to the legalized pointer
372   Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
373   // Load the actual argument out of the pointer VAList
374   return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
375 }
376
377 SDValue XCoreTargetLowering::
378 LowerVASTART(SDValue Op, SelectionDAG &DAG)
379 {
380   DebugLoc dl = Op.getDebugLoc();
381   // vastart stores the address of the VarArgsFrameIndex slot into the
382   // memory location argument
383   MachineFunction &MF = DAG.getMachineFunction();
384   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
385   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
386   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
387   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
388 }
389
390 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
391   DebugLoc dl = Op.getDebugLoc();
392   // Depths > 0 not supported yet! 
393   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
394     return SDValue();
395   
396   MachineFunction &MF = DAG.getMachineFunction();
397   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
398   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, 
399                             RegInfo->getFrameRegister(MF), MVT::i32);
400 }
401
402 //===----------------------------------------------------------------------===//
403 //                      Calling Convention Implementation
404 //
405 //  The lower operations present on calling convention works on this order:
406 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
407 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
408 //      LowerRET (virt regs --> phys regs)
409 //      LowerCALL (phys regs --> virt regs)
410 //
411 //===----------------------------------------------------------------------===//
412
413 #include "XCoreGenCallingConv.inc"
414
415 //===----------------------------------------------------------------------===//
416 //                  CALL Calling Convention Implementation
417 //===----------------------------------------------------------------------===//
418
419 /// XCore custom CALL implementation
420 SDValue XCoreTargetLowering::
421 LowerCALL(SDValue Op, SelectionDAG &DAG)
422 {
423   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
424   unsigned CallingConv = TheCall->getCallingConv();
425   // For now, only CallingConv::C implemented
426   switch (CallingConv) 
427   {
428     default:
429       LLVM_UNREACHABLE("Unsupported calling convention");
430     case CallingConv::Fast:
431     case CallingConv::C:
432       return LowerCCCCallTo(Op, DAG, CallingConv);
433   }
434 }
435
436 /// LowerCCCCallTo - functions arguments are copied from virtual
437 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
438 /// CALLSEQ_END are emitted.
439 /// TODO: isTailCall, sret.
440 SDValue XCoreTargetLowering::
441 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC) 
442 {
443   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
444   SDValue Chain  = TheCall->getChain();
445   SDValue Callee = TheCall->getCallee();
446   bool isVarArg  = TheCall->isVarArg();
447   DebugLoc dl = Op.getDebugLoc();
448
449   // Analyze operands of the call, assigning locations to each operand.
450   SmallVector<CCValAssign, 16> ArgLocs;
451   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
452
453   // The ABI dictates there should be one stack slot available to the callee
454   // on function entry (for saving lr).
455   CCInfo.AllocateStack(4, 4);
456
457   CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
458
459   // Get a count of how many bytes are to be pushed on the stack.
460   unsigned NumBytes = CCInfo.getNextStackOffset();
461
462   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
463                                  getPointerTy(), true));
464
465   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
466   SmallVector<SDValue, 12> MemOpChains;
467
468   // Walk the register/memloc assignments, inserting copies/loads.
469   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
470     CCValAssign &VA = ArgLocs[i];
471
472     // Arguments start after the 5 first operands of ISD::CALL
473     SDValue Arg = TheCall->getArg(i);
474
475     // Promote the value if needed.
476     switch (VA.getLocInfo()) {
477       default: LLVM_UNREACHABLE("Unknown loc info!");
478       case CCValAssign::Full: break;
479       case CCValAssign::SExt:
480         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
481         break;
482       case CCValAssign::ZExt:
483         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
484         break;
485       case CCValAssign::AExt:
486         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
487         break;
488     }
489     
490     // Arguments that can be passed on register must be kept at 
491     // RegsToPass vector
492     if (VA.isRegLoc()) {
493       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
494     } else {
495       assert(VA.isMemLoc());
496
497       int Offset = VA.getLocMemOffset();
498
499       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other, 
500                                         Chain, Arg,
501                                         DAG.getConstant(Offset/4, MVT::i32)));
502     }
503   }
504
505   // Transform all store nodes into one single node because
506   // all store nodes are independent of each other.
507   if (!MemOpChains.empty())
508     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
509                         &MemOpChains[0], MemOpChains.size());
510
511   // Build a sequence of copy-to-reg nodes chained together with token 
512   // chain and flag operands which copy the outgoing args into registers.
513   // The InFlag in necessary since all emited instructions must be
514   // stuck together.
515   SDValue InFlag;
516   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
517     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
518                              RegsToPass[i].second, InFlag);
519     InFlag = Chain.getValue(1);
520   }
521
522   // If the callee is a GlobalAddress node (quite common, every direct call is)
523   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
524   // Likewise ExternalSymbol -> TargetExternalSymbol.
525   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
526     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
527   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
528     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
529
530   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
531   //             = Chain, Callee, Reg#1, Reg#2, ...  
532   //
533   // Returns a chain & a flag for retval copy to use.
534   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
535   SmallVector<SDValue, 8> Ops;
536   Ops.push_back(Chain);
537   Ops.push_back(Callee);
538
539   // Add argument registers to the end of the list so that they are 
540   // known live into the call.
541   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
542     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
543                                   RegsToPass[i].second.getValueType()));
544
545   if (InFlag.getNode())
546     Ops.push_back(InFlag);
547
548   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
549   InFlag = Chain.getValue(1);
550
551   // Create the CALLSEQ_END node.
552   Chain = DAG.getCALLSEQ_END(Chain,
553                              DAG.getConstant(NumBytes, getPointerTy(), true),
554                              DAG.getConstant(0, getPointerTy(), true),
555                              InFlag);
556   InFlag = Chain.getValue(1);
557
558   // Handle result values, copying them out of physregs into vregs that we
559   // return.
560   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
561                  Op.getResNo());
562 }
563
564 /// LowerCallResult - Lower the result values of an ISD::CALL into the
565 /// appropriate copies out of appropriate physical registers.  This assumes that
566 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
567 /// being lowered. Returns a SDNode with the same number of values as the 
568 /// ISD::CALL.
569 SDNode *XCoreTargetLowering::
570 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
571         unsigned CallingConv, SelectionDAG &DAG) {
572   bool isVarArg = TheCall->isVarArg();
573   DebugLoc dl = TheCall->getDebugLoc();
574
575   // Assign locations to each value returned by this call.
576   SmallVector<CCValAssign, 16> RVLocs;
577   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
578                  RVLocs, DAG.getContext());
579
580   CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
581   SmallVector<SDValue, 8> ResultVals;
582
583   // Copy all of the result registers out of their specified physreg.
584   for (unsigned i = 0; i != RVLocs.size(); ++i) {
585     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
586                                  RVLocs[i].getValVT(), InFlag).getValue(1);
587     InFlag = Chain.getValue(2);
588     ResultVals.push_back(Chain.getValue(0));
589   }
590
591   ResultVals.push_back(Chain);
592
593   // Merge everything together with a MERGE_VALUES node.
594   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
595                      &ResultVals[0], ResultVals.size()).getNode();
596 }
597
598 //===----------------------------------------------------------------------===//
599 //             FORMAL_ARGUMENTS Calling Convention Implementation
600 //===----------------------------------------------------------------------===//
601
602 /// XCore custom FORMAL_ARGUMENTS implementation
603 SDValue XCoreTargetLowering::
604 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) 
605 {
606   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
607   switch(CC) 
608   {
609     default:
610       LLVM_UNREACHABLE("Unsupported calling convention");
611     case CallingConv::C:
612     case CallingConv::Fast:
613       return LowerCCCArguments(Op, DAG);
614   }
615 }
616
617 /// LowerCCCArguments - transform physical registers into
618 /// virtual registers and generate load operations for
619 /// arguments places on the stack.
620 /// TODO: sret
621 SDValue XCoreTargetLowering::
622 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
623 {
624   MachineFunction &MF = DAG.getMachineFunction();
625   MachineFrameInfo *MFI = MF.getFrameInfo();
626   MachineRegisterInfo &RegInfo = MF.getRegInfo();
627   SDValue Root = Op.getOperand(0);
628   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
629   unsigned CC = MF.getFunction()->getCallingConv();
630   DebugLoc dl = Op.getDebugLoc();
631
632   // Assign locations to all of the incoming arguments.
633   SmallVector<CCValAssign, 16> ArgLocs;
634   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
635
636   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
637
638   unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
639
640   SmallVector<SDValue, 16> ArgValues;
641   
642   unsigned LRSaveSize = StackSlotSize;
643   
644   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
645
646     CCValAssign &VA = ArgLocs[i];
647     
648     if (VA.isRegLoc()) {
649       // Arguments passed in registers
650       MVT RegVT = VA.getLocVT();
651       switch (RegVT.getSimpleVT()) {
652       default:
653         {
654 #ifndef NDEBUG
655           cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
656                << RegVT.getSimpleVT() << "\n";
657 #endif
658           llvm_unreachable();
659         }
660       case MVT::i32:
661         unsigned VReg = RegInfo.createVirtualRegister(
662                           XCore::GRRegsRegisterClass);
663         RegInfo.addLiveIn(VA.getLocReg(), VReg);
664         ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
665       }
666     } else {
667       // sanity check
668       assert(VA.isMemLoc());
669       // Load the argument to a virtual register
670       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
671       if (ObjSize > StackSlotSize) {
672         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
673              << VA.getLocVT().getSimpleVT()
674              << "\n";
675       }
676       // Create the frame index object for this incoming parameter...
677       int FI = MFI->CreateFixedObject(ObjSize,
678                                       LRSaveSize + VA.getLocMemOffset());
679
680       // Create the SelectionDAG nodes corresponding to a load
681       //from this parameter
682       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
683       ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
684     }
685   }
686   
687   if (isVarArg) {
688     /* Argument registers */
689     static const unsigned ArgRegs[] = {
690       XCore::R0, XCore::R1, XCore::R2, XCore::R3
691     };
692     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
693     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
694                                                      array_lengthof(ArgRegs));
695     if (FirstVAReg < array_lengthof(ArgRegs)) {
696       SmallVector<SDValue, 4> MemOps;
697       int offset = 0;
698       // Save remaining registers, storing higher register numbers at a higher
699       // address
700       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
701         // Create a stack slot
702         int FI = MFI->CreateFixedObject(4, offset);
703         if (i == FirstVAReg) {
704           XFI->setVarArgsFrameIndex(FI);
705         }
706         offset -= StackSlotSize;
707         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
708         // Move argument from phys reg -> virt reg
709         unsigned VReg = RegInfo.createVirtualRegister(
710                           XCore::GRRegsRegisterClass);
711         RegInfo.addLiveIn(ArgRegs[i], VReg);
712         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
713         // Move argument from virt reg -> stack
714         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
715         MemOps.push_back(Store);
716       }
717       if (!MemOps.empty())
718         Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
719                            &MemOps[0], MemOps.size());
720     } else {
721       // This will point to the next argument passed via stack.
722       XFI->setVarArgsFrameIndex(
723           MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
724     }
725   }
726   
727   ArgValues.push_back(Root);
728
729   // Return the new list of results.
730   std::vector<MVT> RetVT(Op.getNode()->value_begin(),
731                                     Op.getNode()->value_end());
732   return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT, 
733                      &ArgValues[0], ArgValues.size());
734 }
735
736 //===----------------------------------------------------------------------===//
737 //               Return Value Calling Convention Implementation
738 //===----------------------------------------------------------------------===//
739
740 SDValue XCoreTargetLowering::
741 LowerRET(SDValue Op, SelectionDAG &DAG)
742 {
743   // CCValAssign - represent the assignment of
744   // the return value to a location
745   SmallVector<CCValAssign, 16> RVLocs;
746   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
747   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
748   DebugLoc dl = Op.getDebugLoc();
749
750   // CCState - Info about the registers and stack slot.
751   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, DAG.getContext());
752
753   // Analize return values of ISD::RET
754   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
755
756   // If this is the first return lowered for this function, add 
757   // the regs to the liveout set for the function.
758   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
759     for (unsigned i = 0; i != RVLocs.size(); ++i)
760       if (RVLocs[i].isRegLoc())
761         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
762   }
763
764   // The chain is always operand #0
765   SDValue Chain = Op.getOperand(0);
766   SDValue Flag;
767
768   // Copy the result values into the output registers.
769   for (unsigned i = 0; i != RVLocs.size(); ++i) {
770     CCValAssign &VA = RVLocs[i];
771     assert(VA.isRegLoc() && "Can only return in registers!");
772
773     // ISD::RET => ret chain, (regnum1,val1), ...
774     // So i*2+1 index only the regnums
775     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
776                              Op.getOperand(i*2+1), Flag);
777
778     // guarantee that all emitted copies are
779     // stuck together, avoiding something bad
780     Flag = Chain.getValue(1);
781   }
782
783   // Return on XCore is always a "retsp 0"
784   if (Flag.getNode())
785     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
786                        Chain, DAG.getConstant(0, MVT::i32), Flag);
787   else // Return Void
788     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
789                        Chain, DAG.getConstant(0, MVT::i32));
790 }
791
792 //===----------------------------------------------------------------------===//
793 //  Other Lowering Code
794 //===----------------------------------------------------------------------===//
795
796 MachineBasicBlock *
797 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
798                                                  MachineBasicBlock *BB) const {
799   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
800   DebugLoc dl = MI->getDebugLoc();
801   assert((MI->getOpcode() == XCore::SELECT_CC) &&
802          "Unexpected instr type to insert");
803   
804   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
805   // control-flow pattern.  The incoming instruction knows the destination vreg
806   // to set, the condition code register to branch on, the true/false values to
807   // select between, and a branch opcode to use.
808   const BasicBlock *LLVM_BB = BB->getBasicBlock();
809   MachineFunction::iterator It = BB;
810   ++It;
811   
812   //  thisMBB:
813   //  ...
814   //   TrueVal = ...
815   //   cmpTY ccX, r1, r2
816   //   bCC copy1MBB
817   //   fallthrough --> copy0MBB
818   MachineBasicBlock *thisMBB = BB;
819   MachineFunction *F = BB->getParent();
820   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
821   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
822   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
823     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
824   F->insert(It, copy0MBB);
825   F->insert(It, sinkMBB);
826   // Update machine-CFG edges by transferring all successors of the current
827   // block to the new block which will contain the Phi node for the select.
828   sinkMBB->transferSuccessors(BB);
829   // Next, add the true and fallthrough blocks as its successors.
830   BB->addSuccessor(copy0MBB);
831   BB->addSuccessor(sinkMBB);
832   
833   //  copy0MBB:
834   //   %FalseValue = ...
835   //   # fallthrough to sinkMBB
836   BB = copy0MBB;
837   
838   // Update machine-CFG edges
839   BB->addSuccessor(sinkMBB);
840   
841   //  sinkMBB:
842   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
843   //  ...
844   BB = sinkMBB;
845   BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
846     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
847     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
848   
849   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
850   return BB;
851 }
852
853 //===----------------------------------------------------------------------===//
854 //  Addressing mode description hooks
855 //===----------------------------------------------------------------------===//
856
857 static inline bool isImmUs(int64_t val)
858 {
859   return (val >= 0 && val <= 11);
860 }
861
862 static inline bool isImmUs2(int64_t val)
863 {
864   return (val%2 == 0 && isImmUs(val/2));
865 }
866
867 static inline bool isImmUs4(int64_t val)
868 {
869   return (val%4 == 0 && isImmUs(val/4));
870 }
871
872 /// isLegalAddressingMode - Return true if the addressing mode represented
873 /// by AM is legal for this target, for a load/store of the specified type.
874 bool
875 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
876                                               const Type *Ty) const {
877   MVT VT = getValueType(Ty, true);
878   // Get expected value type after legalization
879   switch (VT.getSimpleVT()) {
880   // Legal load / stores
881   case MVT::i8:
882   case MVT::i16:
883   case MVT::i32:
884     break;
885   // Expand i1 -> i8
886   case MVT::i1:
887     VT = MVT::i8;
888     break;
889   // Everything else is lowered to words
890   default:
891     VT = MVT::i32;
892     break;
893   }
894   if (AM.BaseGV) {
895     return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
896                  AM.BaseOffs%4 == 0;
897   }
898   
899   switch (VT.getSimpleVT()) {
900   default:
901     return false;
902   case MVT::i8:
903     // reg + imm
904     if (AM.Scale == 0) {
905       return isImmUs(AM.BaseOffs);
906     }
907     return AM.Scale == 1 && AM.BaseOffs == 0;
908   case MVT::i16:
909     // reg + imm
910     if (AM.Scale == 0) {
911       return isImmUs2(AM.BaseOffs);
912     }
913     return AM.Scale == 2 && AM.BaseOffs == 0;
914   case MVT::i32:
915     // reg + imm
916     if (AM.Scale == 0) {
917       return isImmUs4(AM.BaseOffs);
918     }
919     // reg + reg<<2
920     return AM.Scale == 4 && AM.BaseOffs == 0;
921   }
922   
923   return false;
924 }
925
926 //===----------------------------------------------------------------------===//
927 //                           XCore Inline Assembly Support
928 //===----------------------------------------------------------------------===//
929
930 std::vector<unsigned> XCoreTargetLowering::
931 getRegClassForInlineAsmConstraint(const std::string &Constraint,
932                                   MVT VT) const 
933 {
934   if (Constraint.size() != 1)
935     return std::vector<unsigned>();
936
937   switch (Constraint[0]) {
938     default : break;
939     case 'r':
940       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
941                                    XCore::R3, XCore::R4,  XCore::R5, 
942                                    XCore::R6, XCore::R7,  XCore::R8, 
943                                    XCore::R9, XCore::R10, XCore::R11, 0);
944       break;
945   }
946   return std::vector<unsigned>();
947 }