Home | History | Annotate | Download | only in MBlaze
      1 //===-- MBlazeISelLowering.cpp - MBlaze DAG Lowering Implementation -------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file defines the interfaces that MBlaze uses to lower LLVM code into a
     11 // selection DAG.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "mblaze-lower"
     16 #include "MBlazeISelLowering.h"
     17 #include "MBlazeMachineFunction.h"
     18 #include "MBlazeTargetMachine.h"
     19 #include "MBlazeTargetObjectFile.h"
     20 #include "MBlazeSubtarget.h"
     21 #include "llvm/DerivedTypes.h"
     22 #include "llvm/Function.h"
     23 #include "llvm/GlobalVariable.h"
     24 #include "llvm/Intrinsics.h"
     25 #include "llvm/CallingConv.h"
     26 #include "llvm/CodeGen/CallingConvLower.h"
     27 #include "llvm/CodeGen/MachineFrameInfo.h"
     28 #include "llvm/CodeGen/MachineFunction.h"
     29 #include "llvm/CodeGen/MachineInstrBuilder.h"
     30 #include "llvm/CodeGen/MachineRegisterInfo.h"
     31 #include "llvm/CodeGen/SelectionDAGISel.h"
     32 #include "llvm/CodeGen/ValueTypes.h"
     33 #include "llvm/Support/Debug.h"
     34 #include "llvm/Support/ErrorHandling.h"
     35 #include "llvm/Support/raw_ostream.h"
     36 using namespace llvm;
     37 
     38 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
     39                                 CCValAssign::LocInfo &LocInfo,
     40                                 ISD::ArgFlagsTy &ArgFlags,
     41                                 CCState &State);
     42 
     43 const char *MBlazeTargetLowering::getTargetNodeName(unsigned Opcode) const {
     44   switch (Opcode) {
     45     case MBlazeISD::JmpLink    : return "MBlazeISD::JmpLink";
     46     case MBlazeISD::GPRel      : return "MBlazeISD::GPRel";
     47     case MBlazeISD::Wrap       : return "MBlazeISD::Wrap";
     48     case MBlazeISD::ICmp       : return "MBlazeISD::ICmp";
     49     case MBlazeISD::Ret        : return "MBlazeISD::Ret";
     50     case MBlazeISD::Select_CC  : return "MBlazeISD::Select_CC";
     51     default                    : return NULL;
     52   }
     53 }
     54 
     55 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
     56   : TargetLowering(TM, new MBlazeTargetObjectFile()) {
     57   Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
     58 
     59   // MBlaze does not have i1 type, so use i32 for
     60   // setcc operations results (slt, sgt, ...).
     61   setBooleanContents(ZeroOrOneBooleanContent);
     62   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
     63 
     64   // Set up the register classes
     65   addRegisterClass(MVT::i32, MBlaze::GPRRegisterClass);
     66   if (Subtarget->hasFPU()) {
     67     addRegisterClass(MVT::f32, MBlaze::GPRRegisterClass);
     68     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
     69   }
     70 
     71   // Floating point operations which are not supported
     72   setOperationAction(ISD::FREM,       MVT::f32, Expand);
     73   setOperationAction(ISD::FMA,        MVT::f32, Expand);
     74   setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Expand);
     75   setOperationAction(ISD::UINT_TO_FP, MVT::i16, Expand);
     76   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
     77   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
     78   setOperationAction(ISD::FP_ROUND,   MVT::f32, Expand);
     79   setOperationAction(ISD::FP_ROUND,   MVT::f64, Expand);
     80   setOperationAction(ISD::FCOPYSIGN,  MVT::f32, Expand);
     81   setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
     82   setOperationAction(ISD::FSIN,       MVT::f32, Expand);
     83   setOperationAction(ISD::FCOS,       MVT::f32, Expand);
     84   setOperationAction(ISD::FPOWI,      MVT::f32, Expand);
     85   setOperationAction(ISD::FPOW,       MVT::f32, Expand);
     86   setOperationAction(ISD::FLOG,       MVT::f32, Expand);
     87   setOperationAction(ISD::FLOG2,      MVT::f32, Expand);
     88   setOperationAction(ISD::FLOG10,     MVT::f32, Expand);
     89   setOperationAction(ISD::FEXP,       MVT::f32, Expand);
     90 
     91   // Load extented operations for i1 types must be promoted
     92   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
     93   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
     94   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
     95 
     96   // Sign extended loads must be expanded
     97   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
     98   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
     99 
    100   // MBlaze has no REM or DIVREM operations.
    101   setOperationAction(ISD::UREM,    MVT::i32, Expand);
    102   setOperationAction(ISD::SREM,    MVT::i32, Expand);
    103   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
    104   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
    105 
    106   // If the processor doesn't support multiply then expand it
    107   if (!Subtarget->hasMul()) {
    108     setOperationAction(ISD::MUL, MVT::i32, Expand);
    109   }
    110 
    111   // If the processor doesn't support 64-bit multiply then expand
    112   if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
    113     setOperationAction(ISD::MULHS, MVT::i32, Expand);
    114     setOperationAction(ISD::MULHS, MVT::i64, Expand);
    115     setOperationAction(ISD::MULHU, MVT::i32, Expand);
    116     setOperationAction(ISD::MULHU, MVT::i64, Expand);
    117   }
    118 
    119   // If the processor doesn't support division then expand
    120   if (!Subtarget->hasDiv()) {
    121     setOperationAction(ISD::UDIV, MVT::i32, Expand);
    122     setOperationAction(ISD::SDIV, MVT::i32, Expand);
    123   }
    124 
    125   // Expand unsupported conversions
    126   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
    127   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
    128 
    129   // Expand SELECT_CC
    130   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
    131 
    132   // MBlaze doesn't have MUL_LOHI
    133   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
    134   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
    135   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
    136   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
    137 
    138   // Used by legalize types to correctly generate the setcc result.
    139   // Without this, every float setcc comes with a AND/OR with the result,
    140   // we don't want this, since the fpcmp result goes to a flag register,
    141   // which is used implicitly by brcond and select operations.
    142   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
    143   AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
    144   AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
    145 
    146   // MBlaze Custom Operations
    147   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
    148   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
    149   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
    150   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
    151 
    152   // Variable Argument support
    153   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
    154   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
    155   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
    156   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
    157 
    158 
    159   // Operations not directly supported by MBlaze.
    160   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
    161   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
    162   setOperationAction(ISD::BR_CC,              MVT::Other, Expand);
    163   setOperationAction(ISD::SIGN_EXTEND_INREG,  MVT::i1,    Expand);
    164   setOperationAction(ISD::ROTL,               MVT::i32,   Expand);
    165   setOperationAction(ISD::ROTR,               MVT::i32,   Expand);
    166   setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Expand);
    167   setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Expand);
    168   setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Expand);
    169   setOperationAction(ISD::CTLZ,               MVT::i32,   Expand);
    170   setOperationAction(ISD::CTTZ,               MVT::i32,   Expand);
    171   setOperationAction(ISD::CTPOP,              MVT::i32,   Expand);
    172   setOperationAction(ISD::BSWAP,              MVT::i32,   Expand);
    173 
    174   // We don't have line number support yet.
    175   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
    176 
    177   // Use the default for now
    178   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
    179   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
    180 
    181   // MBlaze doesn't have extending float->double load/store
    182   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
    183   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
    184 
    185   setMinFunctionAlignment(2);
    186 
    187   setStackPointerRegisterToSaveRestore(MBlaze::R1);
    188   computeRegisterProperties();
    189 }
    190 
    191 EVT MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
    192   return MVT::i32;
    193 }
    194 
    195 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op,
    196                                              SelectionDAG &DAG) const {
    197   switch (Op.getOpcode())
    198   {
    199     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
    200     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
    201     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
    202     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
    203     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
    204     case ISD::VASTART:            return LowerVASTART(Op, DAG);
    205   }
    206   return SDValue();
    207 }
    208 
    209 //===----------------------------------------------------------------------===//
    210 //  Lower helper functions
    211 //===----------------------------------------------------------------------===//
    212 MachineBasicBlock*
    213 MBlazeTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
    214                                                   MachineBasicBlock *MBB)
    215                                                   const {
    216   switch (MI->getOpcode()) {
    217   default: assert(false && "Unexpected instr type to insert");
    218 
    219   case MBlaze::ShiftRL:
    220   case MBlaze::ShiftRA:
    221   case MBlaze::ShiftL:
    222     return EmitCustomShift(MI, MBB);
    223 
    224   case MBlaze::Select_FCC:
    225   case MBlaze::Select_CC:
    226     return EmitCustomSelect(MI, MBB);
    227 
    228   case MBlaze::CAS32:
    229   case MBlaze::SWP32:
    230   case MBlaze::LAA32:
    231   case MBlaze::LAS32:
    232   case MBlaze::LAD32:
    233   case MBlaze::LAO32:
    234   case MBlaze::LAX32:
    235   case MBlaze::LAN32:
    236     return EmitCustomAtomic(MI, MBB);
    237 
    238   case MBlaze::MEMBARRIER:
    239     // The Microblaze does not need memory barriers. Just delete the pseudo
    240     // instruction and finish.
    241     MI->eraseFromParent();
    242     return MBB;
    243   }
    244 }
    245 
    246 MachineBasicBlock*
    247 MBlazeTargetLowering::EmitCustomShift(MachineInstr *MI,
    248                                       MachineBasicBlock *MBB) const {
    249   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
    250   DebugLoc dl = MI->getDebugLoc();
    251 
    252   // To "insert" a shift left instruction, we actually have to insert a
    253   // simple loop.  The incoming instruction knows the destination vreg to
    254   // set, the source vreg to operate over and the shift amount.
    255   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
    256   MachineFunction::iterator It = MBB;
    257   ++It;
    258 
    259   // start:
    260   //   andi     samt, samt, 31
    261   //   beqid    samt, finish
    262   //   add      dst, src, r0
    263   // loop:
    264   //   addik    samt, samt, -1
    265   //   sra      dst, dst
    266   //   bneid    samt, loop
    267   //   nop
    268   // finish:
    269   MachineFunction *F = MBB->getParent();
    270   MachineRegisterInfo &R = F->getRegInfo();
    271   MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
    272   MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
    273   F->insert(It, loop);
    274   F->insert(It, finish);
    275 
    276   // Update machine-CFG edges by transferring adding all successors and
    277   // remaining instructions from the current block to the new block which
    278   // will contain the Phi node for the select.
    279   finish->splice(finish->begin(), MBB,
    280                  llvm::next(MachineBasicBlock::iterator(MI)),
    281                  MBB->end());
    282   finish->transferSuccessorsAndUpdatePHIs(MBB);
    283 
    284   // Add the true and fallthrough blocks as its successors.
    285   MBB->addSuccessor(loop);
    286   MBB->addSuccessor(finish);
    287 
    288   // Next, add the finish block as a successor of the loop block
    289   loop->addSuccessor(finish);
    290   loop->addSuccessor(loop);
    291 
    292   unsigned IAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    293   BuildMI(MBB, dl, TII->get(MBlaze::ANDI), IAMT)
    294     .addReg(MI->getOperand(2).getReg())
    295     .addImm(31);
    296 
    297   unsigned IVAL = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    298   BuildMI(MBB, dl, TII->get(MBlaze::ADDIK), IVAL)
    299     .addReg(MI->getOperand(1).getReg())
    300     .addImm(0);
    301 
    302   BuildMI(MBB, dl, TII->get(MBlaze::BEQID))
    303     .addReg(IAMT)
    304     .addMBB(finish);
    305 
    306   unsigned DST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    307   unsigned NDST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    308   BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
    309     .addReg(IVAL).addMBB(MBB)
    310     .addReg(NDST).addMBB(loop);
    311 
    312   unsigned SAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    313   unsigned NAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    314   BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
    315     .addReg(IAMT).addMBB(MBB)
    316     .addReg(NAMT).addMBB(loop);
    317 
    318   if (MI->getOpcode() == MBlaze::ShiftL)
    319     BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
    320   else if (MI->getOpcode() == MBlaze::ShiftRA)
    321     BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
    322   else if (MI->getOpcode() == MBlaze::ShiftRL)
    323     BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
    324   else
    325     llvm_unreachable("Cannot lower unknown shift instruction");
    326 
    327   BuildMI(loop, dl, TII->get(MBlaze::ADDIK), NAMT)
    328     .addReg(SAMT)
    329     .addImm(-1);
    330 
    331   BuildMI(loop, dl, TII->get(MBlaze::BNEID))
    332     .addReg(NAMT)
    333     .addMBB(loop);
    334 
    335   BuildMI(*finish, finish->begin(), dl,
    336           TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
    337     .addReg(IVAL).addMBB(MBB)
    338     .addReg(NDST).addMBB(loop);
    339 
    340   // The pseudo instruction is no longer needed so remove it
    341   MI->eraseFromParent();
    342   return finish;
    343 }
    344 
    345 MachineBasicBlock*
    346 MBlazeTargetLowering::EmitCustomSelect(MachineInstr *MI,
    347                                        MachineBasicBlock *MBB) const {
    348   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
    349   DebugLoc dl = MI->getDebugLoc();
    350 
    351   // To "insert" a SELECT_CC instruction, we actually have to insert the
    352   // diamond control-flow pattern.  The incoming instruction knows the
    353   // destination vreg to set, the condition code register to branch on, the
    354   // true/false values to select between, and a branch opcode to use.
    355   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
    356   MachineFunction::iterator It = MBB;
    357   ++It;
    358 
    359   //  thisMBB:
    360   //  ...
    361   //   TrueVal = ...
    362   //   setcc r1, r2, r3
    363   //   bNE   r1, r0, copy1MBB
    364   //   fallthrough --> copy0MBB
    365   MachineFunction *F = MBB->getParent();
    366   MachineBasicBlock *flsBB = F->CreateMachineBasicBlock(LLVM_BB);
    367   MachineBasicBlock *dneBB = F->CreateMachineBasicBlock(LLVM_BB);
    368 
    369   unsigned Opc;
    370   switch (MI->getOperand(4).getImm()) {
    371   default: llvm_unreachable("Unknown branch condition");
    372   case MBlazeCC::EQ: Opc = MBlaze::BEQID; break;
    373   case MBlazeCC::NE: Opc = MBlaze::BNEID; break;
    374   case MBlazeCC::GT: Opc = MBlaze::BGTID; break;
    375   case MBlazeCC::LT: Opc = MBlaze::BLTID; break;
    376   case MBlazeCC::GE: Opc = MBlaze::BGEID; break;
    377   case MBlazeCC::LE: Opc = MBlaze::BLEID; break;
    378   }
    379 
    380   F->insert(It, flsBB);
    381   F->insert(It, dneBB);
    382 
    383   // Transfer the remainder of MBB and its successor edges to dneBB.
    384   dneBB->splice(dneBB->begin(), MBB,
    385                 llvm::next(MachineBasicBlock::iterator(MI)),
    386                 MBB->end());
    387   dneBB->transferSuccessorsAndUpdatePHIs(MBB);
    388 
    389   MBB->addSuccessor(flsBB);
    390   MBB->addSuccessor(dneBB);
    391   flsBB->addSuccessor(dneBB);
    392 
    393   BuildMI(MBB, dl, TII->get(Opc))
    394     .addReg(MI->getOperand(3).getReg())
    395     .addMBB(dneBB);
    396 
    397   //  sinkMBB:
    398   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
    399   //  ...
    400   //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
    401   //  .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
    402   //  .addReg(MI->getOperand(2).getReg()).addMBB(BB);
    403 
    404   BuildMI(*dneBB, dneBB->begin(), dl,
    405           TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
    406     .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
    407     .addReg(MI->getOperand(1).getReg()).addMBB(MBB);
    408 
    409   MI->eraseFromParent();   // The pseudo instruction is gone now.
    410   return dneBB;
    411 }
    412 
    413 MachineBasicBlock*
    414 MBlazeTargetLowering::EmitCustomAtomic(MachineInstr *MI,
    415                                        MachineBasicBlock *MBB) const {
    416   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
    417   DebugLoc dl = MI->getDebugLoc();
    418 
    419   // All atomic instructions on the Microblaze are implemented using the
    420   // load-linked / store-conditional style atomic instruction sequences.
    421   // Thus, all operations will look something like the following:
    422   //
    423   //  start:
    424   //    lwx     RV, RP, 0
    425   //    <do stuff>
    426   //    swx     RV, RP, 0
    427   //    addic   RC, R0, 0
    428   //    bneid   RC, start
    429   //
    430   //  exit:
    431   //
    432   // To "insert" a shift left instruction, we actually have to insert a
    433   // simple loop.  The incoming instruction knows the destination vreg to
    434   // set, the source vreg to operate over and the shift amount.
    435   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
    436   MachineFunction::iterator It = MBB;
    437   ++It;
    438 
    439   // start:
    440   //   andi     samt, samt, 31
    441   //   beqid    samt, finish
    442   //   add      dst, src, r0
    443   // loop:
    444   //   addik    samt, samt, -1
    445   //   sra      dst, dst
    446   //   bneid    samt, loop
    447   //   nop
    448   // finish:
    449   MachineFunction *F = MBB->getParent();
    450   MachineRegisterInfo &R = F->getRegInfo();
    451 
    452   // Create the start and exit basic blocks for the atomic operation
    453   MachineBasicBlock *start = F->CreateMachineBasicBlock(LLVM_BB);
    454   MachineBasicBlock *exit = F->CreateMachineBasicBlock(LLVM_BB);
    455   F->insert(It, start);
    456   F->insert(It, exit);
    457 
    458   // Update machine-CFG edges by transferring adding all successors and
    459   // remaining instructions from the current block to the new block which
    460   // will contain the Phi node for the select.
    461   exit->splice(exit->begin(), MBB, llvm::next(MachineBasicBlock::iterator(MI)),
    462                MBB->end());
    463   exit->transferSuccessorsAndUpdatePHIs(MBB);
    464 
    465   // Add the fallthrough block as its successors.
    466   MBB->addSuccessor(start);
    467 
    468   BuildMI(start, dl, TII->get(MBlaze::LWX), MI->getOperand(0).getReg())
    469     .addReg(MI->getOperand(1).getReg())
    470     .addReg(MBlaze::R0);
    471 
    472   MachineBasicBlock *final = start;
    473   unsigned finalReg = 0;
    474 
    475   switch (MI->getOpcode()) {
    476   default: llvm_unreachable("Cannot lower unknown atomic instruction!");
    477 
    478   case MBlaze::SWP32:
    479     finalReg = MI->getOperand(2).getReg();
    480     start->addSuccessor(exit);
    481     start->addSuccessor(start);
    482     break;
    483 
    484   case MBlaze::LAN32:
    485   case MBlaze::LAX32:
    486   case MBlaze::LAO32:
    487   case MBlaze::LAD32:
    488   case MBlaze::LAS32:
    489   case MBlaze::LAA32: {
    490     unsigned opcode = 0;
    491     switch (MI->getOpcode()) {
    492     default: llvm_unreachable("Cannot lower unknown atomic load!");
    493     case MBlaze::LAA32: opcode = MBlaze::ADDIK; break;
    494     case MBlaze::LAS32: opcode = MBlaze::RSUBIK; break;
    495     case MBlaze::LAD32: opcode = MBlaze::AND; break;
    496     case MBlaze::LAO32: opcode = MBlaze::OR; break;
    497     case MBlaze::LAX32: opcode = MBlaze::XOR; break;
    498     case MBlaze::LAN32: opcode = MBlaze::AND; break;
    499     }
    500 
    501     finalReg = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    502     start->addSuccessor(exit);
    503     start->addSuccessor(start);
    504 
    505     BuildMI(start, dl, TII->get(opcode), finalReg)
    506       .addReg(MI->getOperand(0).getReg())
    507       .addReg(MI->getOperand(2).getReg());
    508 
    509     if (MI->getOpcode() == MBlaze::LAN32) {
    510       unsigned tmp = finalReg;
    511       finalReg = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    512       BuildMI(start, dl, TII->get(MBlaze::XORI), finalReg)
    513         .addReg(tmp)
    514         .addImm(-1);
    515     }
    516     break;
    517   }
    518 
    519   case MBlaze::CAS32: {
    520     finalReg = MI->getOperand(3).getReg();
    521     final = F->CreateMachineBasicBlock(LLVM_BB);
    522 
    523     F->insert(It, final);
    524     start->addSuccessor(exit);
    525     start->addSuccessor(final);
    526     final->addSuccessor(exit);
    527     final->addSuccessor(start);
    528 
    529     unsigned CMP = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    530     BuildMI(start, dl, TII->get(MBlaze::CMP), CMP)
    531       .addReg(MI->getOperand(0).getReg())
    532       .addReg(MI->getOperand(2).getReg());
    533 
    534     BuildMI(start, dl, TII->get(MBlaze::BNEID))
    535       .addReg(CMP)
    536       .addMBB(exit);
    537 
    538     final->moveAfter(start);
    539     exit->moveAfter(final);
    540     break;
    541   }
    542   }
    543 
    544   unsigned CHK = R.createVirtualRegister(MBlaze::GPRRegisterClass);
    545   BuildMI(final, dl, TII->get(MBlaze::SWX))
    546     .addReg(finalReg)
    547     .addReg(MI->getOperand(1).getReg())
    548     .addReg(MBlaze::R0);
    549 
    550   BuildMI(final, dl, TII->get(MBlaze::ADDIC), CHK)
    551     .addReg(MBlaze::R0)
    552     .addImm(0);
    553 
    554   BuildMI(final, dl, TII->get(MBlaze::BNEID))
    555     .addReg(CHK)
    556     .addMBB(start);
    557 
    558   // The pseudo instruction is no longer needed so remove it
    559   MI->eraseFromParent();
    560   return exit;
    561 }
    562 
    563 //===----------------------------------------------------------------------===//
    564 //  Misc Lower Operation implementation
    565 //===----------------------------------------------------------------------===//
    566 //
    567 
    568 SDValue MBlazeTargetLowering::LowerSELECT_CC(SDValue Op,
    569                                              SelectionDAG &DAG) const {
    570   SDValue LHS = Op.getOperand(0);
    571   SDValue RHS = Op.getOperand(1);
    572   SDValue TrueVal = Op.getOperand(2);
    573   SDValue FalseVal = Op.getOperand(3);
    574   DebugLoc dl = Op.getDebugLoc();
    575   unsigned Opc;
    576 
    577   SDValue CompareFlag;
    578   if (LHS.getValueType() == MVT::i32) {
    579     Opc = MBlazeISD::Select_CC;
    580     CompareFlag = DAG.getNode(MBlazeISD::ICmp, dl, MVT::i32, LHS, RHS)
    581                     .getValue(1);
    582   } else {
    583     llvm_unreachable("Cannot lower select_cc with unknown type");
    584   }
    585 
    586   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
    587                      CompareFlag);
    588 }
    589 
    590 SDValue MBlazeTargetLowering::
    591 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
    592   // FIXME there isn't actually debug info here
    593   DebugLoc dl = Op.getDebugLoc();
    594   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    595   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
    596 
    597   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
    598 }
    599 
    600 SDValue MBlazeTargetLowering::
    601 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
    602   llvm_unreachable("TLS not implemented for MicroBlaze.");
    603   return SDValue(); // Not reached
    604 }
    605 
    606 SDValue MBlazeTargetLowering::
    607 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
    608   SDValue ResNode;
    609   SDValue HiPart;
    610   // FIXME there isn't actually debug info here
    611   DebugLoc dl = Op.getDebugLoc();
    612 
    613   EVT PtrVT = Op.getValueType();
    614   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
    615 
    616   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 0);
    617   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
    618 }
    619 
    620 SDValue MBlazeTargetLowering::
    621 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
    622   SDValue ResNode;
    623   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
    624   const Constant *C = N->getConstVal();
    625   DebugLoc dl = Op.getDebugLoc();
    626 
    627   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
    628                                          N->getOffset(), 0);
    629   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
    630 }
    631 
    632 SDValue MBlazeTargetLowering::LowerVASTART(SDValue Op,
    633                                            SelectionDAG &DAG) const {
    634   MachineFunction &MF = DAG.getMachineFunction();
    635   MBlazeFunctionInfo *FuncInfo = MF.getInfo<MBlazeFunctionInfo>();
    636 
    637   DebugLoc dl = Op.getDebugLoc();
    638   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
    639                                  getPointerTy());
    640 
    641   // vastart just stores the address of the VarArgsFrameIndex slot into the
    642   // memory location argument.
    643   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    644   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
    645                       MachinePointerInfo(SV),
    646                       false, false, 0);
    647 }
    648 
    649 //===----------------------------------------------------------------------===//
    650 //                      Calling Convention Implementation
    651 //===----------------------------------------------------------------------===//
    652 
    653 #include "MBlazeGenCallingConv.inc"
    654 
    655 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
    656                                 CCValAssign::LocInfo &LocInfo,
    657                                 ISD::ArgFlagsTy &ArgFlags,
    658                                 CCState &State) {
    659   static const unsigned ArgRegs[] = {
    660     MBlaze::R5, MBlaze::R6, MBlaze::R7,
    661     MBlaze::R8, MBlaze::R9, MBlaze::R10
    662   };
    663 
    664   const unsigned NumArgRegs = array_lengthof(ArgRegs);
    665   unsigned Reg = State.AllocateReg(ArgRegs, NumArgRegs);
    666   if (!Reg) return false;
    667 
    668   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
    669   State.AllocateStack(SizeInBytes, SizeInBytes);
    670   State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
    671 
    672   return true;
    673 }
    674 
    675 //===----------------------------------------------------------------------===//
    676 //                  Call Calling Convention Implementation
    677 //===----------------------------------------------------------------------===//
    678 
    679 /// LowerCall - functions arguments are copied from virtual regs to
    680 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
    681 /// TODO: isVarArg, isTailCall.
    682 SDValue MBlazeTargetLowering::
    683 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
    684           bool isVarArg, bool &isTailCall,
    685           const SmallVectorImpl<ISD::OutputArg> &Outs,
    686           const SmallVectorImpl<SDValue> &OutVals,
    687           const SmallVectorImpl<ISD::InputArg> &Ins,
    688           DebugLoc dl, SelectionDAG &DAG,
    689           SmallVectorImpl<SDValue> &InVals) const {
    690   // MBlaze does not yet support tail call optimization
    691   isTailCall = false;
    692 
    693   // The MBlaze requires stack slots for arguments passed to var arg
    694   // functions even if they are passed in registers.
    695   bool needsRegArgSlots = isVarArg;
    696 
    697   MachineFunction &MF = DAG.getMachineFunction();
    698   MachineFrameInfo *MFI = MF.getFrameInfo();
    699   const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
    700 
    701   // Analyze operands of the call, assigning locations to each operand.
    702   SmallVector<CCValAssign, 16> ArgLocs;
    703   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    704 		 getTargetMachine(), ArgLocs, *DAG.getContext());
    705   CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
    706 
    707   // Get a count of how many bytes are to be pushed on the stack.
    708   unsigned NumBytes = CCInfo.getNextStackOffset();
    709 
    710   // Variable argument function calls require a minimum of 24-bytes of stack
    711   if (isVarArg && NumBytes < 24) NumBytes = 24;
    712 
    713   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
    714 
    715   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
    716   SmallVector<SDValue, 8> MemOpChains;
    717 
    718   // Walk the register/memloc assignments, inserting copies/loads.
    719   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    720     CCValAssign &VA = ArgLocs[i];
    721     MVT RegVT = VA.getLocVT();
    722     SDValue Arg = OutVals[i];
    723 
    724     // Promote the value if needed.
    725     switch (VA.getLocInfo()) {
    726     default: llvm_unreachable("Unknown loc info!");
    727     case CCValAssign::Full: break;
    728     case CCValAssign::SExt:
    729       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
    730       break;
    731     case CCValAssign::ZExt:
    732       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
    733       break;
    734     case CCValAssign::AExt:
    735       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
    736       break;
    737     }
    738 
    739     // Arguments that can be passed on register must be kept at
    740     // RegsToPass vector
    741     if (VA.isRegLoc()) {
    742       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
    743     } else {
    744       // Register can't get to this point...
    745       assert(VA.isMemLoc());
    746 
    747       // Since we are alread passing values on the stack we don't
    748       // need to worry about creating additional slots for the
    749       // values passed via registers.
    750       needsRegArgSlots = false;
    751 
    752       // Create the frame index object for this incoming parameter
    753       unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
    754       unsigned StackLoc = VA.getLocMemOffset() + 4;
    755       int FI = MFI->CreateFixedObject(ArgSize, StackLoc, true);
    756 
    757       SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
    758 
    759       // emit ISD::STORE whichs stores the
    760       // parameter value to a stack Location
    761       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
    762                                          MachinePointerInfo(),
    763                                          false, false, 0));
    764     }
    765   }
    766 
    767   // If we need to reserve stack space for the arguments passed via registers
    768   // then create a fixed stack object at the beginning of the stack.
    769   if (needsRegArgSlots && TFI.hasReservedCallFrame(MF))
    770     MFI->CreateFixedObject(28,0,true);
    771 
    772   // Transform all store nodes into one single node because all store
    773   // nodes are independent of each other.
    774   if (!MemOpChains.empty())
    775     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    776                         &MemOpChains[0], MemOpChains.size());
    777 
    778   // Build a sequence of copy-to-reg nodes chained together with token
    779   // chain and flag operands which copy the outgoing args into registers.
    780   // The InFlag in necessary since all emitted instructions must be
    781   // stuck together.
    782   SDValue InFlag;
    783   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
    784     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
    785                              RegsToPass[i].second, InFlag);
    786     InFlag = Chain.getValue(1);
    787   }
    788 
    789   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
    790   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
    791   // node so that legalize doesn't hack it.
    792   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
    793     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
    794                                 getPointerTy(), 0, 0);
    795   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
    796     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
    797                                 getPointerTy(), 0);
    798 
    799   // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
    800   //             = Chain, Callee, Reg#1, Reg#2, ...
    801   //
    802   // Returns a chain & a flag for retval copy to use.
    803   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    804   SmallVector<SDValue, 8> Ops;
    805   Ops.push_back(Chain);
    806   Ops.push_back(Callee);
    807 
    808   // Add argument registers to the end of the list so that they are
    809   // known live into the call.
    810   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
    811     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
    812                                   RegsToPass[i].second.getValueType()));
    813   }
    814 
    815   if (InFlag.getNode())
    816     Ops.push_back(InFlag);
    817 
    818   Chain  = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
    819   InFlag = Chain.getValue(1);
    820 
    821   // Create the CALLSEQ_END node.
    822   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
    823                              DAG.getIntPtrConstant(0, true), InFlag);
    824   if (!Ins.empty())
    825     InFlag = Chain.getValue(1);
    826 
    827   // Handle result values, copying them out of physregs into vregs that we
    828   // return.
    829   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
    830                          Ins, dl, DAG, InVals);
    831 }
    832 
    833 /// LowerCallResult - Lower the result values of a call into the
    834 /// appropriate copies out of appropriate physical registers.
    835 SDValue MBlazeTargetLowering::
    836 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
    837                 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
    838                 DebugLoc dl, SelectionDAG &DAG,
    839                 SmallVectorImpl<SDValue> &InVals) const {
    840   // Assign locations to each value returned by this call.
    841   SmallVector<CCValAssign, 16> RVLocs;
    842   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    843 		 getTargetMachine(), RVLocs, *DAG.getContext());
    844 
    845   CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
    846 
    847   // Copy all of the result registers out of their specified physreg.
    848   for (unsigned i = 0; i != RVLocs.size(); ++i) {
    849     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
    850                                RVLocs[i].getValVT(), InFlag).getValue(1);
    851     InFlag = Chain.getValue(2);
    852     InVals.push_back(Chain.getValue(0));
    853   }
    854 
    855   return Chain;
    856 }
    857 
    858 //===----------------------------------------------------------------------===//
    859 //             Formal Arguments Calling Convention Implementation
    860 //===----------------------------------------------------------------------===//
    861 
    862 /// LowerFormalArguments - transform physical registers into
    863 /// virtual registers and generate load operations for
    864 /// arguments places on the stack.
    865 SDValue MBlazeTargetLowering::
    866 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
    867                      const SmallVectorImpl<ISD::InputArg> &Ins,
    868                      DebugLoc dl, SelectionDAG &DAG,
    869                      SmallVectorImpl<SDValue> &InVals) const {
    870   MachineFunction &MF = DAG.getMachineFunction();
    871   MachineFrameInfo *MFI = MF.getFrameInfo();
    872   MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
    873 
    874   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
    875   MBlazeFI->setVarArgsFrameIndex(0);
    876 
    877   // Used with vargs to acumulate store chains.
    878   std::vector<SDValue> OutChains;
    879 
    880   // Keep track of the last register used for arguments
    881   unsigned ArgRegEnd = 0;
    882 
    883   // Assign locations to all of the incoming arguments.
    884   SmallVector<CCValAssign, 16> ArgLocs;
    885   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
    886 		 getTargetMachine(), ArgLocs, *DAG.getContext());
    887 
    888   CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
    889   SDValue StackPtr;
    890 
    891   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    892     CCValAssign &VA = ArgLocs[i];
    893 
    894     // Arguments stored on registers
    895     if (VA.isRegLoc()) {
    896       MVT RegVT = VA.getLocVT();
    897       ArgRegEnd = VA.getLocReg();
    898       TargetRegisterClass *RC = 0;
    899 
    900       if (RegVT == MVT::i32)
    901         RC = MBlaze::GPRRegisterClass;
    902       else if (RegVT == MVT::f32)
    903         RC = MBlaze::GPRRegisterClass;
    904       else
    905         llvm_unreachable("RegVT not supported by LowerFormalArguments");
    906 
    907       // Transform the arguments stored on
    908       // physical registers into virtual ones
    909       unsigned Reg = MF.addLiveIn(ArgRegEnd, RC);
    910       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
    911 
    912       // If this is an 8 or 16-bit value, it has been passed promoted
    913       // to 32 bits.  Insert an assert[sz]ext to capture this, then
    914       // truncate to the right size. If if is a floating point value
    915       // then convert to the correct type.
    916       if (VA.getLocInfo() != CCValAssign::Full) {
    917         unsigned Opcode = 0;
    918         if (VA.getLocInfo() == CCValAssign::SExt)
    919           Opcode = ISD::AssertSext;
    920         else if (VA.getLocInfo() == CCValAssign::ZExt)
    921           Opcode = ISD::AssertZext;
    922         if (Opcode)
    923           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
    924                                  DAG.getValueType(VA.getValVT()));
    925         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
    926       }
    927 
    928       InVals.push_back(ArgValue);
    929     } else { // VA.isRegLoc()
    930       // sanity check
    931       assert(VA.isMemLoc());
    932 
    933       // The last argument is not a register
    934       ArgRegEnd = 0;
    935 
    936       // The stack pointer offset is relative to the caller stack frame.
    937       // Since the real stack size is unknown here, a negative SPOffset
    938       // is used so there's a way to adjust these offsets when the stack
    939       // size get known (on EliminateFrameIndex). A dummy SPOffset is
    940       // used instead of a direct negative address (which is recorded to
    941       // be used on emitPrologue) to avoid mis-calc of the first stack
    942       // offset on PEI::calculateFrameObjectOffsets.
    943       // Arguments are always 32-bit.
    944       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
    945       unsigned StackLoc = VA.getLocMemOffset() + 4;
    946       int FI = MFI->CreateFixedObject(ArgSize, 0, true);
    947       MBlazeFI->recordLoadArgsFI(FI, -StackLoc);
    948       MBlazeFI->recordLiveIn(FI);
    949 
    950       // Create load nodes to retrieve arguments from the stack
    951       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
    952       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
    953                                    MachinePointerInfo::getFixedStack(FI),
    954                                    false, false, 0));
    955     }
    956   }
    957 
    958   // To meet ABI, when VARARGS are passed on registers, the registers
    959   // must have their values written to the caller stack frame. If the last
    960   // argument was placed in the stack, there's no need to save any register.
    961   if ((isVarArg) && ArgRegEnd) {
    962     if (StackPtr.getNode() == 0)
    963       StackPtr = DAG.getRegister(StackReg, getPointerTy());
    964 
    965     // The last register argument that must be saved is MBlaze::R10
    966     TargetRegisterClass *RC = MBlaze::GPRRegisterClass;
    967 
    968     unsigned Begin = getMBlazeRegisterNumbering(MBlaze::R5);
    969     unsigned Start = getMBlazeRegisterNumbering(ArgRegEnd+1);
    970     unsigned End   = getMBlazeRegisterNumbering(MBlaze::R10);
    971     unsigned StackLoc = Start - Begin + 1;
    972 
    973     for (; Start <= End; ++Start, ++StackLoc) {
    974       unsigned Reg = getMBlazeRegisterFromNumbering(Start);
    975       unsigned LiveReg = MF.addLiveIn(Reg, RC);
    976       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, LiveReg, MVT::i32);
    977 
    978       int FI = MFI->CreateFixedObject(4, 0, true);
    979       MBlazeFI->recordStoreVarArgsFI(FI, -(StackLoc*4));
    980       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
    981       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
    982                                        MachinePointerInfo(),
    983                                        false, false, 0));
    984 
    985       // Record the frame index of the first variable argument
    986       // which is a value necessary to VASTART.
    987       if (!MBlazeFI->getVarArgsFrameIndex())
    988         MBlazeFI->setVarArgsFrameIndex(FI);
    989     }
    990   }
    991 
    992   // All stores are grouped in one node to allow the matching between
    993   // the size of Ins and InVals. This only happens when on varg functions
    994   if (!OutChains.empty()) {
    995     OutChains.push_back(Chain);
    996     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
    997                         &OutChains[0], OutChains.size());
    998   }
    999 
   1000   return Chain;
   1001 }
   1002 
   1003 //===----------------------------------------------------------------------===//
   1004 //               Return Value Calling Convention Implementation
   1005 //===----------------------------------------------------------------------===//
   1006 
   1007 SDValue MBlazeTargetLowering::
   1008 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
   1009             const SmallVectorImpl<ISD::OutputArg> &Outs,
   1010             const SmallVectorImpl<SDValue> &OutVals,
   1011             DebugLoc dl, SelectionDAG &DAG) const {
   1012   // CCValAssign - represent the assignment of
   1013   // the return value to a location
   1014   SmallVector<CCValAssign, 16> RVLocs;
   1015 
   1016   // CCState - Info about the registers and stack slot.
   1017   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   1018 		 getTargetMachine(), RVLocs, *DAG.getContext());
   1019 
   1020   // Analize return values.
   1021   CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
   1022 
   1023   // If this is the first return lowered for this function, add
   1024   // the regs to the liveout set for the function.
   1025   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
   1026     for (unsigned i = 0; i != RVLocs.size(); ++i)
   1027       if (RVLocs[i].isRegLoc())
   1028         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
   1029   }
   1030 
   1031   SDValue Flag;
   1032 
   1033   // Copy the result values into the output registers.
   1034   for (unsigned i = 0; i != RVLocs.size(); ++i) {
   1035     CCValAssign &VA = RVLocs[i];
   1036     assert(VA.isRegLoc() && "Can only return in registers!");
   1037 
   1038     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
   1039                              OutVals[i], Flag);
   1040 
   1041     // guarantee that all emitted copies are
   1042     // stuck together, avoiding something bad
   1043     Flag = Chain.getValue(1);
   1044   }
   1045 
   1046   // If this function is using the interrupt_handler calling convention
   1047   // then use "rtid r14, 0" otherwise use "rtsd r15, 8"
   1048   unsigned Ret = (CallConv == llvm::CallingConv::MBLAZE_INTR) ? MBlazeISD::IRet
   1049                                                               : MBlazeISD::Ret;
   1050   unsigned Reg = (CallConv == llvm::CallingConv::MBLAZE_INTR) ? MBlaze::R14
   1051                                                               : MBlaze::R15;
   1052   SDValue DReg = DAG.getRegister(Reg, MVT::i32);
   1053 
   1054   if (Flag.getNode())
   1055     return DAG.getNode(Ret, dl, MVT::Other, Chain, DReg, Flag);
   1056 
   1057   return DAG.getNode(Ret, dl, MVT::Other, Chain, DReg);
   1058 }
   1059 
   1060 //===----------------------------------------------------------------------===//
   1061 //                           MBlaze Inline Assembly Support
   1062 //===----------------------------------------------------------------------===//
   1063 
   1064 /// getConstraintType - Given a constraint letter, return the type of
   1065 /// constraint it is for this target.
   1066 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
   1067 getConstraintType(const std::string &Constraint) const
   1068 {
   1069   // MBlaze specific constrainy
   1070   //
   1071   // 'd' : An address register. Equivalent to r.
   1072   // 'y' : Equivalent to r; retained for
   1073   //       backwards compatibility.
   1074   // 'f' : Floating Point registers.
   1075   if (Constraint.size() == 1) {
   1076     switch (Constraint[0]) {
   1077       default : break;
   1078       case 'd':
   1079       case 'y':
   1080       case 'f':
   1081         return C_RegisterClass;
   1082         break;
   1083     }
   1084   }
   1085   return TargetLowering::getConstraintType(Constraint);
   1086 }
   1087 
   1088 /// Examine constraint type and operand type and determine a weight value.
   1089 /// This object must already have been set up with the operand type
   1090 /// and the current alternative constraint selected.
   1091 TargetLowering::ConstraintWeight
   1092 MBlazeTargetLowering::getSingleConstraintMatchWeight(
   1093     AsmOperandInfo &info, const char *constraint) const {
   1094   ConstraintWeight weight = CW_Invalid;
   1095   Value *CallOperandVal = info.CallOperandVal;
   1096     // If we don't have a value, we can't do a match,
   1097     // but allow it at the lowest weight.
   1098   if (CallOperandVal == NULL)
   1099     return CW_Default;
   1100   Type *type = CallOperandVal->getType();
   1101   // Look at the constraint type.
   1102   switch (*constraint) {
   1103   default:
   1104     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
   1105     break;
   1106   case 'd':
   1107   case 'y':
   1108     if (type->isIntegerTy())
   1109       weight = CW_Register;
   1110     break;
   1111   case 'f':
   1112     if (type->isFloatTy())
   1113       weight = CW_Register;
   1114     break;
   1115   }
   1116   return weight;
   1117 }
   1118 
   1119 /// Given a register class constraint, like 'r', if this corresponds directly
   1120 /// to an LLVM register class, return a register of 0 and the register class
   1121 /// pointer.
   1122 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
   1123 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
   1124   if (Constraint.size() == 1) {
   1125     switch (Constraint[0]) {
   1126     case 'r':
   1127       return std::make_pair(0U, MBlaze::GPRRegisterClass);
   1128       // TODO: These can't possibly be right, but match what was in
   1129       // getRegClassForInlineAsmConstraint.
   1130     case 'd':
   1131     case 'y':
   1132     case 'f':
   1133       if (VT == MVT::f32)
   1134         return std::make_pair(0U, MBlaze::GPRRegisterClass);
   1135     }
   1136   }
   1137   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
   1138 }
   1139 
   1140 bool MBlazeTargetLowering::
   1141 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
   1142   // The MBlaze target isn't yet aware of offsets.
   1143   return false;
   1144 }
   1145 
   1146 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
   1147   return VT != MVT::f32;
   1148 }
   1149