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