LLVM API Documentation

MSP430ISelLowering.cpp

Go to the documentation of this file.
00001 //===-- MSP430ISelLowering.cpp - MSP430 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 MSP430TargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "msp430-lower"
00015 
00016 #include "MSP430ISelLowering.h"
00017 #include "MSP430.h"
00018 #include "MSP430TargetMachine.h"
00019 #include "MSP430Subtarget.h"
00020 #include "llvm/DerivedTypes.h"
00021 #include "llvm/Function.h"
00022 #include "llvm/Intrinsics.h"
00023 #include "llvm/CallingConv.h"
00024 #include "llvm/GlobalVariable.h"
00025 #include "llvm/GlobalAlias.h"
00026 #include "llvm/CodeGen/CallingConvLower.h"
00027 #include "llvm/CodeGen/MachineFrameInfo.h"
00028 #include "llvm/CodeGen/MachineFunction.h"
00029 #include "llvm/CodeGen/MachineInstrBuilder.h"
00030 #include "llvm/CodeGen/MachineRegisterInfo.h"
00031 #include "llvm/CodeGen/PseudoSourceValue.h"
00032 #include "llvm/CodeGen/SelectionDAGISel.h"
00033 #include "llvm/CodeGen/ValueTypes.h"
00034 #include "llvm/Target/TargetLoweringObjectFile.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/ADT/VectorExtras.h"
00038 using namespace llvm;
00039 
00040 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
00041   TargetLowering(tm, new TargetLoweringObjectFileELF()),
00042   Subtarget(*tm.getSubtargetImpl()), TM(tm) {
00043 
00044   // Set up the register classes.
00045   addRegisterClass(MVT::i8,  MSP430::GR8RegisterClass);
00046   addRegisterClass(MVT::i16, MSP430::GR16RegisterClass);
00047 
00048   // Compute derived properties from the register classes
00049   computeRegisterProperties();
00050 
00051   // Provide all sorts of operation actions
00052 
00053   // Division is expensive
00054   setIntDivIsCheap(false);
00055 
00056   // Even if we have only 1 bit shift here, we can perform
00057   // shifts of the whole bitwidth 1 bit per step.
00058   setShiftAmountType(MVT::i8);
00059 
00060   setStackPointerRegisterToSaveRestore(MSP430::SPW);
00061   setBooleanContents(ZeroOrOneBooleanContent);
00062   setSchedulingPreference(SchedulingForLatency);
00063 
00064   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
00065   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00066   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
00067   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
00068   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
00069 
00070   // We don't have any truncstores
00071   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
00072 
00073   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
00074   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
00075   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
00076   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
00077   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
00078   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
00079   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
00080   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
00081   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
00082   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
00083   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
00084   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
00085   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
00086   setOperationAction(ISD::BRIND,            MVT::Other, Expand);
00087   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
00088   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
00089   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
00090   setOperationAction(ISD::SETCC,            MVT::i8,    Expand);
00091   setOperationAction(ISD::SETCC,            MVT::i16,   Expand);
00092   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
00093   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
00094   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
00095   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
00096   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
00097 
00098   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
00099   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
00100   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
00101   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
00102   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
00103   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
00104 
00105   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
00106   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
00107   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
00108   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
00109   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
00110   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
00111 
00112   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
00113 
00114   // FIXME: Implement efficiently multiplication by a constant
00115   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
00116   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
00117   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
00118   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
00119   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
00120 
00121   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
00122   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
00123   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
00124   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
00125   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
00126   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
00127 }
00128 
00129 SDValue MSP430TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
00130   switch (Op.getOpcode()) {
00131   case ISD::SHL: // FALLTHROUGH
00132   case ISD::SRL:
00133   case ISD::SRA:              return LowerShifts(Op, DAG);
00134   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
00135   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
00136   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
00137   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
00138   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
00139   default:
00140     llvm_unreachable("unimplemented operand");
00141     return SDValue();
00142   }
00143 }
00144 
00145 /// getFunctionAlignment - Return the Log2 alignment of this function.
00146 unsigned MSP430TargetLowering::getFunctionAlignment(const Function *F) const {
00147   return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
00148 }
00149 
00150 //===----------------------------------------------------------------------===//
00151 //                      Calling Convention Implementation
00152 //===----------------------------------------------------------------------===//
00153 
00154 #include "MSP430GenCallingConv.inc"
00155 
00156 SDValue
00157 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
00158                                            unsigned CallConv,
00159                                            bool isVarArg,
00160                                            const SmallVectorImpl<ISD::InputArg>
00161                                              &Ins,
00162                                            DebugLoc dl,
00163                                            SelectionDAG &DAG,
00164                                            SmallVectorImpl<SDValue> &InVals) {
00165 
00166   switch (CallConv) {
00167   default:
00168     llvm_unreachable("Unsupported calling convention");
00169   case CallingConv::C:
00170   case CallingConv::Fast:
00171     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
00172   }
00173 }
00174 
00175 SDValue
00176 MSP430TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
00177                                 unsigned CallConv, bool isVarArg,
00178                                 bool isTailCall,
00179                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
00180                                 const SmallVectorImpl<ISD::InputArg> &Ins,
00181                                 DebugLoc dl, SelectionDAG &DAG,
00182                                 SmallVectorImpl<SDValue> &InVals) {
00183 
00184   switch (CallConv) {
00185   default:
00186     llvm_unreachable("Unsupported calling convention");
00187   case CallingConv::Fast:
00188   case CallingConv::C:
00189     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
00190                           Outs, Ins, dl, DAG, InVals);
00191   }
00192 }
00193 
00194 /// LowerCCCArguments - transform physical registers into virtual registers and
00195 /// generate load operations for arguments places on the stack.
00196 // FIXME: struct return stuff
00197 // FIXME: varargs
00198 SDValue
00199 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
00200                                         unsigned CallConv,
00201                                         bool isVarArg,
00202                                         const SmallVectorImpl<ISD::InputArg>
00203                                           &Ins,
00204                                         DebugLoc dl,
00205                                         SelectionDAG &DAG,
00206                                         SmallVectorImpl<SDValue> &InVals) {
00207   MachineFunction &MF = DAG.getMachineFunction();
00208   MachineFrameInfo *MFI = MF.getFrameInfo();
00209   MachineRegisterInfo &RegInfo = MF.getRegInfo();
00210 
00211   // Assign locations to all of the incoming arguments.
00212   SmallVector<CCValAssign, 16> ArgLocs;
00213   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00214                  ArgLocs, *DAG.getContext());
00215   CCInfo.AnalyzeFormalArguments(Ins, CC_MSP430);
00216 
00217   assert(!isVarArg && "Varargs not supported yet");
00218 
00219   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00220     CCValAssign &VA = ArgLocs[i];
00221     if (VA.isRegLoc()) {
00222       // Arguments passed in registers
00223       EVT RegVT = VA.getLocVT();
00224       switch (RegVT.getSimpleVT().SimpleTy) {
00225       default: 
00226         {
00227 #ifndef NDEBUG
00228           cerr << "LowerFormalArguments Unhandled argument type: "
00229                << RegVT.getSimpleVT().SimpleTy << "\n";
00230 #endif
00231           llvm_unreachable(0);
00232         }
00233       case MVT::i16:
00234         unsigned VReg =
00235           RegInfo.createVirtualRegister(MSP430::GR16RegisterClass);
00236         RegInfo.addLiveIn(VA.getLocReg(), VReg);
00237         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
00238 
00239         // If this is an 8-bit value, it is really passed promoted to 16
00240         // bits. Insert an assert[sz]ext to capture this, then truncate to the
00241         // right size.
00242         if (VA.getLocInfo() == CCValAssign::SExt)
00243           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
00244                                  DAG.getValueType(VA.getValVT()));
00245         else if (VA.getLocInfo() == CCValAssign::ZExt)
00246           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
00247                                  DAG.getValueType(VA.getValVT()));
00248 
00249         if (VA.getLocInfo() != CCValAssign::Full)
00250           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
00251 
00252         InVals.push_back(ArgValue);
00253       }
00254     } else {
00255       // Sanity check
00256       assert(VA.isMemLoc());
00257       // Load the argument to a virtual register
00258       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
00259       if (ObjSize > 2) {
00260         cerr << "LowerFormalArguments Unhandled argument type: "
00261              << VA.getLocVT().getSimpleVT().SimpleTy
00262              << "\n";
00263       }
00264       // Create the frame index object for this incoming parameter...
00265       int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset());
00266 
00267       // Create the SelectionDAG nodes corresponding to a load
00268       //from this parameter
00269       SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
00270       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
00271                                    PseudoSourceValue::getFixedStack(FI), 0));
00272     }
00273   }
00274 
00275   return Chain;
00276 }
00277 
00278 SDValue
00279 MSP430TargetLowering::LowerReturn(SDValue Chain,
00280                                   unsigned CallConv, bool isVarArg,
00281                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
00282                                   DebugLoc dl, SelectionDAG &DAG) {
00283 
00284   // CCValAssign - represent the assignment of the return value to a location
00285   SmallVector<CCValAssign, 16> RVLocs;
00286 
00287   // CCState - Info about the registers and stack slot.
00288   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00289                  RVLocs, *DAG.getContext());
00290 
00291   // Analize return values.
00292   CCInfo.AnalyzeReturn(Outs, RetCC_MSP430);
00293 
00294   // If this is the first return lowered for this function, add the regs to the
00295   // liveout set for the function.
00296   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
00297     for (unsigned i = 0; i != RVLocs.size(); ++i)
00298       if (RVLocs[i].isRegLoc())
00299         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
00300   }
00301 
00302   SDValue Flag;
00303 
00304   // Copy the result values into the output registers.
00305   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00306     CCValAssign &VA = RVLocs[i];
00307     assert(VA.isRegLoc() && "Can only return in registers!");
00308 
00309     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
00310                              Outs[i].Val, Flag);
00311 
00312     // Guarantee that all emitted copies are stuck together,
00313     // avoiding something bad.
00314     Flag = Chain.getValue(1);
00315   }
00316 
00317   if (Flag.getNode())
00318     return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
00319 
00320   // Return Void
00321   return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain);
00322 }
00323 
00324 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
00325 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
00326 /// TODO: sret.
00327 SDValue
00328 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
00329                                      unsigned CallConv, bool isVarArg,
00330                                      bool isTailCall,
00331                                      const SmallVectorImpl<ISD::OutputArg>
00332                                        &Outs,
00333                                      const SmallVectorImpl<ISD::InputArg> &Ins,
00334                                      DebugLoc dl, SelectionDAG &DAG,
00335                                      SmallVectorImpl<SDValue> &InVals) {
00336   // Analyze operands of the call, assigning locations to each operand.
00337   SmallVector<CCValAssign, 16> ArgLocs;
00338   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00339                  ArgLocs, *DAG.getContext());
00340 
00341   CCInfo.AnalyzeCallOperands(Outs, CC_MSP430);
00342 
00343   // Get a count of how many bytes are to be pushed on the stack.
00344   unsigned NumBytes = CCInfo.getNextStackOffset();
00345 
00346   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
00347                                                       getPointerTy(), true));
00348 
00349   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
00350   SmallVector<SDValue, 12> MemOpChains;
00351   SDValue StackPtr;
00352 
00353   // Walk the register/memloc assignments, inserting copies/loads.
00354   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00355     CCValAssign &VA = ArgLocs[i];
00356 
00357     SDValue Arg = Outs[i].Val;
00358 
00359     // Promote the value if needed.
00360     switch (VA.getLocInfo()) {
00361       default: llvm_unreachable("Unknown loc info!");
00362       case CCValAssign::Full: break;
00363       case CCValAssign::SExt:
00364         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
00365         break;
00366       case CCValAssign::ZExt:
00367         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
00368         break;
00369       case CCValAssign::AExt:
00370         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
00371         break;
00372     }
00373 
00374     // Arguments that can be passed on register must be kept at RegsToPass
00375     // vector
00376     if (VA.isRegLoc()) {
00377       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
00378     } else {
00379       assert(VA.isMemLoc());
00380 
00381       if (StackPtr.getNode() == 0)
00382         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
00383 
00384       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
00385                                    StackPtr,
00386                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
00387 
00388 
00389       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
00390                                          PseudoSourceValue::getStack(),
00391                                          VA.getLocMemOffset()));
00392     }
00393   }
00394 
00395   // Transform all store nodes into one single node because all store nodes are
00396   // independent of each other.
00397   if (!MemOpChains.empty())
00398     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
00399                         &MemOpChains[0], MemOpChains.size());
00400 
00401   // Build a sequence of copy-to-reg nodes chained together with token chain and
00402   // flag operands which copy the outgoing args into registers.  The InFlag in
00403   // necessary since all emited instructions must be stuck together.
00404   SDValue InFlag;
00405   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
00406     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
00407                              RegsToPass[i].second, InFlag);
00408     InFlag = Chain.getValue(1);
00409   }
00410 
00411   // If the callee is a GlobalAddress node (quite common, every direct call is)
00412   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
00413   // Likewise ExternalSymbol -> TargetExternalSymbol.
00414   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
00415     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i16);
00416   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
00417     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
00418 
00419   // Returns a chain & a flag for retval copy to use.
00420   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
00421   SmallVector<SDValue, 8> Ops;
00422   Ops.push_back(Chain);
00423   Ops.push_back(Callee);
00424 
00425   // Add argument registers to the end of the list so that they are
00426   // known live into the call.
00427   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
00428     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
00429                                   RegsToPass[i].second.getValueType()));
00430 
00431   if (InFlag.getNode())
00432     Ops.push_back(InFlag);
00433 
00434   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
00435   InFlag = Chain.getValue(1);
00436 
00437   // Create the CALLSEQ_END node.
00438   Chain = DAG.getCALLSEQ_END(Chain,
00439                              DAG.getConstant(NumBytes, getPointerTy(), true),
00440                              DAG.getConstant(0, getPointerTy(), true),
00441                              InFlag);
00442   InFlag = Chain.getValue(1);
00443 
00444   // Handle result values, copying them out of physregs into vregs that we
00445   // return.
00446   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
00447                          DAG, InVals);
00448 }
00449 
00450 /// LowerCallResult - Lower the result values of a call into the
00451 /// appropriate copies out of appropriate physical registers.
00452 ///
00453 SDValue
00454 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
00455                                       unsigned CallConv, bool isVarArg,
00456                                       const SmallVectorImpl<ISD::InputArg> &Ins,
00457                                       DebugLoc dl, SelectionDAG &DAG,
00458                                       SmallVectorImpl<SDValue> &InVals) {
00459 
00460   // Assign locations to each value returned by this call.
00461   SmallVector<CCValAssign, 16> RVLocs;
00462   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00463                  RVLocs, *DAG.getContext());
00464 
00465   CCInfo.AnalyzeCallResult(Ins, RetCC_MSP430);
00466 
00467   // Copy all of the result registers out of their specified physreg.
00468   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00469     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
00470                                RVLocs[i].getValVT(), InFlag).getValue(1);
00471     InFlag = Chain.getValue(2);
00472     InVals.push_back(Chain.getValue(0));
00473   }
00474 
00475   return Chain;
00476 }
00477 
00478 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
00479                                           SelectionDAG &DAG) {
00480   unsigned Opc = Op.getOpcode();
00481   SDNode* N = Op.getNode();
00482   EVT VT = Op.getValueType();
00483   DebugLoc dl = N->getDebugLoc();
00484 
00485   // We currently only lower shifts of constant argument.
00486   if (!isa<ConstantSDNode>(N->getOperand(1)))
00487     return SDValue();
00488 
00489   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
00490 
00491   // Expand the stuff into sequence of shifts.
00492   // FIXME: for some shift amounts this might be done better!
00493   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
00494   SDValue Victim = N->getOperand(0);
00495 
00496   if (Opc == ISD::SRL && ShiftAmount) {
00497     // Emit a special goodness here:
00498     // srl A, 1 => clrc; rrc A
00499     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
00500     ShiftAmount -= 1;
00501   }
00502 
00503   while (ShiftAmount--)
00504     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
00505                          dl, VT, Victim);
00506 
00507   return Victim;
00508 }
00509 
00510 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
00511   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00512   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
00513 
00514   // Create the TargetGlobalAddress node, folding in the constant offset.
00515   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
00516   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
00517                      getPointerTy(), Result);
00518 }
00519 
00520 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
00521                                                   SelectionDAG &DAG) {
00522   DebugLoc dl = Op.getDebugLoc();
00523   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
00524   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
00525 
00526   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
00527 }
00528 
00529 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, unsigned &TargetCC,
00530                        ISD::CondCode CC,
00531                        DebugLoc dl, SelectionDAG &DAG) {
00532   // FIXME: Handle bittests someday
00533   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
00534 
00535   // FIXME: Handle jump negative someday
00536   TargetCC = MSP430::COND_INVALID;
00537   switch (CC) {
00538   default: llvm_unreachable("Invalid integer condition!");
00539   case ISD::SETEQ:
00540     TargetCC = MSP430::COND_E;  // aka COND_Z
00541     break;
00542   case ISD::SETNE:
00543     TargetCC = MSP430::COND_NE; // aka COND_NZ
00544     break;
00545   case ISD::SETULE:
00546     std::swap(LHS, RHS);        // FALLTHROUGH
00547   case ISD::SETUGE:
00548     TargetCC = MSP430::COND_HS; // aka COND_C
00549     break;
00550   case ISD::SETUGT:
00551     std::swap(LHS, RHS);        // FALLTHROUGH
00552   case ISD::SETULT:
00553     TargetCC = MSP430::COND_LO; // aka COND_NC
00554     break;
00555   case ISD::SETLE:
00556     std::swap(LHS, RHS);        // FALLTHROUGH
00557   case ISD::SETGE:
00558     TargetCC = MSP430::COND_GE;
00559     break;
00560   case ISD::SETGT:
00561     std::swap(LHS, RHS);        // FALLTHROUGH
00562   case ISD::SETLT:
00563     TargetCC = MSP430::COND_L;
00564     break;
00565   }
00566 
00567   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Flag, LHS, RHS);
00568 }
00569 
00570 
00571 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
00572   SDValue Chain = Op.getOperand(0);
00573   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
00574   SDValue LHS   = Op.getOperand(2);
00575   SDValue RHS   = Op.getOperand(3);
00576   SDValue Dest  = Op.getOperand(4);
00577   DebugLoc dl   = Op.getDebugLoc();
00578 
00579   unsigned TargetCC = MSP430::COND_INVALID;
00580   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
00581 
00582   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
00583                      Chain,
00584                      Dest, DAG.getConstant(TargetCC, MVT::i8),
00585                      Flag);
00586 }
00587 
00588 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
00589   SDValue LHS    = Op.getOperand(0);
00590   SDValue RHS    = Op.getOperand(1);
00591   SDValue TrueV  = Op.getOperand(2);
00592   SDValue FalseV = Op.getOperand(3);
00593   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
00594   DebugLoc dl    = Op.getDebugLoc();
00595 
00596   unsigned TargetCC = MSP430::COND_INVALID;
00597   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
00598 
00599   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
00600   SmallVector<SDValue, 4> Ops;
00601   Ops.push_back(TrueV);
00602   Ops.push_back(FalseV);
00603   Ops.push_back(DAG.getConstant(TargetCC, MVT::i8));
00604   Ops.push_back(Flag);
00605 
00606   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
00607 }
00608 
00609 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
00610                                                SelectionDAG &DAG) {
00611   SDValue Val = Op.getOperand(0);
00612   EVT VT      = Op.getValueType();
00613   DebugLoc dl = Op.getDebugLoc();
00614 
00615   assert(VT == MVT::i16 && "Only support i16 for now!");
00616 
00617   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
00618                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
00619                      DAG.getValueType(Val.getValueType()));
00620 }
00621 
00622 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
00623   switch (Opcode) {
00624   default: return NULL;
00625   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
00626   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
00627   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
00628   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
00629   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
00630   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
00631   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
00632   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
00633   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
00634   }
00635 }
00636 
00637 //===----------------------------------------------------------------------===//
00638 //  Other Lowering Code
00639 //===----------------------------------------------------------------------===//
00640 
00641 MachineBasicBlock*
00642 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00643                                                   MachineBasicBlock *BB) const {
00644   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
00645   DebugLoc dl = MI->getDebugLoc();
00646   assert((MI->getOpcode() == MSP430::Select16 ||
00647           MI->getOpcode() == MSP430::Select8) &&
00648          "Unexpected instr type to insert");
00649 
00650   // To "insert" a SELECT instruction, we actually have to insert the diamond
00651   // control-flow pattern.  The incoming instruction knows the destination vreg
00652   // to set, the condition code register to branch on, the true/false values to
00653   // select between, and a branch opcode to use.
00654   const BasicBlock *LLVM_BB = BB->getBasicBlock();
00655   MachineFunction::iterator I = BB;
00656   ++I;
00657 
00658   //  thisMBB:
00659   //  ...
00660   //   TrueVal = ...
00661   //   cmpTY ccX, r1, r2
00662   //   jCC copy1MBB
00663   //   fallthrough --> copy0MBB
00664   MachineBasicBlock *thisMBB = BB;
00665   MachineFunction *F = BB->getParent();
00666   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
00667   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
00668   BuildMI(BB, dl, TII.get(MSP430::JCC))
00669     .addMBB(copy1MBB)
00670     .addImm(MI->getOperand(3).getImm());
00671   F->insert(I, copy0MBB);
00672   F->insert(I, copy1MBB);
00673   // Update machine-CFG edges by transferring all successors of the current
00674   // block to the new block which will contain the Phi node for the select.
00675   copy1MBB->transferSuccessors(BB);
00676   // Next, add the true and fallthrough blocks as its successors.
00677   BB->addSuccessor(copy0MBB);
00678   BB->addSuccessor(copy1MBB);
00679 
00680   //  copy0MBB:
00681   //   %FalseValue = ...
00682   //   # fallthrough to copy1MBB
00683   BB = copy0MBB;
00684 
00685   // Update machine-CFG edges
00686   BB->addSuccessor(copy1MBB);
00687 
00688   //  copy1MBB:
00689   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
00690   //  ...
00691   BB = copy1MBB;
00692   BuildMI(BB, dl, TII.get(MSP430::PHI),
00693           MI->getOperand(0).getReg())
00694     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
00695     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
00696 
00697   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
00698   return BB;
00699 }