LLVM API Documentation

SparcISelDAGToDAG.cpp

Go to the documentation of this file.
00001 //===-- SparcISelDAGToDAG.cpp - A dag to dag inst selector for Sparc ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by Chris Lattner and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines an instruction selector for the SPARC target.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Sparc.h"
00015 #include "SparcTargetMachine.h"
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/Function.h"
00018 #include "llvm/Intrinsics.h"
00019 #include "llvm/CodeGen/MachineFrameInfo.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstrBuilder.h"
00022 #include "llvm/CodeGen/SelectionDAG.h"
00023 #include "llvm/CodeGen/SelectionDAGISel.h"
00024 #include "llvm/CodeGen/SSARegMap.h"
00025 #include "llvm/Target/TargetLowering.h"
00026 #include "llvm/Support/Debug.h"
00027 #include <iostream>
00028 #include <set>
00029 using namespace llvm;
00030 
00031 //===----------------------------------------------------------------------===//
00032 // TargetLowering Implementation
00033 //===----------------------------------------------------------------------===//
00034 
00035 namespace SPISD {
00036   enum {
00037     FIRST_NUMBER = ISD::BUILTIN_OP_END+SP::INSTRUCTION_LIST_END,
00038     CMPICC,      // Compare two GPR operands, set icc.
00039     CMPFCC,      // Compare two FP operands, set fcc.
00040     BRICC,       // Branch to dest on icc condition
00041     BRFCC,       // Branch to dest on fcc condition
00042     SELECT_ICC,  // Select between two values using the current ICC flags.
00043     SELECT_FCC,  // Select between two values using the current FCC flags.
00044     
00045     Hi, Lo,      // Hi/Lo operations, typically on a global address.
00046     
00047     FTOI,        // FP to Int within a FP register.
00048     ITOF,        // Int to FP within a FP register.
00049 
00050     CALL,        // A call instruction.
00051     RET_FLAG,    // Return with a flag operand.
00052   };
00053 }
00054 
00055 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
00056 /// condition.
00057 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
00058   switch (CC) {
00059   default: assert(0 && "Unknown integer condition code!");
00060   case ISD::SETEQ:  return SPCC::ICC_E;
00061   case ISD::SETNE:  return SPCC::ICC_NE;
00062   case ISD::SETLT:  return SPCC::ICC_L;
00063   case ISD::SETGT:  return SPCC::ICC_G;
00064   case ISD::SETLE:  return SPCC::ICC_LE;
00065   case ISD::SETGE:  return SPCC::ICC_GE;
00066   case ISD::SETULT: return SPCC::ICC_CS;
00067   case ISD::SETULE: return SPCC::ICC_LEU;
00068   case ISD::SETUGT: return SPCC::ICC_GU;
00069   case ISD::SETUGE: return SPCC::ICC_CC;
00070   }
00071 }
00072 
00073 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
00074 /// FCC condition.
00075 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
00076   switch (CC) {
00077   default: assert(0 && "Unknown fp condition code!");
00078   case ISD::SETEQ:  return SPCC::FCC_E;
00079   case ISD::SETNE:  return SPCC::FCC_NE;
00080   case ISD::SETLT:  return SPCC::FCC_L;
00081   case ISD::SETGT:  return SPCC::FCC_G;
00082   case ISD::SETLE:  return SPCC::FCC_LE;
00083   case ISD::SETGE:  return SPCC::FCC_GE;
00084   case ISD::SETULT: return SPCC::FCC_UL;
00085   case ISD::SETULE: return SPCC::FCC_ULE;
00086   case ISD::SETUGT: return SPCC::FCC_UG;
00087   case ISD::SETUGE: return SPCC::FCC_UGE;
00088   case ISD::SETUO:  return SPCC::FCC_U;
00089   case ISD::SETO:   return SPCC::FCC_O;
00090   case ISD::SETONE: return SPCC::FCC_LG;
00091   case ISD::SETUEQ: return SPCC::FCC_UE;
00092   }
00093 }
00094 
00095 namespace {
00096   class SparcTargetLowering : public TargetLowering {
00097     int VarArgsFrameOffset;   // Frame offset to start of varargs area.
00098   public:
00099     SparcTargetLowering(TargetMachine &TM);
00100     virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
00101     
00102     /// computeMaskedBitsForTargetNode - Determine which of the bits specified 
00103     /// in Mask are known to be either zero or one and return them in the 
00104     /// KnownZero/KnownOne bitsets.
00105     virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
00106                                                 uint64_t Mask,
00107                                                 uint64_t &KnownZero, 
00108                                                 uint64_t &KnownOne,
00109                                                 unsigned Depth = 0) const;
00110     
00111     virtual std::vector<SDOperand>
00112       LowerArguments(Function &F, SelectionDAG &DAG);
00113     virtual std::pair<SDOperand, SDOperand>
00114       LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
00115                   unsigned CC,
00116                   bool isTailCall, SDOperand Callee, ArgListTy &Args,
00117                   SelectionDAG &DAG);
00118     virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
00119                                                        MachineBasicBlock *MBB);
00120     
00121     virtual const char *getTargetNodeName(unsigned Opcode) const;
00122   };
00123 }
00124 
00125 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
00126   : TargetLowering(TM) {
00127   
00128   // Set up the register classes.
00129   addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
00130   addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
00131   addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
00132 
00133   // Custom legalize GlobalAddress nodes into LO/HI parts.
00134   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
00135   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
00136   
00137   // Sparc doesn't have sext_inreg, replace them with shl/sra
00138   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
00140   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
00141 
00142   // Sparc has no REM operation.
00143   setOperationAction(ISD::UREM, MVT::i32, Expand);
00144   setOperationAction(ISD::SREM, MVT::i32, Expand);
00145 
00146   // Custom expand fp<->sint
00147   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00148   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00149 
00150   // Expand fp<->uint
00151   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
00152   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
00153   
00154   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
00155   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
00156   
00157   // Turn FP extload into load/fextend
00158   setOperationAction(ISD::EXTLOAD, MVT::f32, Expand);
00159   
00160   // Sparc has no select or setcc: expand to SELECT_CC.
00161   setOperationAction(ISD::SELECT, MVT::i32, Expand);
00162   setOperationAction(ISD::SELECT, MVT::f32, Expand);
00163   setOperationAction(ISD::SELECT, MVT::f64, Expand);
00164   setOperationAction(ISD::SETCC, MVT::i32, Expand);
00165   setOperationAction(ISD::SETCC, MVT::f32, Expand);
00166   setOperationAction(ISD::SETCC, MVT::f64, Expand);
00167   
00168   // Sparc doesn't have BRCOND either, it has BR_CC.
00169   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
00170   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
00171   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
00172   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
00173   
00174   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
00175   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00176   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00177   
00178   // SPARC has no intrinsics for these particular operations.
00179   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
00180   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
00181   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
00182   
00183   setOperationAction(ISD::FSIN , MVT::f64, Expand);
00184   setOperationAction(ISD::FCOS , MVT::f64, Expand);
00185   setOperationAction(ISD::FSIN , MVT::f32, Expand);
00186   setOperationAction(ISD::FCOS , MVT::f32, Expand);
00187   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
00188   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
00189   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
00190   setOperationAction(ISD::ROTL , MVT::i32, Expand);
00191   setOperationAction(ISD::ROTR , MVT::i32, Expand);
00192   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00193   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
00194   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
00195 
00196   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
00197   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
00198   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
00199 
00200   // We don't have line number support yet.
00201   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
00202   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
00203   setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
00204 
00205   // RET must be custom lowered, to meet ABI requirements
00206   setOperationAction(ISD::RET               , MVT::Other, Custom);
00207   
00208   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
00209   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
00210   // VAARG needs to be lowered to not do unaligned accesses for doubles.
00211   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
00212   
00213   // Use the default implementation.
00214   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
00215   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
00216   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
00217   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
00218   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
00219 
00220   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
00221   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
00222   
00223   setStackPointerRegisterToSaveRestore(SP::O6);
00224 
00225   if (TM.getSubtarget<SparcSubtarget>().isV9()) {
00226     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
00227   }
00228   
00229   computeRegisterProperties();
00230 }
00231 
00232 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
00233   switch (Opcode) {
00234   default: return 0;
00235   case SPISD::CMPICC:     return "SPISD::CMPICC";
00236   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
00237   case SPISD::BRICC:      return "SPISD::BRICC";
00238   case SPISD::BRFCC:      return "SPISD::BRFCC";
00239   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
00240   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
00241   case SPISD::Hi:         return "SPISD::Hi";
00242   case SPISD::Lo:         return "SPISD::Lo";
00243   case SPISD::FTOI:       return "SPISD::FTOI";
00244   case SPISD::ITOF:       return "SPISD::ITOF";
00245   case SPISD::CALL:       return "SPISD::CALL";
00246   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
00247   }
00248 }
00249 
00250 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
00251 /// be zero. Op is expected to be a target specific node. Used by DAG
00252 /// combiner.
00253 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
00254                                                          uint64_t Mask,
00255                                                          uint64_t &KnownZero, 
00256                                                          uint64_t &KnownOne,
00257                                                          unsigned Depth) const {
00258   uint64_t KnownZero2, KnownOne2;
00259   KnownZero = KnownOne = 0;   // Don't know anything.
00260   
00261   switch (Op.getOpcode()) {
00262   default: break;
00263   case SPISD::SELECT_ICC:
00264   case SPISD::SELECT_FCC:
00265     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
00266     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
00267     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
00268     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
00269     
00270     // Only known if known in both the LHS and RHS.
00271     KnownOne &= KnownOne2;
00272     KnownZero &= KnownZero2;
00273     break;
00274   }
00275 }
00276 
00277 /// LowerArguments - V8 uses a very simple ABI, where all values are passed in
00278 /// either one or two GPRs, including FP values.  TODO: we should pass FP values
00279 /// in FP registers for fastcc functions.
00280 std::vector<SDOperand>
00281 SparcTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
00282   MachineFunction &MF = DAG.getMachineFunction();
00283   SSARegMap *RegMap = MF.getSSARegMap();
00284   std::vector<SDOperand> ArgValues;
00285   
00286   static const unsigned ArgRegs[] = {
00287     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
00288   };
00289   
00290   const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
00291   unsigned ArgOffset = 68;
00292   
00293   SDOperand Root = DAG.getRoot();
00294   std::vector<SDOperand> OutChains;
00295 
00296   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
00297     MVT::ValueType ObjectVT = getValueType(I->getType());
00298     
00299     switch (ObjectVT) {
00300     default: assert(0 && "Unhandled argument type!");
00301     case MVT::i1:
00302     case MVT::i8:
00303     case MVT::i16:
00304     case MVT::i32:
00305       if (I->use_empty()) {                // Argument is dead.
00306         if (CurArgReg < ArgRegEnd) ++CurArgReg;
00307         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
00308       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
00309         unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
00310         MF.addLiveIn(*CurArgReg++, VReg);
00311         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
00312         if (ObjectVT != MVT::i32) {
00313           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
00314                                                        : ISD::AssertZext;
00315           Arg = DAG.getNode(AssertOp, MVT::i32, Arg, 
00316                             DAG.getValueType(ObjectVT));
00317           Arg = DAG.getNode(ISD::TRUNCATE, ObjectVT, Arg);
00318         }
00319         ArgValues.push_back(Arg);
00320       } else {
00321         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
00322         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
00323         SDOperand Load;
00324         if (ObjectVT == MVT::i32) {
00325           Load = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
00326         } else {
00327           unsigned LoadOp =
00328             I->getType()->isSigned() ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
00329 
00330           // Sparc is big endian, so add an offset based on the ObjectVT.
00331           unsigned Offset = 4-std::max(1U, MVT::getSizeInBits(ObjectVT)/8);
00332           FIPtr = DAG.getNode(ISD::ADD, MVT::i32, FIPtr,
00333                               DAG.getConstant(Offset, MVT::i32));
00334           Load = DAG.getExtLoad(LoadOp, MVT::i32, Root, FIPtr,
00335                                 DAG.getSrcValue(0), ObjectVT);
00336           Load = DAG.getNode(ISD::TRUNCATE, ObjectVT, Load);
00337         }
00338         ArgValues.push_back(Load);
00339       }
00340       
00341       ArgOffset += 4;
00342       break;
00343     case MVT::f32:
00344       if (I->use_empty()) {                // Argument is dead.
00345         if (CurArgReg < ArgRegEnd) ++CurArgReg;
00346         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
00347       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
00348         // FP value is passed in an integer register.
00349         unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
00350         MF.addLiveIn(*CurArgReg++, VReg);
00351         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
00352 
00353         Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Arg);
00354         ArgValues.push_back(Arg);
00355       } else {
00356         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
00357         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
00358         SDOperand Load = DAG.getLoad(MVT::f32, Root, FIPtr, DAG.getSrcValue(0));
00359         ArgValues.push_back(Load);
00360       }
00361       ArgOffset += 4;
00362       break;
00363 
00364     case MVT::i64:
00365     case MVT::f64:
00366       if (I->use_empty()) {                // Argument is dead.
00367         if (CurArgReg < ArgRegEnd) ++CurArgReg;
00368         if (CurArgReg < ArgRegEnd) ++CurArgReg;
00369         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
00370       } else if (/* FIXME: Apparently this isn't safe?? */
00371                  0 && CurArgReg == ArgRegEnd && ObjectVT == MVT::f64 &&
00372                  ((CurArgReg-ArgRegs) & 1) == 0) {
00373         // If this is a double argument and the whole thing lives on the stack,
00374         // and the argument is aligned, load the double straight from the stack.
00375         // We can't do a load in cases like void foo([6ints], int,double),
00376         // because the double wouldn't be aligned!
00377         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(8, ArgOffset);
00378         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
00379         ArgValues.push_back(DAG.getLoad(MVT::f64, Root, FIPtr, 
00380                                         DAG.getSrcValue(0)));
00381       } else {
00382         SDOperand HiVal;
00383         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
00384           unsigned VRegHi = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
00385           MF.addLiveIn(*CurArgReg++, VRegHi);
00386           HiVal = DAG.getCopyFromReg(Root, VRegHi, MVT::i32);
00387         } else {
00388           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
00389           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
00390           HiVal = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
00391         }
00392         
00393         SDOperand LoVal;
00394         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
00395           unsigned VRegLo = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
00396           MF.addLiveIn(*CurArgReg++, VRegLo);
00397           LoVal = DAG.getCopyFromReg(Root, VRegLo, MVT::i32);
00398         } else {
00399           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4);
00400           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
00401           LoVal = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
00402         }
00403         
00404         // Compose the two halves together into an i64 unit.
00405         SDOperand WholeValue = 
00406           DAG.getNode(ISD::BUILD_PAIR, MVT::i64, LoVal, HiVal);
00407         
00408         // If we want a double, do a bit convert.
00409         if (ObjectVT == MVT::f64)
00410           WholeValue = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, WholeValue);
00411         
00412         ArgValues.push_back(WholeValue);
00413       }
00414       ArgOffset += 8;
00415       break;
00416     }
00417   }
00418   
00419   // Store remaining ArgRegs to the stack if this is a varargs function.
00420   if (F.getFunctionType()->isVarArg()) {
00421     // Remember the vararg offset for the va_start implementation.
00422     VarArgsFrameOffset = ArgOffset;
00423     
00424     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
00425       unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
00426       MF.addLiveIn(*CurArgReg, VReg);
00427       SDOperand Arg = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
00428 
00429       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
00430       SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
00431 
00432       OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getRoot(),
00433                                       Arg, FIPtr, DAG.getSrcValue(0)));
00434       ArgOffset += 4;
00435     }
00436   }
00437   
00438   if (!OutChains.empty())
00439     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
00440   
00441   // Finally, inform the code generator which regs we return values in.
00442   switch (getValueType(F.getReturnType())) {
00443   default: assert(0 && "Unknown type!");
00444   case MVT::isVoid: break;
00445   case MVT::i1:
00446   case MVT::i8:
00447   case MVT::i16:
00448   case MVT::i32:
00449     MF.addLiveOut(SP::I0);
00450     break;
00451   case MVT::i64:
00452     MF.addLiveOut(SP::I0);
00453     MF.addLiveOut(SP::I1);
00454     break;
00455   case MVT::f32:
00456     MF.addLiveOut(SP::F0);
00457     break;
00458   case MVT::f64:
00459     MF.addLiveOut(SP::D0);
00460     break;
00461   }
00462   
00463   return ArgValues;
00464 }
00465 
00466 std::pair<SDOperand, SDOperand>
00467 SparcTargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
00468                                  bool isVarArg, unsigned CC,
00469                                  bool isTailCall, SDOperand Callee, 
00470                                  ArgListTy &Args, SelectionDAG &DAG) {
00471   MachineFunction &MF = DAG.getMachineFunction();
00472   // Count the size of the outgoing arguments.
00473   unsigned ArgsSize = 0;
00474   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
00475     switch (getValueType(Args[i].second)) {
00476     default: assert(0 && "Unknown value type!");
00477     case MVT::i1:
00478     case MVT::i8:
00479     case MVT::i16:
00480     case MVT::i32:
00481     case MVT::f32:
00482       ArgsSize += 4;
00483       break;
00484     case MVT::i64:
00485     case MVT::f64:
00486       ArgsSize += 8;
00487       break;
00488     }
00489   }
00490   if (ArgsSize > 4*6)
00491     ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
00492   else
00493     ArgsSize = 0;
00494 
00495   // Keep stack frames 8-byte aligned.
00496   ArgsSize = (ArgsSize+7) & ~7;
00497 
00498   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(ArgsSize, getPointerTy()));
00499   
00500   SDOperand StackPtr, NullSV;
00501   std::vector<SDOperand> Stores;
00502   std::vector<SDOperand> RegValuesToPass;
00503   unsigned ArgOffset = 68;
00504   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
00505     SDOperand Val = Args[i].first;
00506     MVT::ValueType ObjectVT = Val.getValueType();
00507     SDOperand ValToStore(0, 0);
00508     unsigned ObjSize;
00509     switch (ObjectVT) {
00510     default: assert(0 && "Unhandled argument type!");
00511     case MVT::i1:
00512     case MVT::i8:
00513     case MVT::i16:
00514       // Promote the integer to 32-bits.  If the input type is signed, use a
00515       // sign extend, otherwise use a zero extend.
00516       if (Args[i].second->isSigned())
00517         Val = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Val);
00518       else
00519         Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Val);
00520       // FALL THROUGH
00521     case MVT::i32:
00522       ObjSize = 4;
00523 
00524       if (RegValuesToPass.size() >= 6) {
00525         ValToStore = Val;
00526       } else {
00527         RegValuesToPass.push_back(Val);
00528       }
00529       break;
00530     case MVT::f32:
00531       ObjSize = 4;
00532       if (RegValuesToPass.size() >= 6) {
00533         ValToStore = Val;
00534       } else {
00535         // Convert this to a FP value in an int reg.
00536         Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Val);
00537         RegValuesToPass.push_back(Val);
00538       }
00539       break;
00540     case MVT::f64:
00541       ObjSize = 8;
00542       // If we can store this directly into the outgoing slot, do so.  We can
00543       // do this when all ArgRegs are used and if the outgoing slot is aligned.
00544       // FIXME: McGill/misr fails with this.
00545       if (0 && RegValuesToPass.size() >= 6 && ((ArgOffset-68) & 7) == 0) {
00546         ValToStore = Val;
00547         break;
00548       }
00549       
00550       // Otherwise, convert this to a FP value in int regs.
00551       Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Val);
00552       // FALL THROUGH
00553     case MVT::i64:
00554       ObjSize = 8;
00555       if (RegValuesToPass.size() >= 6) {
00556         ValToStore = Val;    // Whole thing is passed in memory.
00557         break;
00558       }
00559       
00560       // Split the value into top and bottom part.  Top part goes in a reg.
00561       SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Val, 
00562                                  DAG.getConstant(1, MVT::i32));
00563       SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Val,
00564                                  DAG.getConstant(0, MVT::i32));
00565       RegValuesToPass.push_back(Hi);
00566       
00567       if (RegValuesToPass.size() >= 6) {
00568         ValToStore = Lo;
00569         ArgOffset += 4;
00570         ObjSize = 4;
00571       } else {
00572         RegValuesToPass.push_back(Lo);
00573       }
00574       break;
00575     }
00576     
00577     if (ValToStore.Val) {
00578       if (!StackPtr.Val) {
00579         StackPtr = DAG.getRegister(SP::O6, MVT::i32);
00580         NullSV = DAG.getSrcValue(NULL);
00581       }
00582       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
00583       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
00584       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
00585                                    ValToStore, PtrOff, NullSV));
00586     }
00587     ArgOffset += ObjSize;
00588   }
00589   
00590   // Emit all stores, make sure the occur before any copies into physregs.
00591   if (!Stores.empty())
00592     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
00593   
00594   static const unsigned ArgRegs[] = {
00595     SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5
00596   };
00597   
00598   // Build a sequence of copy-to-reg nodes chained together with token chain
00599   // and flag operands which copy the outgoing args into O[0-5].
00600   SDOperand InFlag;
00601   for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
00602     Chain = DAG.getCopyToReg(Chain, ArgRegs[i], RegValuesToPass[i], InFlag);
00603     InFlag = Chain.getValue(1);
00604   }
00605 
00606   // If the callee is a GlobalAddress node (quite common, every direct call is)
00607   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
00608   // Likewise ExternalSymbol -> TargetExternalSymbol.
00609   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
00610     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
00611   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
00612     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
00613 
00614   std::vector<MVT::ValueType> NodeTys;
00615   NodeTys.push_back(MVT::Other);   // Returns a chain
00616   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
00617   std::vector<SDOperand> Ops;
00618   Ops.push_back(Chain);
00619   Ops.push_back(Callee);
00620   if (InFlag.Val)
00621     Ops.push_back(InFlag);
00622   Chain = DAG.getNode(SPISD::CALL, NodeTys, Ops);
00623   InFlag = Chain.getValue(1);
00624   
00625   MVT::ValueType RetTyVT = getValueType(RetTy);
00626   SDOperand RetVal;
00627   if (RetTyVT != MVT::isVoid) {
00628     switch (RetTyVT) {
00629     default: assert(0 && "Unknown value type to return!");
00630     case MVT::i1:
00631     case MVT::i8:
00632     case MVT::i16:
00633       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
00634       Chain = RetVal.getValue(1);
00635       
00636       // Add a note to keep track of whether it is sign or zero extended.
00637       RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext :ISD::AssertZext,
00638                            MVT::i32, RetVal, DAG.getValueType(RetTyVT));
00639       RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
00640       break;
00641     case MVT::i32:
00642       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
00643       Chain = RetVal.getValue(1);
00644       break;
00645     case MVT::f32:
00646       RetVal = DAG.getCopyFromReg(Chain, SP::F0, MVT::f32, InFlag);
00647       Chain = RetVal.getValue(1);
00648       break;
00649     case MVT::f64:
00650       RetVal = DAG.getCopyFromReg(Chain, SP::D0, MVT::f64, InFlag);
00651       Chain = RetVal.getValue(1);
00652       break;
00653     case MVT::i64:
00654       SDOperand Lo = DAG.getCopyFromReg(Chain, SP::O1, MVT::i32, InFlag);
00655       SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), SP::O0, MVT::i32, 
00656                                         Lo.getValue(2));
00657       RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
00658       Chain = Hi.getValue(1);
00659       break;
00660     }
00661   }
00662   
00663   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
00664                       DAG.getConstant(ArgsSize, getPointerTy()));
00665   
00666   return std::make_pair(RetVal, Chain);
00667 }
00668 
00669 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
00670 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
00671 static void LookThroughSetCC(SDOperand &LHS, SDOperand &RHS,
00672                              ISD::CondCode CC, unsigned &SPCC) {
00673   if (isa<ConstantSDNode>(RHS) && cast<ConstantSDNode>(RHS)->getValue() == 0 &&
00674       CC == ISD::SETNE && 
00675       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
00676         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
00677        (LHS.getOpcode() == SPISD::SELECT_FCC &&
00678         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
00679       isa<ConstantSDNode>(LHS.getOperand(0)) &&
00680       isa<ConstantSDNode>(LHS.getOperand(1)) &&
00681       cast<ConstantSDNode>(LHS.getOperand(0))->getValue() == 1 &&
00682       cast<ConstantSDNode>(LHS.getOperand(1))->getValue() == 0) {
00683     SDOperand CMPCC = LHS.getOperand(3);
00684     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getValue();
00685     LHS = CMPCC.getOperand(0);
00686     RHS = CMPCC.getOperand(1);
00687   }
00688 }
00689 
00690 
00691 SDOperand SparcTargetLowering::
00692 LowerOperation(SDOperand Op, SelectionDAG &DAG) {
00693   switch (Op.getOpcode()) {
00694   default: assert(0 && "Should not custom lower this!");
00695   case ISD::GlobalAddress: {
00696     GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00697     SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
00698     SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, GA);
00699     SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, GA);
00700     return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
00701   }
00702   case ISD::ConstantPool: {
00703     Constant *C = cast<ConstantPoolSDNode>(Op)->get();
00704     SDOperand CP = DAG.getTargetConstantPool(C, MVT::i32,
00705                                   cast<ConstantPoolSDNode>(Op)->getAlignment());
00706     SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, CP);
00707     SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, CP);
00708     return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
00709   }
00710   case ISD::FP_TO_SINT:
00711     // Convert the fp value to integer in an FP register.
00712     assert(Op.getValueType() == MVT::i32);
00713     Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
00714     return DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
00715   case ISD::SINT_TO_FP: {
00716     assert(Op.getOperand(0).getValueType() == MVT::i32);
00717     SDOperand Tmp = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Op.getOperand(0));
00718     // Convert the int value to FP in an FP register.
00719     return DAG.getNode(SPISD::ITOF, Op.getValueType(), Tmp);
00720   }
00721   case ISD::BR_CC: {
00722     SDOperand Chain = Op.getOperand(0);
00723     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
00724     SDOperand LHS = Op.getOperand(2);
00725     SDOperand RHS = Op.getOperand(3);
00726     SDOperand Dest = Op.getOperand(4);
00727     unsigned Opc, SPCC = ~0U;
00728     
00729     // If this is a br_cc of a "setcc", and if the setcc got lowered into
00730     // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
00731     LookThroughSetCC(LHS, RHS, CC, SPCC);
00732     
00733     // Get the condition flag.
00734     SDOperand CompareFlag;
00735     if (LHS.getValueType() == MVT::i32) {
00736       std::vector<MVT::ValueType> VTs;
00737       VTs.push_back(MVT::i32);
00738       VTs.push_back(MVT::Flag);
00739       std::vector<SDOperand> Ops;
00740       Ops.push_back(LHS);
00741       Ops.push_back(RHS);
00742       CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1);
00743       if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
00744       Opc = SPISD::BRICC;
00745     } else {
00746       CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
00747       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
00748       Opc = SPISD::BRFCC;
00749     }
00750     return DAG.getNode(Opc, MVT::Other, Chain, Dest,
00751                        DAG.getConstant(SPCC, MVT::i32), CompareFlag);
00752   }
00753   case ISD::SELECT_CC: {
00754     SDOperand LHS = Op.getOperand(0);
00755     SDOperand RHS = Op.getOperand(1);
00756     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
00757     SDOperand TrueVal = Op.getOperand(2);
00758     SDOperand FalseVal = Op.getOperand(3);
00759     unsigned Opc, SPCC = ~0U;
00760 
00761     // If this is a select_cc of a "setcc", and if the setcc got lowered into
00762     // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
00763     LookThroughSetCC(LHS, RHS, CC, SPCC);
00764     
00765     SDOperand CompareFlag;
00766     if (LHS.getValueType() == MVT::i32) {
00767       std::vector<MVT::ValueType> VTs;
00768       VTs.push_back(LHS.getValueType());   // subcc returns a value
00769       VTs.push_back(MVT::Flag);
00770       std::vector<SDOperand> Ops;
00771       Ops.push_back(LHS);
00772       Ops.push_back(RHS);
00773       CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1);
00774       Opc = SPISD::SELECT_ICC;
00775       if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
00776     } else {
00777       CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
00778       Opc = SPISD::SELECT_FCC;
00779       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
00780     }
00781     return DAG.getNode(Opc, TrueVal.getValueType(), TrueVal, FalseVal, 
00782                        DAG.getConstant(SPCC, MVT::i32), CompareFlag);
00783   }
00784   case ISD::VASTART: {
00785     // vastart just stores the address of the VarArgsFrameIndex slot into the
00786     // memory location argument.
00787     SDOperand Offset = DAG.getNode(ISD::ADD, MVT::i32,
00788                                    DAG.getRegister(SP::I6, MVT::i32),
00789                                 DAG.getConstant(VarArgsFrameOffset, MVT::i32));
00790     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), Offset, 
00791                        Op.getOperand(1), Op.getOperand(2));
00792   }
00793   case ISD::VAARG: {
00794     SDNode *Node = Op.Val;
00795     MVT::ValueType VT = Node->getValueType(0);
00796     SDOperand InChain = Node->getOperand(0);
00797     SDOperand VAListPtr = Node->getOperand(1);
00798     SDOperand VAList = DAG.getLoad(getPointerTy(), InChain, VAListPtr,
00799                                    Node->getOperand(2));
00800     // Increment the pointer, VAList, to the next vaarg
00801     SDOperand NextPtr = DAG.getNode(ISD::ADD, getPointerTy(), VAList, 
00802                                     DAG.getConstant(MVT::getSizeInBits(VT)/8, 
00803                                                     getPointerTy()));
00804     // Store the incremented VAList to the legalized pointer
00805     InChain = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), NextPtr,
00806                           VAListPtr, Node->getOperand(2));
00807     // Load the actual argument out of the pointer VAList, unless this is an
00808     // f64 load.
00809     if (VT != MVT::f64) {
00810       return DAG.getLoad(VT, InChain, VAList, DAG.getSrcValue(0));
00811     } else {
00812       // Otherwise, load it as i64, then do a bitconvert.
00813       SDOperand V = DAG.getLoad(MVT::i64, InChain, VAList, DAG.getSrcValue(0));
00814       std::vector<MVT::ValueType> Tys;
00815       Tys.push_back(MVT::f64);
00816       Tys.push_back(MVT::Other);
00817       std::vector<SDOperand> Ops;
00818       // Bit-Convert the value to f64.
00819       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, MVT::f64, V));
00820       Ops.push_back(V.getValue(1));
00821       return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
00822     }
00823   }
00824   case ISD::DYNAMIC_STACKALLOC: {
00825     SDOperand Chain = Op.getOperand(0);  // Legalize the chain.
00826     SDOperand Size  = Op.getOperand(1);  // Legalize the size.
00827     
00828     unsigned SPReg = SP::O6;
00829     SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, MVT::i32);
00830     SDOperand NewSP = DAG.getNode(ISD::SUB, MVT::i32, SP, Size);    // Value
00831     Chain = DAG.getCopyToReg(SP.getValue(1), SPReg, NewSP);      // Output chain
00832 
00833     // The resultant pointer is actually 16 words from the bottom of the stack,
00834     // to provide a register spill area.
00835     SDOperand NewVal = DAG.getNode(ISD::ADD, MVT::i32, NewSP,
00836                                    DAG.getConstant(96, MVT::i32));
00837     std::vector<MVT::ValueType> Tys;
00838     Tys.push_back(MVT::i32);
00839     Tys.push_back(MVT::Other);
00840     std::vector<SDOperand> Ops;
00841     Ops.push_back(NewVal);
00842     Ops.push_back(Chain);
00843     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
00844   }
00845   case ISD::RET: {
00846     SDOperand Copy;
00847     
00848     switch(Op.getNumOperands()) {
00849     default:
00850       assert(0 && "Do not know how to return this many arguments!");
00851       abort();
00852     case 1: 
00853       return SDOperand(); // ret void is legal
00854     case 2: {
00855       unsigned ArgReg;
00856       switch(Op.getOperand(1).getValueType()) {
00857       default: assert(0 && "Unknown type to return!");
00858       case MVT::i32: ArgReg = SP::I0; break;
00859       case MVT::f32: ArgReg = SP::F0; break;
00860       case MVT::f64: ArgReg = SP::D0; break;
00861       }
00862       Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
00863                               SDOperand());
00864       break;
00865     }
00866     case 3:
00867       Copy = DAG.getCopyToReg(Op.getOperand(0), SP::I0, Op.getOperand(2), 
00868                               SDOperand());
00869       Copy = DAG.getCopyToReg(Copy, SP::I1, Op.getOperand(1), Copy.getValue(1));
00870       break;
00871     }
00872     return DAG.getNode(SPISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
00873   }
00874   }
00875 }
00876 
00877 MachineBasicBlock *
00878 SparcTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
00879                                              MachineBasicBlock *BB) {
00880   unsigned BROpcode;
00881   unsigned CC;
00882   // Figure out the conditional branch opcode to use for this select_cc.
00883   switch (MI->getOpcode()) {
00884   default: assert(0 && "Unknown SELECT_CC!");
00885   case SP::SELECT_CC_Int_ICC:
00886   case SP::SELECT_CC_FP_ICC:
00887   case SP::SELECT_CC_DFP_ICC:
00888     BROpcode = SP::BCOND;
00889     break;
00890   case SP::SELECT_CC_Int_FCC:
00891   case SP::SELECT_CC_FP_FCC:
00892   case SP::SELECT_CC_DFP_FCC:
00893     BROpcode = SP::FBCOND;
00894     break;
00895   }
00896 
00897   CC = (SPCC::CondCodes)MI->getOperand(3).getImmedValue();
00898   
00899   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
00900   // control-flow pattern.  The incoming instruction knows the destination vreg
00901   // to set, the condition code register to branch on, the true/false values to
00902   // select between, and a branch opcode to use.
00903   const BasicBlock *LLVM_BB = BB->getBasicBlock();
00904   ilist<MachineBasicBlock>::iterator It = BB;
00905   ++It;
00906   
00907   //  thisMBB:
00908   //  ...
00909   //   TrueVal = ...
00910   //   [f]bCC copy1MBB
00911   //   fallthrough --> copy0MBB
00912   MachineBasicBlock *thisMBB = BB;
00913   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
00914   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
00915   BuildMI(BB, BROpcode, 2).addMBB(sinkMBB).addImm(CC);
00916   MachineFunction *F = BB->getParent();
00917   F->getBasicBlockList().insert(It, copy0MBB);
00918   F->getBasicBlockList().insert(It, sinkMBB);
00919   // Update machine-CFG edges by first adding all successors of the current
00920   // block to the new block which will contain the Phi node for the select.
00921   for(MachineBasicBlock::succ_iterator i = BB->succ_begin(), 
00922       e = BB->succ_end(); i != e; ++i)
00923     sinkMBB->addSuccessor(*i);
00924   // Next, remove all successors of the current block, and add the true
00925   // and fallthrough blocks as its successors.
00926   while(!BB->succ_empty())
00927     BB->removeSuccessor(BB->succ_begin());
00928   BB->addSuccessor(copy0MBB);
00929   BB->addSuccessor(sinkMBB);
00930   
00931   //  copy0MBB:
00932   //   %FalseValue = ...
00933   //   # fallthrough to sinkMBB
00934   BB = copy0MBB;
00935   
00936   // Update machine-CFG edges
00937   BB->addSuccessor(sinkMBB);
00938   
00939   //  sinkMBB:
00940   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
00941   //  ...
00942   BB = sinkMBB;
00943   BuildMI(BB, SP::PHI, 4, MI->getOperand(0).getReg())
00944     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
00945     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
00946   
00947   delete MI;   // The pseudo instruction is gone now.
00948   return BB;
00949 }
00950   
00951 //===----------------------------------------------------------------------===//
00952 // Instruction Selector Implementation
00953 //===----------------------------------------------------------------------===//
00954 
00955 //===--------------------------------------------------------------------===//
00956 /// SparcDAGToDAGISel - SPARC specific code to select SPARC machine
00957 /// instructions for SelectionDAG operations.
00958 ///
00959 namespace {
00960 class SparcDAGToDAGISel : public SelectionDAGISel {
00961   SparcTargetLowering Lowering;
00962 
00963   /// Subtarget - Keep a pointer to the Sparc Subtarget around so that we can
00964   /// make the right decision when generating code for different targets.
00965   const SparcSubtarget &Subtarget;
00966 public:
00967   SparcDAGToDAGISel(TargetMachine &TM)
00968     : SelectionDAGISel(Lowering), Lowering(TM),
00969       Subtarget(TM.getSubtarget<SparcSubtarget>()) {
00970   }
00971 
00972   void Select(SDOperand &Result, SDOperand Op);
00973 
00974   // Complex Pattern Selectors.
00975   bool SelectADDRrr(SDOperand N, SDOperand &R1, SDOperand &R2);
00976   bool SelectADDRri(SDOperand N, SDOperand &Base, SDOperand &Offset);
00977   
00978   /// InstructionSelectBasicBlock - This callback is invoked by
00979   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
00980   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
00981   
00982   virtual const char *getPassName() const {
00983     return "SPARC DAG->DAG Pattern Instruction Selection";
00984   } 
00985   
00986   // Include the pieces autogenerated from the target description.
00987 #include "SparcGenDAGISel.inc"
00988 };
00989 }  // end anonymous namespace
00990 
00991 /// InstructionSelectBasicBlock - This callback is invoked by
00992 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
00993 void SparcDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
00994   DEBUG(BB->dump());
00995   
00996   // Select target instructions for the DAG.
00997   DAG.setRoot(SelectRoot(DAG.getRoot()));
00998   CodeGenMap.clear();
00999   DAG.RemoveDeadNodes();
01000   
01001   // Emit machine code to BB. 
01002   ScheduleAndEmitDAG(DAG);
01003 }
01004 
01005 bool SparcDAGToDAGISel::SelectADDRri(SDOperand Addr, SDOperand &Base,
01006                                      SDOperand &Offset) {
01007   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
01008     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
01009     Offset = CurDAG->getTargetConstant(0, MVT::i32);
01010     return true;
01011   }
01012   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
01013       Addr.getOpcode() == ISD::TargetGlobalAddress)
01014     return false;  // direct calls.
01015   
01016   if (Addr.getOpcode() == ISD::ADD) {
01017     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
01018       if (Predicate_simm13(CN)) {
01019         if (FrameIndexSDNode *FIN = 
01020                 dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
01021           // Constant offset from frame ref.
01022           Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
01023         } else {
01024           Base = Addr.getOperand(0);
01025         }
01026         Offset = CurDAG->getTargetConstant(CN->getValue(), MVT::i32);
01027         return true;
01028       }
01029     }
01030     if (Addr.getOperand(0).getOpcode() == SPISD::Lo) {
01031       Base = Addr.getOperand(1);
01032       Offset = Addr.getOperand(0).getOperand(0);
01033       return true;
01034     }
01035     if (Addr.getOperand(1).getOpcode() == SPISD::Lo) {
01036       Base = Addr.getOperand(0);
01037       Offset = Addr.getOperand(1).getOperand(0);
01038       return true;
01039     }
01040   }
01041   Base = Addr;
01042   Offset = CurDAG->getTargetConstant(0, MVT::i32);
01043   return true;
01044 }
01045 
01046 bool SparcDAGToDAGISel::SelectADDRrr(SDOperand Addr, SDOperand &R1, 
01047                                      SDOperand &R2) {
01048   if (Addr.getOpcode() == ISD::FrameIndex) return false;
01049   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
01050       Addr.getOpcode() == ISD::TargetGlobalAddress)
01051     return false;  // direct calls.
01052   
01053   if (Addr.getOpcode() == ISD::ADD) {
01054     if (isa<ConstantSDNode>(Addr.getOperand(1)) &&
01055         Predicate_simm13(Addr.getOperand(1).Val))
01056       return false;  // Let the reg+imm pattern catch this!
01057     if (Addr.getOperand(0).getOpcode() == SPISD::Lo ||
01058         Addr.getOperand(1).getOpcode() == SPISD::Lo)
01059       return false;  // Let the reg+imm pattern catch this!
01060     R1 = Addr.getOperand(0);
01061     R2 = Addr.getOperand(1);
01062     return true;
01063   }
01064 
01065   R1 = Addr;
01066   R2 = CurDAG->getRegister(SP::G0, MVT::i32);
01067   return true;
01068 }
01069 
01070 void SparcDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
01071   SDNode *N = Op.Val;
01072   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
01073       N->getOpcode() < SPISD::FIRST_NUMBER) {
01074     Result = Op;
01075     return;   // Already selected.
01076   }
01077 
01078                  // If this has already been converted, use it.
01079   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
01080   if (CGMI != CodeGenMap.end()) {
01081     Result = CGMI->second;
01082     return;
01083   }
01084   
01085   switch (N->getOpcode()) {
01086   default: break;
01087   case ISD::SDIV:
01088   case ISD::UDIV: {
01089     // FIXME: should use a custom expander to expose the SRA to the dag.
01090     SDOperand DivLHS, DivRHS;
01091     Select(DivLHS, N->getOperand(0));
01092     Select(DivRHS, N->getOperand(1));
01093     
01094     // Set the Y register to the high-part.
01095     SDOperand TopPart;
01096     if (N->getOpcode() == ISD::SDIV) {
01097       TopPart = SDOperand(CurDAG->getTargetNode(SP::SRAri, MVT::i32, DivLHS,
01098                                    CurDAG->getTargetConstant(31, MVT::i32)), 0);
01099     } else {
01100       TopPart = CurDAG->getRegister(SP::G0, MVT::i32);
01101     }
01102     TopPart = SDOperand(CurDAG->getTargetNode(SP::WRYrr, MVT::Flag, TopPart,
01103                                      CurDAG->getRegister(SP::G0, MVT::i32)), 0);
01104 
01105     // FIXME: Handle div by immediate.
01106     unsigned Opcode = N->getOpcode() == ISD::SDIV ? SP::SDIVrr : SP::UDIVrr;
01107     Result = CurDAG->SelectNodeTo(N, Opcode, MVT::i32, DivLHS, DivRHS, TopPart);
01108     return;
01109   }    
01110   case ISD::MULHU:
01111   case ISD::MULHS: {
01112     // FIXME: Handle mul by immediate.
01113     SDOperand MulLHS, MulRHS;
01114     Select(MulLHS, N->getOperand(0));
01115     Select(MulRHS, N->getOperand(1));
01116     unsigned Opcode = N->getOpcode() == ISD::MULHU ? SP::UMULrr : SP::SMULrr;
01117     SDNode *Mul = CurDAG->getTargetNode(Opcode, MVT::i32, MVT::Flag,
01118                                         MulLHS, MulRHS);
01119     // The high part is in the Y register.
01120     Result = CurDAG->SelectNodeTo(N, SP::RDY, MVT::i32, SDOperand(Mul, 1));
01121     return;
01122   }
01123   }
01124   
01125   SelectCode(Result, Op);
01126 }
01127 
01128 
01129 /// createSparcISelDag - This pass converts a legalized DAG into a 
01130 /// SPARC-specific DAG, ready for instruction scheduling.
01131 ///
01132 FunctionPass *llvm::createSparcISelDag(TargetMachine &TM) {
01133   return new SparcDAGToDAGISel(TM);
01134 }