LLVM API Documentation

XCoreISelLowering.cpp

Go to the documentation of this file.
00001 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation   ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the XCoreTargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "xcore-lower"
00015 
00016 #include "XCoreISelLowering.h"
00017 #include "XCoreMachineFunctionInfo.h"
00018 #include "XCore.h"
00019 #include "XCoreTargetMachine.h"
00020 #include "XCoreSubtarget.h"
00021 #include "llvm/DerivedTypes.h"
00022 #include "llvm/Function.h"
00023 #include "llvm/Intrinsics.h"
00024 #include "llvm/CallingConv.h"
00025 #include "llvm/GlobalVariable.h"
00026 #include "llvm/GlobalAlias.h"
00027 #include "llvm/CodeGen/CallingConvLower.h"
00028 #include "llvm/CodeGen/MachineFrameInfo.h"
00029 #include "llvm/CodeGen/MachineFunction.h"
00030 #include "llvm/CodeGen/MachineInstrBuilder.h"
00031 #include "llvm/CodeGen/MachineRegisterInfo.h"
00032 #include "llvm/CodeGen/SelectionDAGISel.h"
00033 #include "llvm/CodeGen/ValueTypes.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/ADT/VectorExtras.h"
00036 #include <queue>
00037 #include <set>
00038 using namespace llvm;
00039 
00040 const char *XCoreTargetLowering::
00041 getTargetNodeName(unsigned Opcode) const 
00042 {
00043   switch (Opcode) 
00044   {
00045     case XCoreISD::BL                : return "XCoreISD::BL";
00046     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
00047     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
00048     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
00049     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
00050     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
00051     default                           : return NULL;
00052   }
00053 }
00054 
00055 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
00056   : TargetLowering(XTM),
00057     TM(XTM),
00058     Subtarget(*XTM.getSubtargetImpl()) {
00059 
00060   // Set up the register classes.
00061   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
00062 
00063   // Compute derived properties from the register classes
00064   computeRegisterProperties();
00065 
00066   // Division is expensive
00067   setIntDivIsCheap(false);
00068 
00069   setShiftAmountType(MVT::i32);
00070   // shl X, 32 == 0
00071   setShiftAmountFlavor(Extend);
00072   setStackPointerRegisterToSaveRestore(XCore::SP);
00073 
00074   setSchedulingPreference(SchedulingForRegPressure);
00075 
00076   // Use i32 for setcc operations results (slt, sgt, ...).
00077   setBooleanContents(ZeroOrOneBooleanContent);
00078 
00079   // XCore does not have the NodeTypes below.
00080   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
00081   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
00082   setOperationAction(ISD::ADDC, MVT::i32, Expand);
00083   setOperationAction(ISD::ADDE, MVT::i32, Expand);
00084   setOperationAction(ISD::SUBC, MVT::i32, Expand);
00085   setOperationAction(ISD::SUBE, MVT::i32, Expand);
00086 
00087   // Stop the combiner recombining select and set_cc
00088   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
00089   
00090   // 64bit
00091   if (!Subtarget.isXS1A()) {
00092     setOperationAction(ISD::ADD, MVT::i64, Custom);
00093     setOperationAction(ISD::SUB, MVT::i64, Custom);
00094   }
00095   if (Subtarget.isXS1A()) {
00096     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00097   }
00098   setOperationAction(ISD::MULHS, MVT::i32, Expand);
00099   setOperationAction(ISD::MULHU, MVT::i32, Expand);
00100   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
00101   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
00102   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
00103   
00104   // Bit Manipulation
00105   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
00106   setOperationAction(ISD::ROTL , MVT::i32, Expand);
00107   setOperationAction(ISD::ROTR , MVT::i32, Expand);
00108   
00109   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00110   
00111   // Expand jump tables for now
00112   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
00113   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
00114 
00115   // RET must be custom lowered, to meet ABI requirements
00116   setOperationAction(ISD::RET,           MVT::Other, Custom);
00117 
00118   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
00119   
00120   // Thread Local Storage
00121   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00122   
00123   // Conversion of i64 -> double produces constantpool nodes
00124   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
00125 
00126   // Loads
00127   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
00128   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
00129   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00130 
00131   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
00132   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
00133   
00134   // Varargs
00135   setOperationAction(ISD::VAEND, MVT::Other, Expand);
00136   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
00137   setOperationAction(ISD::VAARG, MVT::Other, Custom);
00138   setOperationAction(ISD::VASTART, MVT::Other, Custom);
00139   
00140   // Dynamic stack
00141   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
00142   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
00143   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
00144   
00145   // Debug
00146   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
00147   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
00148 }
00149 
00150 SDValue XCoreTargetLowering::
00151 LowerOperation(SDValue Op, SelectionDAG &DAG) {
00152   switch (Op.getOpcode()) 
00153   {
00154   case ISD::CALL:             return LowerCALL(Op, DAG);
00155   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
00156   case ISD::RET:              return LowerRET(Op, DAG);
00157   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
00158   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
00159   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
00160   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
00161   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
00162   case ISD::VAARG:            return LowerVAARG(Op, DAG);
00163   case ISD::VASTART:          return LowerVASTART(Op, DAG);
00164   // FIXME: Remove these when LegalizeDAGTypes lands.
00165   case ISD::ADD:
00166   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
00167   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
00168   default:
00169     assert(0 && "unimplemented operand");
00170     return SDValue();
00171   }
00172 }
00173 
00174 /// ReplaceNodeResults - Replace the results of node with an illegal result
00175 /// type with new values built out of custom code.
00176 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
00177                                              SmallVectorImpl<SDValue>&Results,
00178                                              SelectionDAG &DAG) {
00179   switch (N->getOpcode()) {
00180   default:
00181     assert(0 && "Don't know how to custom expand this!");
00182     return;
00183   case ISD::ADD:
00184   case ISD::SUB:
00185     Results.push_back(ExpandADDSUB(N, DAG));
00186     return;
00187   }
00188 }
00189 
00190 //===----------------------------------------------------------------------===//
00191 //  Misc Lower Operation implementation
00192 //===----------------------------------------------------------------------===//
00193 
00194 SDValue XCoreTargetLowering::
00195 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
00196 {
00197   SDValue Cond = DAG.getNode(ISD::SETCC, MVT::i32, Op.getOperand(2),
00198                              Op.getOperand(3), Op.getOperand(4));
00199   return DAG.getNode(ISD::SELECT, MVT::i32, Cond, Op.getOperand(0),
00200                      Op.getOperand(1));
00201 }
00202 
00203 SDValue XCoreTargetLowering::
00204 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
00205 {
00206   if (isa<Function>(GV)) {
00207     return DAG.getNode(XCoreISD::PCRelativeWrapper, MVT::i32, GA);
00208   } else if (!Subtarget.isXS1A()) {
00209     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00210     if (!GVar) {
00211       // If GV is an alias then use the aliasee to determine constness
00212       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
00213         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
00214     }
00215     bool isConst = GVar && GVar->isConstant();
00216     if (isConst) {
00217       return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, GA);
00218     }
00219   }
00220   return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, GA);
00221 }
00222 
00223 SDValue XCoreTargetLowering::
00224 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
00225 {
00226   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00227   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
00228   // If it's a debug information descriptor, don't mess with it.
00229   if (DAG.isVerifiedDebugInfoDesc(Op))
00230     return GA;
00231   return getGlobalAddressWrapper(GA, GV, DAG);
00232 }
00233 
00234 static inline SDValue BuildGetId(SelectionDAG &DAG) {
00235   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, MVT::i32,
00236                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
00237 }
00238 
00239 static inline bool isZeroLengthArray(const Type *Ty) {
00240   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
00241   return AT && (AT->getNumElements() == 0);
00242 }
00243 
00244 SDValue XCoreTargetLowering::
00245 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
00246 {
00247   // transform to label + getid() * size
00248   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00249   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
00250   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00251   if (!GVar) {
00252     // If GV is an alias then use the aliasee to determine size
00253     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
00254       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
00255   }
00256   if (! GVar) {
00257     assert(0 && "Thread local object not a GlobalVariable?");
00258     return SDValue();
00259   }
00260   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
00261   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
00262     cerr << "Size of thread local object " << GVar->getName()
00263          << " is unknown\n";
00264     abort();
00265   }
00266   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
00267   const TargetData *TD = TM.getTargetData();
00268   unsigned Size = TD->getTypePaddedSize(Ty);
00269   SDValue offset = DAG.getNode(ISD::MUL, MVT::i32, BuildGetId(DAG),
00270                        DAG.getConstant(Size, MVT::i32));
00271   return DAG.getNode(ISD::ADD, MVT::i32, base, offset);
00272 }
00273 
00274 SDValue XCoreTargetLowering::
00275 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
00276 {
00277   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
00278   if (Subtarget.isXS1A()) {
00279     assert(0 && "Lowering of constant pool unimplemented");
00280     return SDValue();
00281   } else {
00282     MVT PtrVT = Op.getValueType();
00283     SDValue Res;
00284     if (CP->isMachineConstantPoolEntry()) {
00285       Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
00286                                       CP->getAlignment());
00287     } else {
00288       Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
00289                                       CP->getAlignment());
00290     }
00291     return DAG.getNode(XCoreISD::CPRelativeWrapper, MVT::i32, Res);
00292   }
00293 }
00294 
00295 SDValue XCoreTargetLowering::
00296 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
00297 {
00298   MVT PtrVT = Op.getValueType();
00299   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
00300   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
00301   return DAG.getNode(XCoreISD::DPRelativeWrapper, MVT::i32, JTI);
00302 }
00303 
00304 SDValue XCoreTargetLowering::
00305 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
00306 {
00307   assert(N->getValueType(0) == MVT::i64 &&
00308          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
00309         "Unknown operand to lower!");
00310   assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
00311   
00312   // Extract components
00313   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
00314                              DAG.getConstant(0, MVT::i32));
00315   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
00316                              DAG.getConstant(1, MVT::i32));
00317   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
00318                              DAG.getConstant(0, MVT::i32));
00319   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(1),
00320                              DAG.getConstant(1, MVT::i32));
00321   
00322   // Expand
00323   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
00324                                                    XCoreISD::LSUB;
00325   SDValue Zero = DAG.getConstant(0, MVT::i32);
00326   SDValue Carry = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
00327                                   LHSL, RHSL, Zero);
00328   SDValue Lo(Carry.getNode(), 1);
00329   
00330   SDValue Ignored = DAG.getNode(Opcode, DAG.getVTList(MVT::i32, MVT::i32),
00331                                   LHSH, RHSH, Carry);
00332   SDValue Hi(Ignored.getNode(), 1);
00333   // Merge the pieces
00334   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
00335 }
00336 
00337 SDValue XCoreTargetLowering::
00338 LowerVAARG(SDValue Op, SelectionDAG &DAG)
00339 {
00340   assert(0 && "unimplemented");
00341   // FIX Arguments passed by reference need a extra dereference.
00342   SDNode *Node = Op.getNode();
00343   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
00344   MVT VT = Node->getValueType(0);
00345   SDValue VAList = DAG.getLoad(getPointerTy(), Node->getOperand(0),
00346                                Node->getOperand(1), V, 0);
00347   // Increment the pointer, VAList, to the next vararg
00348   SDValue Tmp3 = DAG.getNode(ISD::ADD, getPointerTy(), VAList, 
00349                      DAG.getConstant(VT.getSizeInBits(), 
00350                                      getPointerTy()));
00351   // Store the incremented VAList to the legalized pointer
00352   Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Node->getOperand(1), V, 0);
00353   // Load the actual argument out of the pointer VAList
00354   return DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
00355 }
00356 
00357 SDValue XCoreTargetLowering::
00358 LowerVASTART(SDValue Op, SelectionDAG &DAG)
00359 {
00360   // vastart stores the address of the VarArgsFrameIndex slot into the
00361   // memory location argument
00362   MachineFunction &MF = DAG.getMachineFunction();
00363   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
00364   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
00365   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
00366   return DAG.getStore(Op.getOperand(0), Addr, Op.getOperand(1), SV, 0);
00367 }
00368 
00369 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
00370   // Depths > 0 not supported yet! 
00371   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
00372     return SDValue();
00373   
00374   MachineFunction &MF = DAG.getMachineFunction();
00375   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
00376   return DAG.getCopyFromReg(DAG.getEntryNode(), RegInfo->getFrameRegister(MF),
00377     MVT::i32);
00378 }
00379 
00380 //===----------------------------------------------------------------------===//
00381 //                      Calling Convention Implementation
00382 //
00383 //  The lower operations present on calling convention works on this order:
00384 //      LowerCALL (virt regs --> phys regs, virt regs --> stack) 
00385 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
00386 //      LowerRET (virt regs --> phys regs)
00387 //      LowerCALL (phys regs --> virt regs)
00388 //
00389 //===----------------------------------------------------------------------===//
00390 
00391 #include "XCoreGenCallingConv.inc"
00392 
00393 //===----------------------------------------------------------------------===//
00394 //                  CALL Calling Convention Implementation
00395 //===----------------------------------------------------------------------===//
00396 
00397 /// XCore custom CALL implementation
00398 SDValue XCoreTargetLowering::
00399 LowerCALL(SDValue Op, SelectionDAG &DAG)
00400 {
00401   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
00402   unsigned CallingConv = TheCall->getCallingConv();
00403   // For now, only CallingConv::C implemented
00404   switch (CallingConv) 
00405   {
00406     default:
00407       assert(0 && "Unsupported calling convention");
00408     case CallingConv::Fast:
00409     case CallingConv::C:
00410       return LowerCCCCallTo(Op, DAG, CallingConv);
00411   }
00412 }
00413 
00414 /// LowerCCCCallTo - functions arguments are copied from virtual
00415 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
00416 /// CALLSEQ_END are emitted.
00417 /// TODO: isTailCall, sret.
00418 SDValue XCoreTargetLowering::
00419 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC) 
00420 {
00421   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
00422   SDValue Chain  = TheCall->getChain();
00423   SDValue Callee = TheCall->getCallee();
00424   bool isVarArg  = TheCall->isVarArg();
00425 
00426   // Analyze operands of the call, assigning locations to each operand.
00427   SmallVector<CCValAssign, 16> ArgLocs;
00428   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
00429 
00430   // The ABI dictates there should be one stack slot available to the callee
00431   // on function entry (for saving lr).
00432   CCInfo.AllocateStack(4, 4);
00433 
00434   CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
00435 
00436   // Get a count of how many bytes are to be pushed on the stack.
00437   unsigned NumBytes = CCInfo.getNextStackOffset();
00438 
00439   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
00440                                  getPointerTy(), true));
00441 
00442   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
00443   SmallVector<SDValue, 12> MemOpChains;
00444 
00445   // Walk the register/memloc assignments, inserting copies/loads.
00446   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00447     CCValAssign &VA = ArgLocs[i];
00448 
00449     // Arguments start after the 5 first operands of ISD::CALL
00450     SDValue Arg = TheCall->getArg(i);
00451 
00452     // Promote the value if needed.
00453     switch (VA.getLocInfo()) {
00454       default: assert(0 && "Unknown loc info!");
00455       case CCValAssign::Full: break;
00456       case CCValAssign::SExt:
00457         Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
00458         break;
00459       case CCValAssign::ZExt:
00460         Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
00461         break;
00462       case CCValAssign::AExt:
00463         Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
00464         break;
00465     }
00466     
00467     // Arguments that can be passed on register must be kept at 
00468     // RegsToPass vector
00469     if (VA.isRegLoc()) {
00470       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
00471     } else {
00472       assert(VA.isMemLoc());
00473 
00474       int Offset = VA.getLocMemOffset();
00475 
00476       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, MVT::Other, Chain, Arg,
00477                                         DAG.getConstant(Offset/4, MVT::i32)));
00478     }
00479   }
00480 
00481   // Transform all store nodes into one single node because
00482   // all store nodes are independent of each other.
00483   if (!MemOpChains.empty())
00484     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 
00485                         &MemOpChains[0], MemOpChains.size());
00486 
00487   // Build a sequence of copy-to-reg nodes chained together with token 
00488   // chain and flag operands which copy the outgoing args into registers.
00489   // The InFlag in necessary since all emited instructions must be
00490   // stuck together.
00491   SDValue InFlag;
00492   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
00493     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, 
00494                              RegsToPass[i].second, InFlag);
00495     InFlag = Chain.getValue(1);
00496   }
00497 
00498   // If the callee is a GlobalAddress node (quite common, every direct call is)
00499   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
00500   // Likewise ExternalSymbol -> TargetExternalSymbol.
00501   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
00502     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
00503   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
00504     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
00505 
00506   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
00507   //             = Chain, Callee, Reg#1, Reg#2, ...  
00508   //
00509   // Returns a chain & a flag for retval copy to use.
00510   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
00511   SmallVector<SDValue, 8> Ops;
00512   Ops.push_back(Chain);
00513   Ops.push_back(Callee);
00514 
00515   // Add argument registers to the end of the list so that they are 
00516   // known live into the call.
00517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
00518     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
00519                                   RegsToPass[i].second.getValueType()));
00520 
00521   if (InFlag.getNode())
00522     Ops.push_back(InFlag);
00523 
00524   Chain  = DAG.getNode(XCoreISD::BL, NodeTys, &Ops[0], Ops.size());
00525   InFlag = Chain.getValue(1);
00526 
00527   // Create the CALLSEQ_END node.
00528   Chain = DAG.getCALLSEQ_END(Chain,
00529                              DAG.getConstant(NumBytes, getPointerTy(), true),
00530                              DAG.getConstant(0, getPointerTy(), true),
00531                              InFlag);
00532   InFlag = Chain.getValue(1);
00533 
00534   // Handle result values, copying them out of physregs into vregs that we
00535   // return.
00536   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
00537                  Op.getResNo());
00538 }
00539 
00540 /// LowerCallResult - Lower the result values of an ISD::CALL into the
00541 /// appropriate copies out of appropriate physical registers.  This assumes that
00542 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
00543 /// being lowered. Returns a SDNode with the same number of values as the 
00544 /// ISD::CALL.
00545 SDNode *XCoreTargetLowering::
00546 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
00547         unsigned CallingConv, SelectionDAG &DAG) {
00548   bool isVarArg = TheCall->isVarArg();
00549 
00550   // Assign locations to each value returned by this call.
00551   SmallVector<CCValAssign, 16> RVLocs;
00552   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
00553 
00554   CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
00555   SmallVector<SDValue, 8> ResultVals;
00556 
00557   // Copy all of the result registers out of their specified physreg.
00558   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00559     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
00560                                  RVLocs[i].getValVT(), InFlag).getValue(1);
00561     InFlag = Chain.getValue(2);
00562     ResultVals.push_back(Chain.getValue(0));
00563   }
00564 
00565   ResultVals.push_back(Chain);
00566 
00567   // Merge everything together with a MERGE_VALUES node.
00568   return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
00569                      &ResultVals[0], ResultVals.size()).getNode();
00570 }
00571 
00572 //===----------------------------------------------------------------------===//
00573 //             FORMAL_ARGUMENTS Calling Convention Implementation
00574 //===----------------------------------------------------------------------===//
00575 
00576 /// XCore custom FORMAL_ARGUMENTS implementation
00577 SDValue XCoreTargetLowering::
00578 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) 
00579 {
00580   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
00581   switch(CC) 
00582   {
00583     default:
00584       assert(0 && "Unsupported calling convention");
00585     case CallingConv::C:
00586     case CallingConv::Fast:
00587       return LowerCCCArguments(Op, DAG);
00588   }
00589 }
00590 
00591 /// LowerCCCArguments - transform physical registers into
00592 /// virtual registers and generate load operations for
00593 /// arguments places on the stack.
00594 /// TODO: sret
00595 SDValue XCoreTargetLowering::
00596 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
00597 {
00598   MachineFunction &MF = DAG.getMachineFunction();
00599   MachineFrameInfo *MFI = MF.getFrameInfo();
00600   MachineRegisterInfo &RegInfo = MF.getRegInfo();
00601   SDValue Root = Op.getOperand(0);
00602   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
00603   unsigned CC = MF.getFunction()->getCallingConv();
00604 
00605   // Assign locations to all of the incoming arguments.
00606   SmallVector<CCValAssign, 16> ArgLocs;
00607   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
00608 
00609   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
00610 
00611   unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
00612 
00613   SmallVector<SDValue, 16> ArgValues;
00614   
00615   unsigned LRSaveSize = StackSlotSize;
00616   
00617   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00618 
00619     CCValAssign &VA = ArgLocs[i];
00620     
00621     if (VA.isRegLoc()) {
00622       // Arguments passed in registers
00623       MVT RegVT = VA.getLocVT();
00624       switch (RegVT.getSimpleVT()) {
00625       default:
00626         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
00627              << RegVT.getSimpleVT()
00628              << "\n";
00629         abort();
00630       case MVT::i32:
00631         unsigned VReg = RegInfo.createVirtualRegister(
00632                           XCore::GRRegsRegisterClass);
00633         RegInfo.addLiveIn(VA.getLocReg(), VReg);
00634         ArgValues.push_back(DAG.getCopyFromReg(Root, VReg, RegVT));
00635       }
00636     } else {
00637       // sanity check
00638       assert(VA.isMemLoc());
00639       // Load the argument to a virtual register
00640       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
00641       if (ObjSize > StackSlotSize) {
00642         cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
00643              << VA.getLocVT().getSimpleVT()
00644              << "\n";
00645       }
00646       // Create the frame index object for this incoming parameter...
00647       int FI = MFI->CreateFixedObject(ObjSize,
00648                                       LRSaveSize + VA.getLocMemOffset());
00649 
00650       // Create the SelectionDAG nodes corresponding to a load
00651       //from this parameter
00652       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
00653       ArgValues.push_back(DAG.getLoad(VA.getLocVT(), Root, FIN, NULL, 0));
00654     }
00655   }
00656   
00657   if (isVarArg) {
00658     /* Argument registers */
00659     static const unsigned ArgRegs[] = {
00660       XCore::R0, XCore::R1, XCore::R2, XCore::R3
00661     };
00662     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
00663     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
00664                                                      array_lengthof(ArgRegs));
00665     if (FirstVAReg < array_lengthof(ArgRegs)) {
00666       SmallVector<SDValue, 4> MemOps;
00667       int offset = 0;
00668       // Save remaining registers, storing higher register numbers at a higher
00669       // address
00670       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
00671         // Create a stack slot
00672         int FI = MFI->CreateFixedObject(4, offset);
00673         if (i == FirstVAReg) {
00674           XFI->setVarArgsFrameIndex(FI);
00675         }
00676         offset -= StackSlotSize;
00677         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
00678         // Move argument from phys reg -> virt reg
00679         unsigned VReg = RegInfo.createVirtualRegister(
00680                           XCore::GRRegsRegisterClass);
00681         RegInfo.addLiveIn(ArgRegs[i], VReg);
00682         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
00683         // Move argument from virt reg -> stack
00684         SDValue Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
00685         MemOps.push_back(Store);
00686       }
00687       if (!MemOps.empty())
00688         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
00689                            &MemOps[0], MemOps.size());
00690     } else {
00691       // This will point to the next argument passed via stack.
00692       XFI->setVarArgsFrameIndex(
00693           MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
00694     }
00695   }
00696   
00697   ArgValues.push_back(Root);
00698 
00699   // Return the new list of results.
00700   std::vector<MVT> RetVT(Op.getNode()->value_begin(),
00701                                     Op.getNode()->value_end());
00702   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
00703 }
00704 
00705 //===----------------------------------------------------------------------===//
00706 //               Return Value Calling Convention Implementation
00707 //===----------------------------------------------------------------------===//
00708 
00709 SDValue XCoreTargetLowering::
00710 LowerRET(SDValue Op, SelectionDAG &DAG)
00711 {
00712   // CCValAssign - represent the assignment of
00713   // the return value to a location
00714   SmallVector<CCValAssign, 16> RVLocs;
00715   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
00716   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
00717 
00718   // CCState - Info about the registers and stack slot.
00719   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
00720 
00721   // Analize return values of ISD::RET
00722   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
00723 
00724   // If this is the first return lowered for this function, add 
00725   // the regs to the liveout set for the function.
00726   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
00727     for (unsigned i = 0; i != RVLocs.size(); ++i)
00728       if (RVLocs[i].isRegLoc())
00729         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
00730   }
00731 
00732   // The chain is always operand #0
00733   SDValue Chain = Op.getOperand(0);
00734   SDValue Flag;
00735 
00736   // Copy the result values into the output registers.
00737   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00738     CCValAssign &VA = RVLocs[i];
00739     assert(VA.isRegLoc() && "Can only return in registers!");
00740 
00741     // ISD::RET => ret chain, (regnum1,val1), ...
00742     // So i*2+1 index only the regnums
00743     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1), Flag);
00744 
00745     // guarantee that all emitted copies are
00746     // stuck together, avoiding something bad
00747     Flag = Chain.getValue(1);
00748   }
00749 
00750   // Return on XCore is always a "retsp 0"
00751   if (Flag.getNode())
00752     return DAG.getNode(XCoreISD::RETSP, MVT::Other,
00753                        Chain, DAG.getConstant(0, MVT::i32), Flag);
00754   else // Return Void
00755     return DAG.getNode(XCoreISD::RETSP, MVT::Other,
00756                        Chain, DAG.getConstant(0, MVT::i32));
00757 }
00758 
00759 //===----------------------------------------------------------------------===//
00760 //  Other Lowering Code
00761 //===----------------------------------------------------------------------===//
00762 
00763 MachineBasicBlock *
00764 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00765                                                MachineBasicBlock *BB) {
00766   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
00767   assert((MI->getOpcode() == XCore::SELECT_CC) &&
00768          "Unexpected instr type to insert");
00769   
00770   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
00771   // control-flow pattern.  The incoming instruction knows the destination vreg
00772   // to set, the condition code register to branch on, the true/false values to
00773   // select between, and a branch opcode to use.
00774   const BasicBlock *LLVM_BB = BB->getBasicBlock();
00775   MachineFunction::iterator It = BB;
00776   ++It;
00777   
00778   //  thisMBB:
00779   //  ...
00780   //   TrueVal = ...
00781   //   cmpTY ccX, r1, r2
00782   //   bCC copy1MBB
00783   //   fallthrough --> copy0MBB
00784   MachineBasicBlock *thisMBB = BB;
00785   MachineFunction *F = BB->getParent();
00786   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
00787   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
00788   BuildMI(BB, TII.get(XCore::BRFT_lru6))
00789     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
00790   F->insert(It, copy0MBB);
00791   F->insert(It, sinkMBB);
00792   // Update machine-CFG edges by transferring all successors of the current
00793   // block to the new block which will contain the Phi node for the select.
00794   sinkMBB->transferSuccessors(BB);
00795   // Next, add the true and fallthrough blocks as its successors.
00796   BB->addSuccessor(copy0MBB);
00797   BB->addSuccessor(sinkMBB);
00798   
00799   //  copy0MBB:
00800   //   %FalseValue = ...
00801   //   # fallthrough to sinkMBB
00802   BB = copy0MBB;
00803   
00804   // Update machine-CFG edges
00805   BB->addSuccessor(sinkMBB);
00806   
00807   //  sinkMBB:
00808   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
00809   //  ...
00810   BB = sinkMBB;
00811   BuildMI(BB, TII.get(XCore::PHI), MI->getOperand(0).getReg())
00812     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
00813     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
00814   
00815   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
00816   return BB;
00817 }
00818 
00819 //===----------------------------------------------------------------------===//
00820 //  Addressing mode description hooks
00821 //===----------------------------------------------------------------------===//
00822 
00823 static inline bool isImmUs(int64_t val)
00824 {
00825   return (val >= 0 && val <= 11);
00826 }
00827 
00828 static inline bool isImmUs2(int64_t val)
00829 {
00830   return (val%2 == 0 && isImmUs(val/2));
00831 }
00832 
00833 static inline bool isImmUs4(int64_t val)
00834 {
00835   return (val%4 == 0 && isImmUs(val/4));
00836 }
00837 
00838 /// isLegalAddressingMode - Return true if the addressing mode represented
00839 /// by AM is legal for this target, for a load/store of the specified type.
00840 bool
00841 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
00842                                               const Type *Ty) const {
00843   MVT VT = getValueType(Ty, true);
00844   // Get expected value type after legalization
00845   switch (VT.getSimpleVT()) {
00846   // Legal load / stores
00847   case MVT::i8:
00848   case MVT::i16:
00849   case MVT::i32:
00850     break;
00851   // Expand i1 -> i8
00852   case MVT::i1:
00853     VT = MVT::i8;
00854     break;
00855   // Everything else is lowered to words
00856   default:
00857     VT = MVT::i32;
00858     break;
00859   }
00860   if (AM.BaseGV) {
00861     return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
00862                  AM.BaseOffs%4 == 0;
00863   }
00864   
00865   switch (VT.getSimpleVT()) {
00866   default:
00867     return false;
00868   case MVT::i8:
00869     // reg + imm
00870     if (AM.Scale == 0) {
00871       return isImmUs(AM.BaseOffs);
00872     }
00873     return AM.Scale == 1 && AM.BaseOffs == 0;
00874   case MVT::i16:
00875     // reg + imm
00876     if (AM.Scale == 0) {
00877       return isImmUs2(AM.BaseOffs);
00878     }
00879     return AM.Scale == 2 && AM.BaseOffs == 0;
00880   case MVT::i32:
00881     // reg + imm
00882     if (AM.Scale == 0) {
00883       return isImmUs4(AM.BaseOffs);
00884     }
00885     // reg + reg<<2
00886     return AM.Scale == 4 && AM.BaseOffs == 0;
00887   }
00888   
00889   return false;
00890 }
00891 
00892 //===----------------------------------------------------------------------===//
00893 //                           XCore Inline Assembly Support
00894 //===----------------------------------------------------------------------===//
00895 
00896 std::vector<unsigned> XCoreTargetLowering::
00897 getRegClassForInlineAsmConstraint(const std::string &Constraint,
00898                                   MVT VT) const 
00899 {
00900   if (Constraint.size() != 1)
00901     return std::vector<unsigned>();
00902 
00903   switch (Constraint[0]) {
00904     default : break;
00905     case 'r':
00906       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
00907                                    XCore::R3, XCore::R4,  XCore::R5, 
00908                                    XCore::R6, XCore::R7,  XCore::R8, 
00909                                    XCore::R9, XCore::R10, XCore::R11, 0);
00910       break;
00911   }
00912   return std::vector<unsigned>();
00913 }