LLVM  mainline
MipsISelLowering.cpp
Go to the documentation of this file.
00001 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the interfaces that Mips uses to lower LLVM code into a
00011 // selection DAG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 #include "MipsISelLowering.h"
00015 #include "InstPrinter/MipsInstPrinter.h"
00016 #include "MCTargetDesc/MipsBaseInfo.h"
00017 #include "MipsCCState.h"
00018 #include "MipsMachineFunction.h"
00019 #include "MipsSubtarget.h"
00020 #include "MipsTargetMachine.h"
00021 #include "MipsTargetObjectFile.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/ADT/StringSwitch.h"
00024 #include "llvm/CodeGen/CallingConvLower.h"
00025 #include "llvm/CodeGen/MachineFrameInfo.h"
00026 #include "llvm/CodeGen/MachineFunction.h"
00027 #include "llvm/CodeGen/MachineInstrBuilder.h"
00028 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00029 #include "llvm/CodeGen/MachineRegisterInfo.h"
00030 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00031 #include "llvm/CodeGen/SelectionDAGISel.h"
00032 #include "llvm/CodeGen/ValueTypes.h"
00033 #include "llvm/IR/CallingConv.h"
00034 #include "llvm/IR/DerivedTypes.h"
00035 #include "llvm/IR/GlobalVariable.h"
00036 #include "llvm/Support/CommandLine.h"
00037 #include "llvm/Support/Debug.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 #include <cctype>
00041 
00042 using namespace llvm;
00043 
00044 #define DEBUG_TYPE "mips-lower"
00045 
00046 STATISTIC(NumTailCalls, "Number of tail calls");
00047 
00048 static cl::opt<bool>
00049 LargeGOT("mxgot", cl::Hidden,
00050          cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
00051 
00052 static cl::opt<bool>
00053 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
00054                cl::desc("MIPS: Don't trap on integer division by zero."),
00055                cl::init(false));
00056 
00057 static const MCPhysReg Mips64DPRegs[8] = {
00058   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
00059   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
00060 };
00061 
00062 // If I is a shifted mask, set the size (Size) and the first bit of the
00063 // mask (Pos), and return true.
00064 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
00065 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
00066   if (!isShiftedMask_64(I))
00067     return false;
00068 
00069   Size = countPopulation(I);
00070   Pos = countTrailingZeros(I);
00071   return true;
00072 }
00073 
00074 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
00075   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
00076   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
00077 }
00078 
00079 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
00080                                           SelectionDAG &DAG,
00081                                           unsigned Flag) const {
00082   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
00083 }
00084 
00085 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
00086                                           SelectionDAG &DAG,
00087                                           unsigned Flag) const {
00088   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
00089 }
00090 
00091 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
00092                                           SelectionDAG &DAG,
00093                                           unsigned Flag) const {
00094   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
00095 }
00096 
00097 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
00098                                           SelectionDAG &DAG,
00099                                           unsigned Flag) const {
00100   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
00101 }
00102 
00103 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
00104                                           SelectionDAG &DAG,
00105                                           unsigned Flag) const {
00106   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
00107                                    N->getOffset(), Flag);
00108 }
00109 
00110 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
00111   switch ((MipsISD::NodeType)Opcode) {
00112   case MipsISD::FIRST_NUMBER:      break;
00113   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
00114   case MipsISD::TailCall:          return "MipsISD::TailCall";
00115   case MipsISD::Hi:                return "MipsISD::Hi";
00116   case MipsISD::Lo:                return "MipsISD::Lo";
00117   case MipsISD::GPRel:             return "MipsISD::GPRel";
00118   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
00119   case MipsISD::Ret:               return "MipsISD::Ret";
00120   case MipsISD::ERet:              return "MipsISD::ERet";
00121   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
00122   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
00123   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
00124   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
00125   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
00126   case MipsISD::TruncIntFP:        return "MipsISD::TruncIntFP";
00127   case MipsISD::MFHI:              return "MipsISD::MFHI";
00128   case MipsISD::MFLO:              return "MipsISD::MFLO";
00129   case MipsISD::MTLOHI:            return "MipsISD::MTLOHI";
00130   case MipsISD::Mult:              return "MipsISD::Mult";
00131   case MipsISD::Multu:             return "MipsISD::Multu";
00132   case MipsISD::MAdd:              return "MipsISD::MAdd";
00133   case MipsISD::MAddu:             return "MipsISD::MAddu";
00134   case MipsISD::MSub:              return "MipsISD::MSub";
00135   case MipsISD::MSubu:             return "MipsISD::MSubu";
00136   case MipsISD::DivRem:            return "MipsISD::DivRem";
00137   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
00138   case MipsISD::DivRem16:          return "MipsISD::DivRem16";
00139   case MipsISD::DivRemU16:         return "MipsISD::DivRemU16";
00140   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
00141   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
00142   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
00143   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
00144   case MipsISD::Sync:              return "MipsISD::Sync";
00145   case MipsISD::Ext:               return "MipsISD::Ext";
00146   case MipsISD::Ins:               return "MipsISD::Ins";
00147   case MipsISD::LWL:               return "MipsISD::LWL";
00148   case MipsISD::LWR:               return "MipsISD::LWR";
00149   case MipsISD::SWL:               return "MipsISD::SWL";
00150   case MipsISD::SWR:               return "MipsISD::SWR";
00151   case MipsISD::LDL:               return "MipsISD::LDL";
00152   case MipsISD::LDR:               return "MipsISD::LDR";
00153   case MipsISD::SDL:               return "MipsISD::SDL";
00154   case MipsISD::SDR:               return "MipsISD::SDR";
00155   case MipsISD::EXTP:              return "MipsISD::EXTP";
00156   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
00157   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
00158   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
00159   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
00160   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
00161   case MipsISD::SHILO:             return "MipsISD::SHILO";
00162   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
00163   case MipsISD::MULSAQ_S_W_PH:     return "MipsISD::MULSAQ_S_W_PH";
00164   case MipsISD::MAQ_S_W_PHL:       return "MipsISD::MAQ_S_W_PHL";
00165   case MipsISD::MAQ_S_W_PHR:       return "MipsISD::MAQ_S_W_PHR";
00166   case MipsISD::MAQ_SA_W_PHL:      return "MipsISD::MAQ_SA_W_PHL";
00167   case MipsISD::MAQ_SA_W_PHR:      return "MipsISD::MAQ_SA_W_PHR";
00168   case MipsISD::DPAU_H_QBL:        return "MipsISD::DPAU_H_QBL";
00169   case MipsISD::DPAU_H_QBR:        return "MipsISD::DPAU_H_QBR";
00170   case MipsISD::DPSU_H_QBL:        return "MipsISD::DPSU_H_QBL";
00171   case MipsISD::DPSU_H_QBR:        return "MipsISD::DPSU_H_QBR";
00172   case MipsISD::DPAQ_S_W_PH:       return "MipsISD::DPAQ_S_W_PH";
00173   case MipsISD::DPSQ_S_W_PH:       return "MipsISD::DPSQ_S_W_PH";
00174   case MipsISD::DPAQ_SA_L_W:       return "MipsISD::DPAQ_SA_L_W";
00175   case MipsISD::DPSQ_SA_L_W:       return "MipsISD::DPSQ_SA_L_W";
00176   case MipsISD::DPA_W_PH:          return "MipsISD::DPA_W_PH";
00177   case MipsISD::DPS_W_PH:          return "MipsISD::DPS_W_PH";
00178   case MipsISD::DPAQX_S_W_PH:      return "MipsISD::DPAQX_S_W_PH";
00179   case MipsISD::DPAQX_SA_W_PH:     return "MipsISD::DPAQX_SA_W_PH";
00180   case MipsISD::DPAX_W_PH:         return "MipsISD::DPAX_W_PH";
00181   case MipsISD::DPSX_W_PH:         return "MipsISD::DPSX_W_PH";
00182   case MipsISD::DPSQX_S_W_PH:      return "MipsISD::DPSQX_S_W_PH";
00183   case MipsISD::DPSQX_SA_W_PH:     return "MipsISD::DPSQX_SA_W_PH";
00184   case MipsISD::MULSA_W_PH:        return "MipsISD::MULSA_W_PH";
00185   case MipsISD::MULT:              return "MipsISD::MULT";
00186   case MipsISD::MULTU:             return "MipsISD::MULTU";
00187   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSP";
00188   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
00189   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
00190   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
00191   case MipsISD::SHLL_DSP:          return "MipsISD::SHLL_DSP";
00192   case MipsISD::SHRA_DSP:          return "MipsISD::SHRA_DSP";
00193   case MipsISD::SHRL_DSP:          return "MipsISD::SHRL_DSP";
00194   case MipsISD::SETCC_DSP:         return "MipsISD::SETCC_DSP";
00195   case MipsISD::SELECT_CC_DSP:     return "MipsISD::SELECT_CC_DSP";
00196   case MipsISD::VALL_ZERO:         return "MipsISD::VALL_ZERO";
00197   case MipsISD::VANY_ZERO:         return "MipsISD::VANY_ZERO";
00198   case MipsISD::VALL_NONZERO:      return "MipsISD::VALL_NONZERO";
00199   case MipsISD::VANY_NONZERO:      return "MipsISD::VANY_NONZERO";
00200   case MipsISD::VCEQ:              return "MipsISD::VCEQ";
00201   case MipsISD::VCLE_S:            return "MipsISD::VCLE_S";
00202   case MipsISD::VCLE_U:            return "MipsISD::VCLE_U";
00203   case MipsISD::VCLT_S:            return "MipsISD::VCLT_S";
00204   case MipsISD::VCLT_U:            return "MipsISD::VCLT_U";
00205   case MipsISD::VSMAX:             return "MipsISD::VSMAX";
00206   case MipsISD::VSMIN:             return "MipsISD::VSMIN";
00207   case MipsISD::VUMAX:             return "MipsISD::VUMAX";
00208   case MipsISD::VUMIN:             return "MipsISD::VUMIN";
00209   case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
00210   case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
00211   case MipsISD::VNOR:              return "MipsISD::VNOR";
00212   case MipsISD::VSHF:              return "MipsISD::VSHF";
00213   case MipsISD::SHF:               return "MipsISD::SHF";
00214   case MipsISD::ILVEV:             return "MipsISD::ILVEV";
00215   case MipsISD::ILVOD:             return "MipsISD::ILVOD";
00216   case MipsISD::ILVL:              return "MipsISD::ILVL";
00217   case MipsISD::ILVR:              return "MipsISD::ILVR";
00218   case MipsISD::PCKEV:             return "MipsISD::PCKEV";
00219   case MipsISD::PCKOD:             return "MipsISD::PCKOD";
00220   case MipsISD::INSVE:             return "MipsISD::INSVE";
00221   }
00222   return nullptr;
00223 }
00224 
00225 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
00226                                        const MipsSubtarget &STI)
00227     : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
00228   // Mips does not have i1 type, so use i32 for
00229   // setcc operations results (slt, sgt, ...).
00230   setBooleanContents(ZeroOrOneBooleanContent);
00231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00232   // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
00233   // does. Integer booleans still use 0 and 1.
00234   if (Subtarget.hasMips32r6())
00235     setBooleanContents(ZeroOrOneBooleanContent,
00236                        ZeroOrNegativeOneBooleanContent);
00237 
00238   // Load extented operations for i1 types must be promoted
00239   for (MVT VT : MVT::integer_valuetypes()) {
00240     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1,  Promote);
00241     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1,  Promote);
00242     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1,  Promote);
00243   }
00244 
00245   // MIPS doesn't have extending float->double load/store.  Set LoadExtAction
00246   // for f32, f16
00247   for (MVT VT : MVT::fp_valuetypes()) {
00248     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
00249     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
00250   }
00251 
00252   // Set LoadExtAction for f16 vectors to Expand
00253   for (MVT VT : MVT::fp_vector_valuetypes()) {
00254     MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
00255     if (F16VT.isValid())
00256       setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
00257   }
00258 
00259   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
00260   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
00261 
00262   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00263 
00264   // Used by legalize types to correctly generate the setcc result.
00265   // Without this, every float setcc comes with a AND/OR with the result,
00266   // we don't want this, since the fpcmp result goes to a flag register,
00267   // which is used implicitly by brcond and select operations.
00268   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
00269 
00270   // Mips Custom Operations
00271   setOperationAction(ISD::BR_JT,              MVT::Other, Custom);
00272   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
00273   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
00274   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
00275   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
00276   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
00277   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
00278   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
00279   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
00280   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
00281   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
00282   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
00283   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
00284   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
00285   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
00286 
00287   if (Subtarget.isGP64bit()) {
00288     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
00289     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
00290     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
00291     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
00292     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
00293     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
00294     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
00295     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
00296     setOperationAction(ISD::FP_TO_SINT,         MVT::i64,   Custom);
00297     setOperationAction(ISD::SHL_PARTS,          MVT::i64,   Custom);
00298     setOperationAction(ISD::SRA_PARTS,          MVT::i64,   Custom);
00299     setOperationAction(ISD::SRL_PARTS,          MVT::i64,   Custom);
00300   }
00301 
00302   if (!Subtarget.isGP64bit()) {
00303     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
00304     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
00305     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
00306   }
00307 
00308   setOperationAction(ISD::ADD,                MVT::i32,   Custom);
00309   if (Subtarget.isGP64bit())
00310     setOperationAction(ISD::ADD,                MVT::i64,   Custom);
00311 
00312   setOperationAction(ISD::SDIV, MVT::i32, Expand);
00313   setOperationAction(ISD::SREM, MVT::i32, Expand);
00314   setOperationAction(ISD::UDIV, MVT::i32, Expand);
00315   setOperationAction(ISD::UREM, MVT::i32, Expand);
00316   setOperationAction(ISD::SDIV, MVT::i64, Expand);
00317   setOperationAction(ISD::SREM, MVT::i64, Expand);
00318   setOperationAction(ISD::UDIV, MVT::i64, Expand);
00319   setOperationAction(ISD::UREM, MVT::i64, Expand);
00320 
00321   // Operations not directly supported by Mips.
00322   setOperationAction(ISD::BR_CC,             MVT::f32,   Expand);
00323   setOperationAction(ISD::BR_CC,             MVT::f64,   Expand);
00324   setOperationAction(ISD::BR_CC,             MVT::i32,   Expand);
00325   setOperationAction(ISD::BR_CC,             MVT::i64,   Expand);
00326   setOperationAction(ISD::SELECT_CC,         MVT::i32,   Expand);
00327   setOperationAction(ISD::SELECT_CC,         MVT::i64,   Expand);
00328   setOperationAction(ISD::SELECT_CC,         MVT::f32,   Expand);
00329   setOperationAction(ISD::SELECT_CC,         MVT::f64,   Expand);
00330   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
00331   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
00332   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
00333   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
00334   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
00335   if (Subtarget.hasCnMips()) {
00336     setOperationAction(ISD::CTPOP,           MVT::i32,   Legal);
00337     setOperationAction(ISD::CTPOP,           MVT::i64,   Legal);
00338   } else {
00339     setOperationAction(ISD::CTPOP,           MVT::i32,   Expand);
00340     setOperationAction(ISD::CTPOP,           MVT::i64,   Expand);
00341   }
00342   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
00343   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
00344   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
00345   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
00346   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
00347   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
00348   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
00349   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
00350   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
00351   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
00352 
00353   if (!Subtarget.hasMips32r2())
00354     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
00355 
00356   if (!Subtarget.hasMips64r2())
00357     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
00358 
00359   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
00360   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
00361   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
00362   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
00363   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
00364   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
00365   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
00366   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
00367   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
00368   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
00369   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
00370   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
00371   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
00372   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
00373   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
00374   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
00375   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
00376 
00377   // Lower f16 conversion operations into library calls
00378   setOperationAction(ISD::FP16_TO_FP,        MVT::f32,   Expand);
00379   setOperationAction(ISD::FP_TO_FP16,        MVT::f32,   Expand);
00380   setOperationAction(ISD::FP16_TO_FP,        MVT::f64,   Expand);
00381   setOperationAction(ISD::FP_TO_FP16,        MVT::f64,   Expand);
00382 
00383   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
00384 
00385   setOperationAction(ISD::VASTART,           MVT::Other, Custom);
00386   setOperationAction(ISD::VAARG,             MVT::Other, Custom);
00387   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
00388   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
00389 
00390   // Use the default for now
00391   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
00392   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
00393 
00394   if (!Subtarget.isGP64bit()) {
00395     setOperationAction(ISD::ATOMIC_LOAD,     MVT::i64,   Expand);
00396     setOperationAction(ISD::ATOMIC_STORE,    MVT::i64,   Expand);
00397   }
00398 
00399   setInsertFencesForAtomic(true);
00400 
00401   if (!Subtarget.hasMips32r2()) {
00402     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
00403     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00404   }
00405 
00406   // MIPS16 lacks MIPS32's clz and clo instructions.
00407   if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
00408     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
00409   if (!Subtarget.hasMips64())
00410     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
00411 
00412   if (!Subtarget.hasMips32r2())
00413     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00414   if (!Subtarget.hasMips64r2())
00415     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
00416 
00417   if (Subtarget.isGP64bit()) {
00418     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
00419     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
00420     setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
00421     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
00422   }
00423 
00424   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00425 
00426   setTargetDAGCombine(ISD::SDIVREM);
00427   setTargetDAGCombine(ISD::UDIVREM);
00428   setTargetDAGCombine(ISD::SELECT);
00429   setTargetDAGCombine(ISD::AND);
00430   setTargetDAGCombine(ISD::OR);
00431   setTargetDAGCombine(ISD::ADD);
00432 
00433   setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
00434 
00435   // The arguments on the stack are defined in terms of 4-byte slots on O32
00436   // and 8-byte slots on N32/N64.
00437   setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
00438 
00439   setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
00440 
00441   MaxStoresPerMemcpy = 16;
00442 
00443   isMicroMips = Subtarget.inMicroMipsMode();
00444 }
00445 
00446 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
00447                                                      const MipsSubtarget &STI) {
00448   if (STI.inMips16Mode())
00449     return llvm::createMips16TargetLowering(TM, STI);
00450 
00451   return llvm::createMipsSETargetLowering(TM, STI);
00452 }
00453 
00454 // Create a fast isel object.
00455 FastISel *
00456 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
00457                                   const TargetLibraryInfo *libInfo) const {
00458   if (!funcInfo.MF->getTarget().Options.EnableFastISel)
00459     return TargetLowering::createFastISel(funcInfo, libInfo);
00460   return Mips::createFastISel(funcInfo, libInfo);
00461 }
00462 
00463 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
00464                                            EVT VT) const {
00465   if (!VT.isVector())
00466     return MVT::i32;
00467   return VT.changeVectorElementTypeToInteger();
00468 }
00469 
00470 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
00471                                     TargetLowering::DAGCombinerInfo &DCI,
00472                                     const MipsSubtarget &Subtarget) {
00473   if (DCI.isBeforeLegalizeOps())
00474     return SDValue();
00475 
00476   EVT Ty = N->getValueType(0);
00477   unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
00478   unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
00479   unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
00480                                                   MipsISD::DivRemU16;
00481   SDLoc DL(N);
00482 
00483   SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
00484                                N->getOperand(0), N->getOperand(1));
00485   SDValue InChain = DAG.getEntryNode();
00486   SDValue InGlue = DivRem;
00487 
00488   // insert MFLO
00489   if (N->hasAnyUseOfValue(0)) {
00490     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
00491                                             InGlue);
00492     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
00493     InChain = CopyFromLo.getValue(1);
00494     InGlue = CopyFromLo.getValue(2);
00495   }
00496 
00497   // insert MFHI
00498   if (N->hasAnyUseOfValue(1)) {
00499     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
00500                                             HI, Ty, InGlue);
00501     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
00502   }
00503 
00504   return SDValue();
00505 }
00506 
00507 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
00508   switch (CC) {
00509   default: llvm_unreachable("Unknown fp condition code!");
00510   case ISD::SETEQ:
00511   case ISD::SETOEQ: return Mips::FCOND_OEQ;
00512   case ISD::SETUNE: return Mips::FCOND_UNE;
00513   case ISD::SETLT:
00514   case ISD::SETOLT: return Mips::FCOND_OLT;
00515   case ISD::SETGT:
00516   case ISD::SETOGT: return Mips::FCOND_OGT;
00517   case ISD::SETLE:
00518   case ISD::SETOLE: return Mips::FCOND_OLE;
00519   case ISD::SETGE:
00520   case ISD::SETOGE: return Mips::FCOND_OGE;
00521   case ISD::SETULT: return Mips::FCOND_ULT;
00522   case ISD::SETULE: return Mips::FCOND_ULE;
00523   case ISD::SETUGT: return Mips::FCOND_UGT;
00524   case ISD::SETUGE: return Mips::FCOND_UGE;
00525   case ISD::SETUO:  return Mips::FCOND_UN;
00526   case ISD::SETO:   return Mips::FCOND_OR;
00527   case ISD::SETNE:
00528   case ISD::SETONE: return Mips::FCOND_ONE;
00529   case ISD::SETUEQ: return Mips::FCOND_UEQ;
00530   }
00531 }
00532 
00533 
00534 /// This function returns true if the floating point conditional branches and
00535 /// conditional moves which use condition code CC should be inverted.
00536 static bool invertFPCondCodeUser(Mips::CondCode CC) {
00537   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
00538     return false;
00539 
00540   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
00541          "Illegal Condition Code");
00542 
00543   return true;
00544 }
00545 
00546 // Creates and returns an FPCmp node from a setcc node.
00547 // Returns Op if setcc is not a floating point comparison.
00548 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
00549   // must be a SETCC node
00550   if (Op.getOpcode() != ISD::SETCC)
00551     return Op;
00552 
00553   SDValue LHS = Op.getOperand(0);
00554 
00555   if (!LHS.getValueType().isFloatingPoint())
00556     return Op;
00557 
00558   SDValue RHS = Op.getOperand(1);
00559   SDLoc DL(Op);
00560 
00561   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
00562   // node if necessary.
00563   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
00564 
00565   return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
00566                      DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
00567 }
00568 
00569 // Creates and returns a CMovFPT/F node.
00570 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
00571                             SDValue False, SDLoc DL) {
00572   ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
00573   bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
00574   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
00575 
00576   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
00577                      True.getValueType(), True, FCC0, False, Cond);
00578 }
00579 
00580 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
00581                                     TargetLowering::DAGCombinerInfo &DCI,
00582                                     const MipsSubtarget &Subtarget) {
00583   if (DCI.isBeforeLegalizeOps())
00584     return SDValue();
00585 
00586   SDValue SetCC = N->getOperand(0);
00587 
00588   if ((SetCC.getOpcode() != ISD::SETCC) ||
00589       !SetCC.getOperand(0).getValueType().isInteger())
00590     return SDValue();
00591 
00592   SDValue False = N->getOperand(2);
00593   EVT FalseTy = False.getValueType();
00594 
00595   if (!FalseTy.isInteger())
00596     return SDValue();
00597 
00598   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
00599 
00600   // If the RHS (False) is 0, we swap the order of the operands
00601   // of ISD::SELECT (obviously also inverting the condition) so that we can
00602   // take advantage of conditional moves using the $0 register.
00603   // Example:
00604   //   return (a != 0) ? x : 0;
00605   //     load $reg, x
00606   //     movz $reg, $0, a
00607   if (!FalseC)
00608     return SDValue();
00609 
00610   const SDLoc DL(N);
00611 
00612   if (!FalseC->getZExtValue()) {
00613     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
00614     SDValue True = N->getOperand(1);
00615 
00616     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
00617                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
00618 
00619     return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
00620   }
00621 
00622   // If both operands are integer constants there's a possibility that we
00623   // can do some interesting optimizations.
00624   SDValue True = N->getOperand(1);
00625   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
00626 
00627   if (!TrueC || !True.getValueType().isInteger())
00628     return SDValue();
00629 
00630   // We'll also ignore MVT::i64 operands as this optimizations proves
00631   // to be ineffective because of the required sign extensions as the result
00632   // of a SETCC operator is always MVT::i32 for non-vector types.
00633   if (True.getValueType() == MVT::i64)
00634     return SDValue();
00635 
00636   int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
00637 
00638   // 1)  (a < x) ? y : y-1
00639   //  slti $reg1, a, x
00640   //  addiu $reg2, $reg1, y-1
00641   if (Diff == 1)
00642     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
00643 
00644   // 2)  (a < x) ? y-1 : y
00645   //  slti $reg1, a, x
00646   //  xor $reg1, $reg1, 1
00647   //  addiu $reg2, $reg1, y-1
00648   if (Diff == -1) {
00649     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
00650     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
00651                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
00652     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
00653   }
00654 
00655   // Couldn't optimize.
00656   return SDValue();
00657 }
00658 
00659 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
00660                                     TargetLowering::DAGCombinerInfo &DCI,
00661                                     const MipsSubtarget &Subtarget) {
00662   if (DCI.isBeforeLegalizeOps())
00663     return SDValue();
00664 
00665   SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
00666 
00667   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
00668   if (!FalseC || FalseC->getZExtValue())
00669     return SDValue();
00670 
00671   // Since RHS (False) is 0, we swap the order of the True/False operands
00672   // (obviously also inverting the condition) so that we can
00673   // take advantage of conditional moves using the $0 register.
00674   // Example:
00675   //   return (a != 0) ? x : 0;
00676   //     load $reg, x
00677   //     movz $reg, $0, a
00678   unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
00679                                                          MipsISD::CMovFP_T;
00680 
00681   SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
00682   return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
00683                      ValueIfFalse, FCC, ValueIfTrue, Glue);
00684 }
00685 
00686 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
00687                                  TargetLowering::DAGCombinerInfo &DCI,
00688                                  const MipsSubtarget &Subtarget) {
00689   // Pattern match EXT.
00690   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
00691   //  => ext $dst, $src, size, pos
00692   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
00693     return SDValue();
00694 
00695   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
00696   unsigned ShiftRightOpc = ShiftRight.getOpcode();
00697 
00698   // Op's first operand must be a shift right.
00699   if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
00700     return SDValue();
00701 
00702   // The second operand of the shift must be an immediate.
00703   ConstantSDNode *CN;
00704   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
00705     return SDValue();
00706 
00707   uint64_t Pos = CN->getZExtValue();
00708   uint64_t SMPos, SMSize;
00709 
00710   // Op's second operand must be a shifted mask.
00711   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
00712       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
00713     return SDValue();
00714 
00715   // Return if the shifted mask does not start at bit 0 or the sum of its size
00716   // and Pos exceeds the word's size.
00717   EVT ValTy = N->getValueType(0);
00718   if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
00719     return SDValue();
00720 
00721   SDLoc DL(N);
00722   return DAG.getNode(MipsISD::Ext, DL, ValTy,
00723                      ShiftRight.getOperand(0),
00724                      DAG.getConstant(Pos, DL, MVT::i32),
00725                      DAG.getConstant(SMSize, DL, MVT::i32));
00726 }
00727 
00728 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
00729                                 TargetLowering::DAGCombinerInfo &DCI,
00730                                 const MipsSubtarget &Subtarget) {
00731   // Pattern match INS.
00732   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
00733   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
00734   //  => ins $dst, $src, size, pos, $src1
00735   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
00736     return SDValue();
00737 
00738   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
00739   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
00740   ConstantSDNode *CN;
00741 
00742   // See if Op's first operand matches (and $src1 , mask0).
00743   if (And0.getOpcode() != ISD::AND)
00744     return SDValue();
00745 
00746   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
00747       !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
00748     return SDValue();
00749 
00750   // See if Op's second operand matches (and (shl $src, pos), mask1).
00751   if (And1.getOpcode() != ISD::AND)
00752     return SDValue();
00753 
00754   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
00755       !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
00756     return SDValue();
00757 
00758   // The shift masks must have the same position and size.
00759   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
00760     return SDValue();
00761 
00762   SDValue Shl = And1.getOperand(0);
00763   if (Shl.getOpcode() != ISD::SHL)
00764     return SDValue();
00765 
00766   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
00767     return SDValue();
00768 
00769   unsigned Shamt = CN->getZExtValue();
00770 
00771   // Return if the shift amount and the first bit position of mask are not the
00772   // same.
00773   EVT ValTy = N->getValueType(0);
00774   if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
00775     return SDValue();
00776 
00777   SDLoc DL(N);
00778   return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
00779                      DAG.getConstant(SMPos0, DL, MVT::i32),
00780                      DAG.getConstant(SMSize0, DL, MVT::i32),
00781                      And0.getOperand(0));
00782 }
00783 
00784 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
00785                                  TargetLowering::DAGCombinerInfo &DCI,
00786                                  const MipsSubtarget &Subtarget) {
00787   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
00788 
00789   if (DCI.isBeforeLegalizeOps())
00790     return SDValue();
00791 
00792   SDValue Add = N->getOperand(1);
00793 
00794   if (Add.getOpcode() != ISD::ADD)
00795     return SDValue();
00796 
00797   SDValue Lo = Add.getOperand(1);
00798 
00799   if ((Lo.getOpcode() != MipsISD::Lo) ||
00800       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
00801     return SDValue();
00802 
00803   EVT ValTy = N->getValueType(0);
00804   SDLoc DL(N);
00805 
00806   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
00807                              Add.getOperand(0));
00808   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
00809 }
00810 
00811 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
00812   const {
00813   SelectionDAG &DAG = DCI.DAG;
00814   unsigned Opc = N->getOpcode();
00815 
00816   switch (Opc) {
00817   default: break;
00818   case ISD::SDIVREM:
00819   case ISD::UDIVREM:
00820     return performDivRemCombine(N, DAG, DCI, Subtarget);
00821   case ISD::SELECT:
00822     return performSELECTCombine(N, DAG, DCI, Subtarget);
00823   case MipsISD::CMovFP_F:
00824   case MipsISD::CMovFP_T:
00825     return performCMovFPCombine(N, DAG, DCI, Subtarget);
00826   case ISD::AND:
00827     return performANDCombine(N, DAG, DCI, Subtarget);
00828   case ISD::OR:
00829     return performORCombine(N, DAG, DCI, Subtarget);
00830   case ISD::ADD:
00831     return performADDCombine(N, DAG, DCI, Subtarget);
00832   }
00833 
00834   return SDValue();
00835 }
00836 
00837 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
00838   return Subtarget.hasMips32();
00839 }
00840 
00841 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
00842   return Subtarget.hasMips32();
00843 }
00844 
00845 void
00846 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
00847                                           SmallVectorImpl<SDValue> &Results,
00848                                           SelectionDAG &DAG) const {
00849   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
00850 
00851   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
00852     Results.push_back(Res.getValue(I));
00853 }
00854 
00855 void
00856 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
00857                                        SmallVectorImpl<SDValue> &Results,
00858                                        SelectionDAG &DAG) const {
00859   return LowerOperationWrapper(N, Results, DAG);
00860 }
00861 
00862 SDValue MipsTargetLowering::
00863 LowerOperation(SDValue Op, SelectionDAG &DAG) const
00864 {
00865   switch (Op.getOpcode())
00866   {
00867   case ISD::BR_JT:              return lowerBR_JT(Op, DAG);
00868   case ISD::BRCOND:             return lowerBRCOND(Op, DAG);
00869   case ISD::ConstantPool:       return lowerConstantPool(Op, DAG);
00870   case ISD::GlobalAddress:      return lowerGlobalAddress(Op, DAG);
00871   case ISD::BlockAddress:       return lowerBlockAddress(Op, DAG);
00872   case ISD::GlobalTLSAddress:   return lowerGlobalTLSAddress(Op, DAG);
00873   case ISD::JumpTable:          return lowerJumpTable(Op, DAG);
00874   case ISD::SELECT:             return lowerSELECT(Op, DAG);
00875   case ISD::SETCC:              return lowerSETCC(Op, DAG);
00876   case ISD::VASTART:            return lowerVASTART(Op, DAG);
00877   case ISD::VAARG:              return lowerVAARG(Op, DAG);
00878   case ISD::FCOPYSIGN:          return lowerFCOPYSIGN(Op, DAG);
00879   case ISD::FRAMEADDR:          return lowerFRAMEADDR(Op, DAG);
00880   case ISD::RETURNADDR:         return lowerRETURNADDR(Op, DAG);
00881   case ISD::EH_RETURN:          return lowerEH_RETURN(Op, DAG);
00882   case ISD::ATOMIC_FENCE:       return lowerATOMIC_FENCE(Op, DAG);
00883   case ISD::SHL_PARTS:          return lowerShiftLeftParts(Op, DAG);
00884   case ISD::SRA_PARTS:          return lowerShiftRightParts(Op, DAG, true);
00885   case ISD::SRL_PARTS:          return lowerShiftRightParts(Op, DAG, false);
00886   case ISD::LOAD:               return lowerLOAD(Op, DAG);
00887   case ISD::STORE:              return lowerSTORE(Op, DAG);
00888   case ISD::ADD:                return lowerADD(Op, DAG);
00889   case ISD::FP_TO_SINT:         return lowerFP_TO_SINT(Op, DAG);
00890   }
00891   return SDValue();
00892 }
00893 
00894 //===----------------------------------------------------------------------===//
00895 //  Lower helper functions
00896 //===----------------------------------------------------------------------===//
00897 
00898 // addLiveIn - This helper function adds the specified physical register to the
00899 // MachineFunction as a live in value.  It also creates a corresponding
00900 // virtual register for it.
00901 static unsigned
00902 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
00903 {
00904   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
00905   MF.getRegInfo().addLiveIn(PReg, VReg);
00906   return VReg;
00907 }
00908 
00909 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
00910                                               MachineBasicBlock &MBB,
00911                                               const TargetInstrInfo &TII,
00912                                               bool Is64Bit) {
00913   if (NoZeroDivCheck)
00914     return &MBB;
00915 
00916   // Insert instruction "teq $divisor_reg, $zero, 7".
00917   MachineBasicBlock::iterator I(MI);
00918   MachineInstrBuilder MIB;
00919   MachineOperand &Divisor = MI->getOperand(2);
00920   MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
00921     .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
00922     .addReg(Mips::ZERO).addImm(7);
00923 
00924   // Use the 32-bit sub-register if this is a 64-bit division.
00925   if (Is64Bit)
00926     MIB->getOperand(0).setSubReg(Mips::sub_32);
00927 
00928   // Clear Divisor's kill flag.
00929   Divisor.setIsKill(false);
00930 
00931   // We would normally delete the original instruction here but in this case
00932   // we only needed to inject an additional instruction rather than replace it.
00933 
00934   return &MBB;
00935 }
00936 
00937 MachineBasicBlock *
00938 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00939                                                 MachineBasicBlock *BB) const {
00940   switch (MI->getOpcode()) {
00941   default:
00942     llvm_unreachable("Unexpected instr type to insert");
00943   case Mips::ATOMIC_LOAD_ADD_I8:
00944     return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
00945   case Mips::ATOMIC_LOAD_ADD_I16:
00946     return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
00947   case Mips::ATOMIC_LOAD_ADD_I32:
00948     return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
00949   case Mips::ATOMIC_LOAD_ADD_I64:
00950     return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
00951 
00952   case Mips::ATOMIC_LOAD_AND_I8:
00953     return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
00954   case Mips::ATOMIC_LOAD_AND_I16:
00955     return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
00956   case Mips::ATOMIC_LOAD_AND_I32:
00957     return emitAtomicBinary(MI, BB, 4, Mips::AND);
00958   case Mips::ATOMIC_LOAD_AND_I64:
00959     return emitAtomicBinary(MI, BB, 8, Mips::AND64);
00960 
00961   case Mips::ATOMIC_LOAD_OR_I8:
00962     return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
00963   case Mips::ATOMIC_LOAD_OR_I16:
00964     return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
00965   case Mips::ATOMIC_LOAD_OR_I32:
00966     return emitAtomicBinary(MI, BB, 4, Mips::OR);
00967   case Mips::ATOMIC_LOAD_OR_I64:
00968     return emitAtomicBinary(MI, BB, 8, Mips::OR64);
00969 
00970   case Mips::ATOMIC_LOAD_XOR_I8:
00971     return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
00972   case Mips::ATOMIC_LOAD_XOR_I16:
00973     return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
00974   case Mips::ATOMIC_LOAD_XOR_I32:
00975     return emitAtomicBinary(MI, BB, 4, Mips::XOR);
00976   case Mips::ATOMIC_LOAD_XOR_I64:
00977     return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
00978 
00979   case Mips::ATOMIC_LOAD_NAND_I8:
00980     return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
00981   case Mips::ATOMIC_LOAD_NAND_I16:
00982     return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
00983   case Mips::ATOMIC_LOAD_NAND_I32:
00984     return emitAtomicBinary(MI, BB, 4, 0, true);
00985   case Mips::ATOMIC_LOAD_NAND_I64:
00986     return emitAtomicBinary(MI, BB, 8, 0, true);
00987 
00988   case Mips::ATOMIC_LOAD_SUB_I8:
00989     return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
00990   case Mips::ATOMIC_LOAD_SUB_I16:
00991     return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
00992   case Mips::ATOMIC_LOAD_SUB_I32:
00993     return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
00994   case Mips::ATOMIC_LOAD_SUB_I64:
00995     return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
00996 
00997   case Mips::ATOMIC_SWAP_I8:
00998     return emitAtomicBinaryPartword(MI, BB, 1, 0);
00999   case Mips::ATOMIC_SWAP_I16:
01000     return emitAtomicBinaryPartword(MI, BB, 2, 0);
01001   case Mips::ATOMIC_SWAP_I32:
01002     return emitAtomicBinary(MI, BB, 4, 0);
01003   case Mips::ATOMIC_SWAP_I64:
01004     return emitAtomicBinary(MI, BB, 8, 0);
01005 
01006   case Mips::ATOMIC_CMP_SWAP_I8:
01007     return emitAtomicCmpSwapPartword(MI, BB, 1);
01008   case Mips::ATOMIC_CMP_SWAP_I16:
01009     return emitAtomicCmpSwapPartword(MI, BB, 2);
01010   case Mips::ATOMIC_CMP_SWAP_I32:
01011     return emitAtomicCmpSwap(MI, BB, 4);
01012   case Mips::ATOMIC_CMP_SWAP_I64:
01013     return emitAtomicCmpSwap(MI, BB, 8);
01014   case Mips::PseudoSDIV:
01015   case Mips::PseudoUDIV:
01016   case Mips::DIV:
01017   case Mips::DIVU:
01018   case Mips::MOD:
01019   case Mips::MODU:
01020     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
01021   case Mips::PseudoDSDIV:
01022   case Mips::PseudoDUDIV:
01023   case Mips::DDIV:
01024   case Mips::DDIVU:
01025   case Mips::DMOD:
01026   case Mips::DMODU:
01027     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
01028   case Mips::SEL_D:
01029     return emitSEL_D(MI, BB);
01030 
01031   case Mips::PseudoSELECT_I:
01032   case Mips::PseudoSELECT_I64:
01033   case Mips::PseudoSELECT_S:
01034   case Mips::PseudoSELECT_D32:
01035   case Mips::PseudoSELECT_D64:
01036     return emitPseudoSELECT(MI, BB, false, Mips::BNE);
01037   case Mips::PseudoSELECTFP_F_I:
01038   case Mips::PseudoSELECTFP_F_I64:
01039   case Mips::PseudoSELECTFP_F_S:
01040   case Mips::PseudoSELECTFP_F_D32:
01041   case Mips::PseudoSELECTFP_F_D64:
01042     return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
01043   case Mips::PseudoSELECTFP_T_I:
01044   case Mips::PseudoSELECTFP_T_I64:
01045   case Mips::PseudoSELECTFP_T_S:
01046   case Mips::PseudoSELECTFP_T_D32:
01047   case Mips::PseudoSELECTFP_T_D64:
01048     return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
01049   }
01050 }
01051 
01052 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
01053 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
01054 MachineBasicBlock *
01055 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
01056                                      unsigned Size, unsigned BinOpcode,
01057                                      bool Nand) const {
01058   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
01059 
01060   MachineFunction *MF = BB->getParent();
01061   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01062   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
01063   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
01064   DebugLoc DL = MI->getDebugLoc();
01065   unsigned LL, SC, AND, NOR, ZERO, BEQ;
01066 
01067   if (Size == 4) {
01068     if (isMicroMips) {
01069       LL = Mips::LL_MM;
01070       SC = Mips::SC_MM;
01071     } else {
01072       LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
01073       SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
01074     }
01075     AND = Mips::AND;
01076     NOR = Mips::NOR;
01077     ZERO = Mips::ZERO;
01078     BEQ = Mips::BEQ;
01079   } else {
01080     LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
01081     SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
01082     AND = Mips::AND64;
01083     NOR = Mips::NOR64;
01084     ZERO = Mips::ZERO_64;
01085     BEQ = Mips::BEQ64;
01086   }
01087 
01088   unsigned OldVal = MI->getOperand(0).getReg();
01089   unsigned Ptr = MI->getOperand(1).getReg();
01090   unsigned Incr = MI->getOperand(2).getReg();
01091 
01092   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
01093   unsigned AndRes = RegInfo.createVirtualRegister(RC);
01094   unsigned Success = RegInfo.createVirtualRegister(RC);
01095 
01096   // insert new blocks after the current block
01097   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01098   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01099   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01100   MachineFunction::iterator It = ++BB->getIterator();
01101   MF->insert(It, loopMBB);
01102   MF->insert(It, exitMBB);
01103 
01104   // Transfer the remainder of BB and its successor edges to exitMBB.
01105   exitMBB->splice(exitMBB->begin(), BB,
01106                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01107   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01108 
01109   //  thisMBB:
01110   //    ...
01111   //    fallthrough --> loopMBB
01112   BB->addSuccessor(loopMBB);
01113   loopMBB->addSuccessor(loopMBB);
01114   loopMBB->addSuccessor(exitMBB);
01115 
01116   //  loopMBB:
01117   //    ll oldval, 0(ptr)
01118   //    <binop> storeval, oldval, incr
01119   //    sc success, storeval, 0(ptr)
01120   //    beq success, $0, loopMBB
01121   BB = loopMBB;
01122   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
01123   if (Nand) {
01124     //  and andres, oldval, incr
01125     //  nor storeval, $0, andres
01126     BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
01127     BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
01128   } else if (BinOpcode) {
01129     //  <binop> storeval, oldval, incr
01130     BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
01131   } else {
01132     StoreVal = Incr;
01133   }
01134   BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
01135   BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
01136 
01137   MI->eraseFromParent(); // The instruction is gone now.
01138 
01139   return exitMBB;
01140 }
01141 
01142 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
01143     MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
01144     unsigned SrcReg) const {
01145   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
01146   DebugLoc DL = MI->getDebugLoc();
01147 
01148   if (Subtarget.hasMips32r2() && Size == 1) {
01149     BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
01150     return BB;
01151   }
01152 
01153   if (Subtarget.hasMips32r2() && Size == 2) {
01154     BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
01155     return BB;
01156   }
01157 
01158   MachineFunction *MF = BB->getParent();
01159   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01160   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
01161   unsigned ScrReg = RegInfo.createVirtualRegister(RC);
01162 
01163   assert(Size < 32);
01164   int64_t ShiftImm = 32 - (Size * 8);
01165 
01166   BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
01167   BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
01168 
01169   return BB;
01170 }
01171 
01172 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
01173     MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
01174     bool Nand) const {
01175   assert((Size == 1 || Size == 2) &&
01176          "Unsupported size for EmitAtomicBinaryPartial.");
01177 
01178   MachineFunction *MF = BB->getParent();
01179   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01180   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
01181   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
01182   DebugLoc DL = MI->getDebugLoc();
01183 
01184   unsigned Dest = MI->getOperand(0).getReg();
01185   unsigned Ptr = MI->getOperand(1).getReg();
01186   unsigned Incr = MI->getOperand(2).getReg();
01187 
01188   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
01189   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
01190   unsigned Mask = RegInfo.createVirtualRegister(RC);
01191   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
01192   unsigned NewVal = RegInfo.createVirtualRegister(RC);
01193   unsigned OldVal = RegInfo.createVirtualRegister(RC);
01194   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
01195   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
01196   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
01197   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
01198   unsigned AndRes = RegInfo.createVirtualRegister(RC);
01199   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
01200   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
01201   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
01202   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
01203   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
01204   unsigned Success = RegInfo.createVirtualRegister(RC);
01205 
01206   // insert new blocks after the current block
01207   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01208   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01209   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01210   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01211   MachineFunction::iterator It = ++BB->getIterator();
01212   MF->insert(It, loopMBB);
01213   MF->insert(It, sinkMBB);
01214   MF->insert(It, exitMBB);
01215 
01216   // Transfer the remainder of BB and its successor edges to exitMBB.
01217   exitMBB->splice(exitMBB->begin(), BB,
01218                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01219   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01220 
01221   BB->addSuccessor(loopMBB);
01222   loopMBB->addSuccessor(loopMBB);
01223   loopMBB->addSuccessor(sinkMBB);
01224   sinkMBB->addSuccessor(exitMBB);
01225 
01226   //  thisMBB:
01227   //    addiu   masklsb2,$0,-4                # 0xfffffffc
01228   //    and     alignedaddr,ptr,masklsb2
01229   //    andi    ptrlsb2,ptr,3
01230   //    sll     shiftamt,ptrlsb2,3
01231   //    ori     maskupper,$0,255               # 0xff
01232   //    sll     mask,maskupper,shiftamt
01233   //    nor     mask2,$0,mask
01234   //    sll     incr2,incr,shiftamt
01235 
01236   int64_t MaskImm = (Size == 1) ? 255 : 65535;
01237   BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
01238     .addReg(Mips::ZERO).addImm(-4);
01239   BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
01240     .addReg(Ptr).addReg(MaskLSB2);
01241   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
01242   if (Subtarget.isLittle()) {
01243     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
01244   } else {
01245     unsigned Off = RegInfo.createVirtualRegister(RC);
01246     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
01247       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
01248     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
01249   }
01250   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
01251     .addReg(Mips::ZERO).addImm(MaskImm);
01252   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
01253     .addReg(MaskUpper).addReg(ShiftAmt);
01254   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
01255   BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
01256 
01257   // atomic.load.binop
01258   // loopMBB:
01259   //   ll      oldval,0(alignedaddr)
01260   //   binop   binopres,oldval,incr2
01261   //   and     newval,binopres,mask
01262   //   and     maskedoldval0,oldval,mask2
01263   //   or      storeval,maskedoldval0,newval
01264   //   sc      success,storeval,0(alignedaddr)
01265   //   beq     success,$0,loopMBB
01266 
01267   // atomic.swap
01268   // loopMBB:
01269   //   ll      oldval,0(alignedaddr)
01270   //   and     newval,incr2,mask
01271   //   and     maskedoldval0,oldval,mask2
01272   //   or      storeval,maskedoldval0,newval
01273   //   sc      success,storeval,0(alignedaddr)
01274   //   beq     success,$0,loopMBB
01275 
01276   BB = loopMBB;
01277   unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
01278   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
01279   if (Nand) {
01280     //  and andres, oldval, incr2
01281     //  nor binopres, $0, andres
01282     //  and newval, binopres, mask
01283     BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
01284     BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
01285       .addReg(Mips::ZERO).addReg(AndRes);
01286     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
01287   } else if (BinOpcode) {
01288     //  <binop> binopres, oldval, incr2
01289     //  and newval, binopres, mask
01290     BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
01291     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
01292   } else { // atomic.swap
01293     //  and newval, incr2, mask
01294     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
01295   }
01296 
01297   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
01298     .addReg(OldVal).addReg(Mask2);
01299   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
01300     .addReg(MaskedOldVal0).addReg(NewVal);
01301   unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
01302   BuildMI(BB, DL, TII->get(SC), Success)
01303     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
01304   BuildMI(BB, DL, TII->get(Mips::BEQ))
01305     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
01306 
01307   //  sinkMBB:
01308   //    and     maskedoldval1,oldval,mask
01309   //    srl     srlres,maskedoldval1,shiftamt
01310   //    sign_extend dest,srlres
01311   BB = sinkMBB;
01312 
01313   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
01314     .addReg(OldVal).addReg(Mask);
01315   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
01316       .addReg(MaskedOldVal1).addReg(ShiftAmt);
01317   BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
01318 
01319   MI->eraseFromParent(); // The instruction is gone now.
01320 
01321   return exitMBB;
01322 }
01323 
01324 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
01325                                                           MachineBasicBlock *BB,
01326                                                           unsigned Size) const {
01327   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
01328 
01329   MachineFunction *MF = BB->getParent();
01330   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01331   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
01332   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
01333   DebugLoc DL = MI->getDebugLoc();
01334   unsigned LL, SC, ZERO, BNE, BEQ;
01335 
01336    if (Size == 4) {
01337      if (isMicroMips) {
01338        LL = Mips::LL_MM;
01339        SC = Mips::SC_MM;
01340      } else {
01341        LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
01342        SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
01343      }
01344     ZERO = Mips::ZERO;
01345     BNE = Mips::BNE;
01346     BEQ = Mips::BEQ;
01347   } else {
01348     LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
01349     SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
01350     ZERO = Mips::ZERO_64;
01351     BNE = Mips::BNE64;
01352     BEQ = Mips::BEQ64;
01353   }
01354 
01355   unsigned Dest    = MI->getOperand(0).getReg();
01356   unsigned Ptr     = MI->getOperand(1).getReg();
01357   unsigned OldVal  = MI->getOperand(2).getReg();
01358   unsigned NewVal  = MI->getOperand(3).getReg();
01359 
01360   unsigned Success = RegInfo.createVirtualRegister(RC);
01361 
01362   // insert new blocks after the current block
01363   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01364   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01365   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01366   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01367   MachineFunction::iterator It = ++BB->getIterator();
01368   MF->insert(It, loop1MBB);
01369   MF->insert(It, loop2MBB);
01370   MF->insert(It, exitMBB);
01371 
01372   // Transfer the remainder of BB and its successor edges to exitMBB.
01373   exitMBB->splice(exitMBB->begin(), BB,
01374                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01375   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01376 
01377   //  thisMBB:
01378   //    ...
01379   //    fallthrough --> loop1MBB
01380   BB->addSuccessor(loop1MBB);
01381   loop1MBB->addSuccessor(exitMBB);
01382   loop1MBB->addSuccessor(loop2MBB);
01383   loop2MBB->addSuccessor(loop1MBB);
01384   loop2MBB->addSuccessor(exitMBB);
01385 
01386   // loop1MBB:
01387   //   ll dest, 0(ptr)
01388   //   bne dest, oldval, exitMBB
01389   BB = loop1MBB;
01390   BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
01391   BuildMI(BB, DL, TII->get(BNE))
01392     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
01393 
01394   // loop2MBB:
01395   //   sc success, newval, 0(ptr)
01396   //   beq success, $0, loop1MBB
01397   BB = loop2MBB;
01398   BuildMI(BB, DL, TII->get(SC), Success)
01399     .addReg(NewVal).addReg(Ptr).addImm(0);
01400   BuildMI(BB, DL, TII->get(BEQ))
01401     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
01402 
01403   MI->eraseFromParent(); // The instruction is gone now.
01404 
01405   return exitMBB;
01406 }
01407 
01408 MachineBasicBlock *
01409 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
01410                                               MachineBasicBlock *BB,
01411                                               unsigned Size) const {
01412   assert((Size == 1 || Size == 2) &&
01413       "Unsupported size for EmitAtomicCmpSwapPartial.");
01414 
01415   MachineFunction *MF = BB->getParent();
01416   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01417   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
01418   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
01419   DebugLoc DL = MI->getDebugLoc();
01420 
01421   unsigned Dest    = MI->getOperand(0).getReg();
01422   unsigned Ptr     = MI->getOperand(1).getReg();
01423   unsigned CmpVal  = MI->getOperand(2).getReg();
01424   unsigned NewVal  = MI->getOperand(3).getReg();
01425 
01426   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
01427   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
01428   unsigned Mask = RegInfo.createVirtualRegister(RC);
01429   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
01430   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
01431   unsigned OldVal = RegInfo.createVirtualRegister(RC);
01432   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
01433   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
01434   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
01435   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
01436   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
01437   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
01438   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
01439   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
01440   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
01441   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
01442   unsigned Success = RegInfo.createVirtualRegister(RC);
01443 
01444   // insert new blocks after the current block
01445   const BasicBlock *LLVM_BB = BB->getBasicBlock();
01446   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01447   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
01448   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01449   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
01450   MachineFunction::iterator It = ++BB->getIterator();
01451   MF->insert(It, loop1MBB);
01452   MF->insert(It, loop2MBB);
01453   MF->insert(It, sinkMBB);
01454   MF->insert(It, exitMBB);
01455 
01456   // Transfer the remainder of BB and its successor edges to exitMBB.
01457   exitMBB->splice(exitMBB->begin(), BB,
01458                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
01459   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
01460 
01461   BB->addSuccessor(loop1MBB);
01462   loop1MBB->addSuccessor(sinkMBB);
01463   loop1MBB->addSuccessor(loop2MBB);
01464   loop2MBB->addSuccessor(loop1MBB);
01465   loop2MBB->addSuccessor(sinkMBB);
01466   sinkMBB->addSuccessor(exitMBB);
01467 
01468   // FIXME: computation of newval2 can be moved to loop2MBB.
01469   //  thisMBB:
01470   //    addiu   masklsb2,$0,-4                # 0xfffffffc
01471   //    and     alignedaddr,ptr,masklsb2
01472   //    andi    ptrlsb2,ptr,3
01473   //    sll     shiftamt,ptrlsb2,3
01474   //    ori     maskupper,$0,255               # 0xff
01475   //    sll     mask,maskupper,shiftamt
01476   //    nor     mask2,$0,mask
01477   //    andi    maskedcmpval,cmpval,255
01478   //    sll     shiftedcmpval,maskedcmpval,shiftamt
01479   //    andi    maskednewval,newval,255
01480   //    sll     shiftednewval,maskednewval,shiftamt
01481   int64_t MaskImm = (Size == 1) ? 255 : 65535;
01482   BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
01483     .addReg(Mips::ZERO).addImm(-4);
01484   BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
01485     .addReg(Ptr).addReg(MaskLSB2);
01486   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
01487   if (Subtarget.isLittle()) {
01488     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
01489   } else {
01490     unsigned Off = RegInfo.createVirtualRegister(RC);
01491     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
01492       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
01493     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
01494   }
01495   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
01496     .addReg(Mips::ZERO).addImm(MaskImm);
01497   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
01498     .addReg(MaskUpper).addReg(ShiftAmt);
01499   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
01500   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
01501     .addReg(CmpVal).addImm(MaskImm);
01502   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
01503     .addReg(MaskedCmpVal).addReg(ShiftAmt);
01504   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
01505     .addReg(NewVal).addImm(MaskImm);
01506   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
01507     .addReg(MaskedNewVal).addReg(ShiftAmt);
01508 
01509   //  loop1MBB:
01510   //    ll      oldval,0(alginedaddr)
01511   //    and     maskedoldval0,oldval,mask
01512   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
01513   BB = loop1MBB;
01514   unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
01515   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
01516   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
01517     .addReg(OldVal).addReg(Mask);
01518   BuildMI(BB, DL, TII->get(Mips::BNE))
01519     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
01520 
01521   //  loop2MBB:
01522   //    and     maskedoldval1,oldval,mask2
01523   //    or      storeval,maskedoldval1,shiftednewval
01524   //    sc      success,storeval,0(alignedaddr)
01525   //    beq     success,$0,loop1MBB
01526   BB = loop2MBB;
01527   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
01528     .addReg(OldVal).addReg(Mask2);
01529   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
01530     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
01531   unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
01532   BuildMI(BB, DL, TII->get(SC), Success)
01533       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
01534   BuildMI(BB, DL, TII->get(Mips::BEQ))
01535       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
01536 
01537   //  sinkMBB:
01538   //    srl     srlres,maskedoldval0,shiftamt
01539   //    sign_extend dest,srlres
01540   BB = sinkMBB;
01541 
01542   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
01543       .addReg(MaskedOldVal0).addReg(ShiftAmt);
01544   BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
01545 
01546   MI->eraseFromParent();   // The instruction is gone now.
01547 
01548   return exitMBB;
01549 }
01550 
01551 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
01552                                                  MachineBasicBlock *BB) const {
01553   MachineFunction *MF = BB->getParent();
01554   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
01555   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
01556   MachineRegisterInfo &RegInfo = MF->getRegInfo();
01557   DebugLoc DL = MI->getDebugLoc();
01558   MachineBasicBlock::iterator II(MI);
01559 
01560   unsigned Fc = MI->getOperand(1).getReg();
01561   const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
01562 
01563   unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
01564 
01565   BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
01566       .addImm(0)
01567       .addReg(Fc)
01568       .addImm(Mips::sub_lo);
01569 
01570   // We don't erase the original instruction, we just replace the condition
01571   // register with the 64-bit super-register.
01572   MI->getOperand(1).setReg(Fc2);
01573 
01574   return BB;
01575 }
01576 
01577 //===----------------------------------------------------------------------===//
01578 //  Misc Lower Operation implementation
01579 //===----------------------------------------------------------------------===//
01580 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
01581   SDValue Chain = Op.getOperand(0);
01582   SDValue Table = Op.getOperand(1);
01583   SDValue Index = Op.getOperand(2);
01584   SDLoc DL(Op);
01585   auto &TD = DAG.getDataLayout();
01586   EVT PTy = getPointerTy(TD);
01587   unsigned EntrySize =
01588       DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
01589 
01590   Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
01591                       DAG.getConstant(EntrySize, DL, PTy));
01592   SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
01593 
01594   EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
01595   Addr =
01596       DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
01597                      MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
01598                      MemVT, false, false, false, 0);
01599   Chain = Addr.getValue(1);
01600 
01601   if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
01602     // For PIC, the sequence is:
01603     // BRIND(load(Jumptable + index) + RelocBase)
01604     // RelocBase can be JumpTable, GOT or some sort of global base.
01605     Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
01606                        getPICJumpTableRelocBase(Table, DAG));
01607   }
01608 
01609   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
01610 }
01611 
01612 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
01613   // The first operand is the chain, the second is the condition, the third is
01614   // the block to branch to if the condition is true.
01615   SDValue Chain = Op.getOperand(0);
01616   SDValue Dest = Op.getOperand(2);
01617   SDLoc DL(Op);
01618 
01619   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
01620   SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
01621 
01622   // Return if flag is not set by a floating point comparison.
01623   if (CondRes.getOpcode() != MipsISD::FPCmp)
01624     return Op;
01625 
01626   SDValue CCNode  = CondRes.getOperand(2);
01627   Mips::CondCode CC =
01628     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
01629   unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
01630   SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
01631   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
01632   return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
01633                      FCC0, Dest, CondRes);
01634 }
01635 
01636 SDValue MipsTargetLowering::
01637 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
01638 {
01639   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
01640   SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
01641 
01642   // Return if flag is not set by a floating point comparison.
01643   if (Cond.getOpcode() != MipsISD::FPCmp)
01644     return Op;
01645 
01646   return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
01647                       SDLoc(Op));
01648 }
01649 
01650 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
01651   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
01652   SDValue Cond = createFPCmp(DAG, Op);
01653 
01654   assert(Cond.getOpcode() == MipsISD::FPCmp &&
01655          "Floating point operand expected.");
01656 
01657   SDLoc DL(Op);
01658   SDValue True  = DAG.getConstant(1, DL, MVT::i32);
01659   SDValue False = DAG.getConstant(0, DL, MVT::i32);
01660 
01661   return createCMovFP(DAG, Cond, True, False, DL);
01662 }
01663 
01664 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
01665                                                SelectionDAG &DAG) const {
01666   EVT Ty = Op.getValueType();
01667   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
01668   const GlobalValue *GV = N->getGlobal();
01669 
01670   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
01671     const MipsTargetObjectFile *TLOF =
01672         static_cast<const MipsTargetObjectFile *>(
01673             getTargetMachine().getObjFileLowering());
01674     if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
01675       // %gp_rel relocation
01676       return getAddrGPRel(N, SDLoc(N), Ty, DAG);
01677 
01678     // %hi/%lo relocation
01679     return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
01680   }
01681 
01682   if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
01683     return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
01684 
01685   if (LargeGOT)
01686     return getAddrGlobalLargeGOT(
01687         N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
01688         DAG.getEntryNode(),
01689         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
01690 
01691   return getAddrGlobal(
01692       N, SDLoc(N), Ty, DAG,
01693       (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
01694       DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
01695 }
01696 
01697 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
01698                                               SelectionDAG &DAG) const {
01699   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
01700   EVT Ty = Op.getValueType();
01701 
01702   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
01703     return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
01704 
01705   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
01706 }
01707 
01708 SDValue MipsTargetLowering::
01709 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
01710 {
01711   // If the relocation model is PIC, use the General Dynamic TLS Model or
01712   // Local Dynamic TLS model, otherwise use the Initial Exec or
01713   // Local Exec TLS Model.
01714 
01715   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
01716   if (DAG.getTarget().Options.EmulatedTLS)
01717     return LowerToTLSEmulatedModel(GA, DAG);
01718 
01719   SDLoc DL(GA);
01720   const GlobalValue *GV = GA->getGlobal();
01721   EVT PtrVT = getPointerTy(DAG.getDataLayout());
01722 
01723   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
01724 
01725   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
01726     // General Dynamic and Local Dynamic TLS Model.
01727     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
01728                                                       : MipsII::MO_TLSGD;
01729 
01730     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
01731     SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
01732                                    getGlobalReg(DAG, PtrVT), TGA);
01733     unsigned PtrSize = PtrVT.getSizeInBits();
01734     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
01735 
01736     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
01737 
01738     ArgListTy Args;
01739     ArgListEntry Entry;
01740     Entry.Node = Argument;
01741     Entry.Ty = PtrTy;
01742     Args.push_back(Entry);
01743 
01744     TargetLowering::CallLoweringInfo CLI(DAG);
01745     CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
01746       .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
01747     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
01748 
01749     SDValue Ret = CallResult.first;
01750 
01751     if (model != TLSModel::LocalDynamic)
01752       return Ret;
01753 
01754     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01755                                                MipsII::MO_DTPREL_HI);
01756     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
01757     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01758                                                MipsII::MO_DTPREL_LO);
01759     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
01760     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
01761     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
01762   }
01763 
01764   SDValue Offset;
01765   if (model == TLSModel::InitialExec) {
01766     // Initial Exec TLS Model
01767     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01768                                              MipsII::MO_GOTTPREL);
01769     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
01770                       TGA);
01771     Offset = DAG.getLoad(PtrVT, DL,
01772                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
01773                          false, false, false, 0);
01774   } else {
01775     // Local Exec TLS Model
01776     assert(model == TLSModel::LocalExec);
01777     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01778                                                MipsII::MO_TPREL_HI);
01779     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
01780                                                MipsII::MO_TPREL_LO);
01781     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
01782     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
01783     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
01784   }
01785 
01786   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
01787   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
01788 }
01789 
01790 SDValue MipsTargetLowering::
01791 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
01792 {
01793   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
01794   EVT Ty = Op.getValueType();
01795 
01796   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
01797     return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
01798 
01799   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
01800 }
01801 
01802 SDValue MipsTargetLowering::
01803 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
01804 {
01805   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
01806   EVT Ty = Op.getValueType();
01807 
01808   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
01809     const MipsTargetObjectFile *TLOF =
01810         static_cast<const MipsTargetObjectFile *>(
01811             getTargetMachine().getObjFileLowering());
01812 
01813     if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
01814                                        getTargetMachine()))
01815       // %gp_rel relocation
01816       return getAddrGPRel(N, SDLoc(N), Ty, DAG);
01817 
01818     return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
01819   }
01820 
01821   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
01822 }
01823 
01824 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
01825   MachineFunction &MF = DAG.getMachineFunction();
01826   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
01827 
01828   SDLoc DL(Op);
01829   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
01830                                  getPointerTy(MF.getDataLayout()));
01831 
01832   // vastart just stores the address of the VarArgsFrameIndex slot into the
01833   // memory location argument.
01834   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
01835   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
01836                       MachinePointerInfo(SV), false, false, 0);
01837 }
01838 
01839 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
01840   SDNode *Node = Op.getNode();
01841   EVT VT = Node->getValueType(0);
01842   SDValue Chain = Node->getOperand(0);
01843   SDValue VAListPtr = Node->getOperand(1);
01844   unsigned Align = Node->getConstantOperandVal(3);
01845   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
01846   SDLoc DL(Node);
01847   unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
01848 
01849   SDValue VAListLoad =
01850       DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, VAListPtr,
01851                   MachinePointerInfo(SV), false, false, false, 0);
01852   SDValue VAList = VAListLoad;
01853 
01854   // Re-align the pointer if necessary.
01855   // It should only ever be necessary for 64-bit types on O32 since the minimum
01856   // argument alignment is the same as the maximum type alignment for N32/N64.
01857   //
01858   // FIXME: We currently align too often. The code generator doesn't notice
01859   //        when the pointer is still aligned from the last va_arg (or pair of
01860   //        va_args for the i64 on O32 case).
01861   if (Align > getMinStackArgumentAlignment()) {
01862     assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
01863 
01864     VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
01865                          DAG.getConstant(Align - 1, DL, VAList.getValueType()));
01866 
01867     VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
01868                          DAG.getConstant(-(int64_t)Align, DL,
01869                                          VAList.getValueType()));
01870   }
01871 
01872   // Increment the pointer, VAList, to the next vaarg.
01873   auto &TD = DAG.getDataLayout();
01874   unsigned ArgSizeInBytes =
01875       TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
01876   SDValue Tmp3 =
01877       DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
01878                   DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
01879                                   DL, VAList.getValueType()));
01880   // Store the incremented VAList to the legalized pointer
01881   Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
01882                       MachinePointerInfo(SV), false, false, 0);
01883 
01884   // In big-endian mode we must adjust the pointer when the load size is smaller
01885   // than the argument slot size. We must also reduce the known alignment to
01886   // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
01887   // the correct half of the slot, and reduce the alignment from 8 (slot
01888   // alignment) down to 4 (type alignment).
01889   if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
01890     unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
01891     VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
01892                          DAG.getIntPtrConstant(Adjustment, DL));
01893   }
01894   // Load the actual argument out of the pointer VAList
01895   return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
01896                      false, 0);
01897 }
01898 
01899 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
01900                                 bool HasExtractInsert) {
01901   EVT TyX = Op.getOperand(0).getValueType();
01902   EVT TyY = Op.getOperand(1).getValueType();
01903   SDLoc DL(Op);
01904   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
01905   SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
01906   SDValue Res;
01907 
01908   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
01909   // to i32.
01910   SDValue X = (TyX == MVT::f32) ?
01911     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
01912     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
01913                 Const1);
01914   SDValue Y = (TyY == MVT::f32) ?
01915     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
01916     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
01917                 Const1);
01918 
01919   if (HasExtractInsert) {
01920     // ext  E, Y, 31, 1  ; extract bit31 of Y
01921     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
01922     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
01923     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
01924   } else {
01925     // sll SllX, X, 1
01926     // srl SrlX, SllX, 1
01927     // srl SrlY, Y, 31
01928     // sll SllY, SrlX, 31
01929     // or  Or, SrlX, SllY
01930     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
01931     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
01932     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
01933     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
01934     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
01935   }
01936 
01937   if (TyX == MVT::f32)
01938     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
01939 
01940   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
01941                              Op.getOperand(0),
01942                              DAG.getConstant(0, DL, MVT::i32));
01943   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
01944 }
01945 
01946 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
01947                                 bool HasExtractInsert) {
01948   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
01949   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
01950   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
01951   SDLoc DL(Op);
01952   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
01953 
01954   // Bitcast to integer nodes.
01955   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
01956   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
01957 
01958   if (HasExtractInsert) {
01959     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
01960     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
01961     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
01962                             DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
01963 
01964     if (WidthX > WidthY)
01965       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
01966     else if (WidthY > WidthX)
01967       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
01968 
01969     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
01970                             DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
01971                             X);
01972     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
01973   }
01974 
01975   // (d)sll SllX, X, 1
01976   // (d)srl SrlX, SllX, 1
01977   // (d)srl SrlY, Y, width(Y)-1
01978   // (d)sll SllY, SrlX, width(Y)-1
01979   // or     Or, SrlX, SllY
01980   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
01981   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
01982   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
01983                              DAG.getConstant(WidthY - 1, DL, MVT::i32));
01984 
01985   if (WidthX > WidthY)
01986     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
01987   else if (WidthY > WidthX)
01988     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
01989 
01990   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
01991                              DAG.getConstant(WidthX - 1, DL, MVT::i32));
01992   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
01993   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
01994 }
01995 
01996 SDValue
01997 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
01998   if (Subtarget.isGP64bit())
01999     return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
02000 
02001   return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
02002 }
02003 
02004 SDValue MipsTargetLowering::
02005 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
02006   // check the depth
02007   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
02008          "Frame address can only be determined for current frame.");
02009 
02010   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
02011   MFI->setFrameAddressIsTaken(true);
02012   EVT VT = Op.getValueType();
02013   SDLoc DL(Op);
02014   SDValue FrameAddr = DAG.getCopyFromReg(
02015       DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
02016   return FrameAddr;
02017 }
02018 
02019 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
02020                                             SelectionDAG &DAG) const {
02021   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
02022     return SDValue();
02023 
02024   // check the depth
02025   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
02026          "Return address can be determined only for current frame.");
02027 
02028   MachineFunction &MF = DAG.getMachineFunction();
02029   MachineFrameInfo *MFI = MF.getFrameInfo();
02030   MVT VT = Op.getSimpleValueType();
02031   unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
02032   MFI->setReturnAddressIsTaken(true);
02033 
02034   // Return RA, which contains the return address. Mark it an implicit live-in.
02035   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
02036   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
02037 }
02038 
02039 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
02040 // generated from __builtin_eh_return (offset, handler)
02041 // The effect of this is to adjust the stack pointer by "offset"
02042 // and then branch to "handler".
02043 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
02044                                                                      const {
02045   MachineFunction &MF = DAG.getMachineFunction();
02046   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
02047 
02048   MipsFI->setCallsEhReturn();
02049   SDValue Chain     = Op.getOperand(0);
02050   SDValue Offset    = Op.getOperand(1);
02051   SDValue Handler   = Op.getOperand(2);
02052   SDLoc DL(Op);
02053   EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
02054 
02055   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
02056   // EH_RETURN nodes, so that instructions are emitted back-to-back.
02057   unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
02058   unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
02059   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
02060   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
02061   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
02062                      DAG.getRegister(OffsetReg, Ty),
02063                      DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
02064                      Chain.getValue(1));
02065 }
02066 
02067 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
02068                                               SelectionDAG &DAG) const {
02069   // FIXME: Need pseudo-fence for 'singlethread' fences
02070   // FIXME: Set SType for weaker fences where supported/appropriate.
02071   unsigned SType = 0;
02072   SDLoc DL(Op);
02073   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
02074                      DAG.getConstant(SType, DL, MVT::i32));
02075 }
02076 
02077 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
02078                                                 SelectionDAG &DAG) const {
02079   SDLoc DL(Op);
02080   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
02081 
02082   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
02083   SDValue Shamt = Op.getOperand(2);
02084   // if shamt < (VT.bits):
02085   //  lo = (shl lo, shamt)
02086   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
02087   // else:
02088   //  lo = 0
02089   //  hi = (shl lo, shamt[4:0])
02090   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
02091                             DAG.getConstant(-1, DL, MVT::i32));
02092   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
02093                                       DAG.getConstant(1, DL, VT));
02094   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
02095   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
02096   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
02097   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
02098   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
02099                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
02100   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
02101                    DAG.getConstant(0, DL, VT), ShiftLeftLo);
02102   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
02103 
02104   SDValue Ops[2] = {Lo, Hi};
02105   return DAG.getMergeValues(Ops, DL);
02106 }
02107 
02108 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
02109                                                  bool IsSRA) const {
02110   SDLoc DL(Op);
02111   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
02112   SDValue Shamt = Op.getOperand(2);
02113   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
02114 
02115   // if shamt < (VT.bits):
02116   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
02117   //  if isSRA:
02118   //    hi = (sra hi, shamt)
02119   //  else:
02120   //    hi = (srl hi, shamt)
02121   // else:
02122   //  if isSRA:
02123   //   lo = (sra hi, shamt[4:0])
02124   //   hi = (sra hi, 31)
02125   //  else:
02126   //   lo = (srl hi, shamt[4:0])
02127   //   hi = 0
02128   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
02129                             DAG.getConstant(-1, DL, MVT::i32));
02130   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
02131                                      DAG.getConstant(1, DL, VT));
02132   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
02133   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
02134   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
02135   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
02136                                      DL, VT, Hi, Shamt);
02137   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
02138                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
02139   SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
02140                             DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
02141   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
02142   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
02143                    IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
02144 
02145   SDValue Ops[2] = {Lo, Hi};
02146   return DAG.getMergeValues(Ops, DL);
02147 }
02148 
02149 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
02150                             SDValue Chain, SDValue Src, unsigned Offset) {
02151   SDValue Ptr = LD->getBasePtr();
02152   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
02153   EVT BasePtrVT = Ptr.getValueType();
02154   SDLoc DL(LD);
02155   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
02156 
02157   if (Offset)
02158     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
02159                       DAG.getConstant(Offset, DL, BasePtrVT));
02160 
02161   SDValue Ops[] = { Chain, Ptr, Src };
02162   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
02163                                  LD->getMemOperand());
02164 }
02165 
02166 // Expand an unaligned 32 or 64-bit integer load node.
02167 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
02168   LoadSDNode *LD = cast<LoadSDNode>(Op);
02169   EVT MemVT = LD->getMemoryVT();
02170 
02171   if (Subtarget.systemSupportsUnalignedAccess())
02172     return Op;
02173 
02174   // Return if load is aligned or if MemVT is neither i32 nor i64.
02175   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
02176       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
02177     return SDValue();
02178 
02179   bool IsLittle = Subtarget.isLittle();
02180   EVT VT = Op.getValueType();
02181   ISD::LoadExtType ExtType = LD->getExtensionType();
02182   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
02183 
02184   assert((VT == MVT::i32) || (VT == MVT::i64));
02185 
02186   // Expand
02187   //  (set dst, (i64 (load baseptr)))
02188   // to
02189   //  (set tmp, (ldl (add baseptr, 7), undef))
02190   //  (set dst, (ldr baseptr, tmp))
02191   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
02192     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
02193                                IsLittle ? 7 : 0);
02194     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
02195                         IsLittle ? 0 : 7);
02196   }
02197 
02198   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
02199                              IsLittle ? 3 : 0);
02200   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
02201                              IsLittle ? 0 : 3);
02202 
02203   // Expand
02204   //  (set dst, (i32 (load baseptr))) or
02205   //  (set dst, (i64 (sextload baseptr))) or
02206   //  (set dst, (i64 (extload baseptr)))
02207   // to
02208   //  (set tmp, (lwl (add baseptr, 3), undef))
02209   //  (set dst, (lwr baseptr, tmp))
02210   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
02211       (ExtType == ISD::EXTLOAD))
02212     return LWR;
02213 
02214   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
02215 
02216   // Expand
02217   //  (set dst, (i64 (zextload baseptr)))
02218   // to
02219   //  (set tmp0, (lwl (add baseptr, 3), undef))
02220   //  (set tmp1, (lwr baseptr, tmp0))
02221   //  (set tmp2, (shl tmp1, 32))
02222   //  (set dst, (srl tmp2, 32))
02223   SDLoc DL(LD);
02224   SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
02225   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
02226   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
02227   SDValue Ops[] = { SRL, LWR.getValue(1) };
02228   return DAG.getMergeValues(Ops, DL);
02229 }
02230 
02231 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
02232                              SDValue Chain, unsigned Offset) {
02233   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
02234   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
02235   SDLoc DL(SD);
02236   SDVTList VTList = DAG.getVTList(MVT::Other);
02237 
02238   if (Offset)
02239     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
02240                       DAG.getConstant(Offset, DL, BasePtrVT));
02241 
02242   SDValue Ops[] = { Chain, Value, Ptr };
02243   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
02244                                  SD->getMemOperand());
02245 }
02246 
02247 // Expand an unaligned 32 or 64-bit integer store node.
02248 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
02249                                       bool IsLittle) {
02250   SDValue Value = SD->getValue(), Chain = SD->getChain();
02251   EVT VT = Value.getValueType();
02252 
02253   // Expand
02254   //  (store val, baseptr) or
02255   //  (truncstore val, baseptr)
02256   // to
02257   //  (swl val, (add baseptr, 3))
02258   //  (swr val, baseptr)
02259   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
02260     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
02261                                 IsLittle ? 3 : 0);
02262     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
02263   }
02264 
02265   assert(VT == MVT::i64);
02266 
02267   // Expand
02268   //  (store val, baseptr)
02269   // to
02270   //  (sdl val, (add baseptr, 7))
02271   //  (sdr val, baseptr)
02272   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
02273   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
02274 }
02275 
02276 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
02277 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
02278   SDValue Val = SD->getValue();
02279 
02280   if (Val.getOpcode() != ISD::FP_TO_SINT)
02281     return SDValue();
02282 
02283   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
02284   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
02285                            Val.getOperand(0));
02286 
02287   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
02288                       SD->getPointerInfo(), SD->isVolatile(),
02289                       SD->isNonTemporal(), SD->getAlignment());
02290 }
02291 
02292 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
02293   StoreSDNode *SD = cast<StoreSDNode>(Op);
02294   EVT MemVT = SD->getMemoryVT();
02295 
02296   // Lower unaligned integer stores.
02297   if (!Subtarget.systemSupportsUnalignedAccess() &&
02298       (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
02299       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
02300     return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
02301 
02302   return lowerFP_TO_SINT_STORE(SD, DAG);
02303 }
02304 
02305 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
02306   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
02307       || cast<ConstantSDNode>
02308         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
02309       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
02310     return SDValue();
02311 
02312   // The pattern
02313   //   (add (frameaddr 0), (frame_to_args_offset))
02314   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
02315   //   (add FrameObject, 0)
02316   // where FrameObject is a fixed StackObject with offset 0 which points to
02317   // the old stack pointer.
02318   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
02319   EVT ValTy = Op->getValueType(0);
02320   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
02321   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
02322   SDLoc DL(Op);
02323   return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
02324                      DAG.getConstant(0, DL, ValTy));
02325 }
02326 
02327 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
02328                                             SelectionDAG &DAG) const {
02329   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
02330   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
02331                               Op.getOperand(0));
02332   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
02333 }
02334 
02335 //===----------------------------------------------------------------------===//
02336 //                      Calling Convention Implementation
02337 //===----------------------------------------------------------------------===//
02338 
02339 //===----------------------------------------------------------------------===//
02340 // TODO: Implement a generic logic using tblgen that can support this.
02341 // Mips O32 ABI rules:
02342 // ---
02343 // i32 - Passed in A0, A1, A2, A3 and stack
02344 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
02345 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
02346 // f64 - Only passed in two aliased f32 registers if no int reg has been used
02347 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
02348 //       not used, it must be shadowed. If only A3 is available, shadow it and
02349 //       go to stack.
02350 //
02351 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
02352 //===----------------------------------------------------------------------===//
02353 
02354 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
02355                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
02356                        CCState &State, ArrayRef<MCPhysReg> F64Regs) {
02357   const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
02358       State.getMachineFunction().getSubtarget());
02359 
02360   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
02361   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
02362 
02363   // Do not process byval args here.
02364   if (ArgFlags.isByVal())
02365     return true;
02366 
02367   // Promote i8 and i16
02368   if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
02369     if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
02370       LocVT = MVT::i32;
02371       if (ArgFlags.isSExt())
02372         LocInfo = CCValAssign::SExtUpper;
02373       else if (ArgFlags.isZExt())
02374         LocInfo = CCValAssign::ZExtUpper;
02375       else
02376         LocInfo = CCValAssign::AExtUpper;
02377     }
02378   }
02379 
02380   // Promote i8 and i16
02381   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
02382     LocVT = MVT::i32;
02383     if (ArgFlags.isSExt())
02384       LocInfo = CCValAssign::SExt;
02385     else if (ArgFlags.isZExt())
02386       LocInfo = CCValAssign::ZExt;
02387     else
02388       LocInfo = CCValAssign::AExt;
02389   }
02390 
02391   unsigned Reg;
02392 
02393   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
02394   // is true: function is vararg, argument is 3rd or higher, there is previous
02395   // argument which is not f32 or f64.
02396   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
02397                                 State.getFirstUnallocated(F32Regs) != ValNo;
02398   unsigned OrigAlign = ArgFlags.getOrigAlign();
02399   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
02400 
02401   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
02402     Reg = State.AllocateReg(IntRegs);
02403     // If this is the first part of an i64 arg,
02404     // the allocated register must be either A0 or A2.
02405     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
02406       Reg = State.AllocateReg(IntRegs);
02407     LocVT = MVT::i32;
02408   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
02409     // Allocate int register and shadow next int register. If first
02410     // available register is Mips::A1 or Mips::A3, shadow it too.
02411     Reg = State.AllocateReg(IntRegs);
02412     if (Reg == Mips::A1 || Reg == Mips::A3)
02413       Reg = State.AllocateReg(IntRegs);
02414     State.AllocateReg(IntRegs);
02415     LocVT = MVT::i32;
02416   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
02417     // we are guaranteed to find an available float register
02418     if (ValVT == MVT::f32) {
02419       Reg = State.AllocateReg(F32Regs);
02420       // Shadow int register
02421       State.AllocateReg(IntRegs);
02422     } else {
02423       Reg = State.AllocateReg(F64Regs);
02424       // Shadow int registers
02425       unsigned Reg2 = State.AllocateReg(IntRegs);
02426       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
02427         State.AllocateReg(IntRegs);
02428       State.AllocateReg(IntRegs);
02429     }
02430   } else
02431     llvm_unreachable("Cannot handle this ValVT.");
02432 
02433   if (!Reg) {
02434     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
02435                                           OrigAlign);
02436     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
02437   } else
02438     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
02439 
02440   return false;
02441 }
02442 
02443 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
02444                             MVT LocVT, CCValAssign::LocInfo LocInfo,
02445                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
02446   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
02447 
02448   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
02449 }
02450 
02451 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
02452                             MVT LocVT, CCValAssign::LocInfo LocInfo,
02453                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
02454   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
02455 
02456   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
02457 }
02458 
02459 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
02460                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
02461                        CCState &State) LLVM_ATTRIBUTE_UNUSED;
02462 
02463 #include "MipsGenCallingConv.inc"
02464 
02465 //===----------------------------------------------------------------------===//
02466 //                  Call Calling Convention Implementation
02467 //===----------------------------------------------------------------------===//
02468 
02469 // Return next O32 integer argument register.
02470 static unsigned getNextIntArgReg(unsigned Reg) {
02471   assert((Reg == Mips::A0) || (Reg == Mips::A2));
02472   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
02473 }
02474 
02475 SDValue
02476 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
02477                                    SDValue Chain, SDValue Arg, SDLoc DL,
02478                                    bool IsTailCall, SelectionDAG &DAG) const {
02479   if (!IsTailCall) {
02480     SDValue PtrOff =
02481         DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
02482                     DAG.getIntPtrConstant(Offset, DL));
02483     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
02484                         false, 0);
02485   }
02486 
02487   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
02488   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
02489   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
02490   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
02491                       /*isVolatile=*/ true, false, 0);
02492 }
02493 
02494 void MipsTargetLowering::
02495 getOpndList(SmallVectorImpl<SDValue> &Ops,
02496             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
02497             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
02498             bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
02499             SDValue Chain) const {
02500   // Insert node "GP copy globalreg" before call to function.
02501   //
02502   // R_MIPS_CALL* operators (emitted when non-internal functions are called
02503   // in PIC mode) allow symbols to be resolved via lazy binding.
02504   // The lazy binding stub requires GP to point to the GOT.
02505   // Note that we don't need GP to point to the GOT for indirect calls
02506   // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
02507   // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
02508   // used for the function (that is, Mips linker doesn't generate lazy binding
02509   // stub for a function whose address is taken in the program).
02510   if (IsPICCall && !InternalLinkage && IsCallReloc) {
02511     unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
02512     EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
02513     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
02514   }
02515 
02516   // Build a sequence of copy-to-reg nodes chained together with token
02517   // chain and flag operands which copy the outgoing args into registers.
02518   // The InFlag in necessary since all emitted instructions must be
02519   // stuck together.
02520   SDValue InFlag;
02521 
02522   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
02523     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
02524                                  RegsToPass[i].second, InFlag);
02525     InFlag = Chain.getValue(1);
02526   }
02527 
02528   // Add argument registers to the end of the list so that they are
02529   // known live into the call.
02530   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
02531     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
02532                                       RegsToPass[i].second.getValueType()));
02533 
02534   // Add a register mask operand representing the call-preserved registers.
02535   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
02536   const uint32_t *Mask =
02537       TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
02538   assert(Mask && "Missing call preserved mask for calling convention");
02539   if (Subtarget.inMips16HardFloat()) {
02540     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
02541       llvm::StringRef Sym = G->getGlobal()->getName();
02542       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
02543       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
02544         Mask = MipsRegisterInfo::getMips16RetHelperMask();
02545       }
02546     }
02547   }
02548   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
02549 
02550   if (InFlag.getNode())
02551     Ops.push_back(InFlag);
02552 }
02553 
02554 /// LowerCall - functions arguments are copied from virtual regs to
02555 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
02556 SDValue
02557 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
02558                               SmallVectorImpl<SDValue> &InVals) const {
02559   SelectionDAG &DAG                     = CLI.DAG;
02560   SDLoc DL                              = CLI.DL;
02561   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
02562   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
02563   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
02564   SDValue Chain                         = CLI.Chain;
02565   SDValue Callee                        = CLI.Callee;
02566   bool &IsTailCall                      = CLI.IsTailCall;
02567   CallingConv::ID CallConv              = CLI.CallConv;
02568   bool IsVarArg                         = CLI.IsVarArg;
02569 
02570   MachineFunction &MF = DAG.getMachineFunction();
02571   MachineFrameInfo *MFI = MF.getFrameInfo();
02572   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
02573   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
02574   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
02575 
02576   // Analyze operands of the call, assigning locations to each operand.
02577   SmallVector<CCValAssign, 16> ArgLocs;
02578   MipsCCState CCInfo(
02579       CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
02580       MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
02581 
02582   // Allocate the reserved argument area. It seems strange to do this from the
02583   // caller side but removing it breaks the frame size calculation.
02584   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
02585 
02586   CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
02587 
02588   // Get a count of how many bytes are to be pushed on the stack.
02589   unsigned NextStackOffset = CCInfo.getNextStackOffset();
02590 
02591   // Check if it's really possible to do a tail call.
02592   if (IsTailCall)
02593     IsTailCall = isEligibleForTailCallOptimization(
02594         CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
02595 
02596   if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
02597     report_fatal_error("failed to perform tail call elimination on a call "
02598                        "site marked musttail");
02599 
02600   if (IsTailCall)
02601     ++NumTailCalls;
02602 
02603   // Chain is the output chain of the last Load/Store or CopyToReg node.
02604   // ByValChain is the output chain of the last Memcpy node created for copying
02605   // byval arguments to the stack.
02606   unsigned StackAlignment = TFL->getStackAlignment();
02607   NextStackOffset = alignTo(NextStackOffset, StackAlignment);
02608   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
02609 
02610   if (!IsTailCall)
02611     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
02612 
02613   SDValue StackPtr =
02614       DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
02615                          getPointerTy(DAG.getDataLayout()));
02616 
02617   // With EABI is it possible to have 16 args on registers.
02618   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
02619   SmallVector<SDValue, 8> MemOpChains;
02620 
02621   CCInfo.rewindByValRegsInfo();
02622 
02623   // Walk the register/memloc assignments, inserting copies/loads.
02624   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02625     SDValue Arg = OutVals[i];
02626     CCValAssign &VA = ArgLocs[i];
02627     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
02628     ISD::ArgFlagsTy Flags = Outs[i].Flags;
02629     bool UseUpperBits = false;
02630 
02631     // ByVal Arg.
02632     if (Flags.isByVal()) {
02633       unsigned FirstByValReg, LastByValReg;
02634       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
02635       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
02636 
02637       assert(Flags.getByValSize() &&
02638              "ByVal args of size 0 should have been ignored by front-end.");
02639       assert(ByValIdx < CCInfo.getInRegsParamsCount());
02640       assert(!IsTailCall &&
02641              "Do not tail-call optimize if there is a byval argument.");
02642       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
02643                    FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
02644                    VA);
02645       CCInfo.nextInRegsParam();
02646       continue;
02647     }
02648 
02649     // Promote the value if needed.
02650     switch (VA.getLocInfo()) {
02651     default:
02652       llvm_unreachable("Unknown loc info!");
02653     case CCValAssign::Full:
02654       if (VA.isRegLoc()) {
02655         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
02656             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
02657             (ValVT == MVT::i64 && LocVT == MVT::f64))
02658           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
02659         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
02660           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
02661                                    Arg, DAG.getConstant(0, DL, MVT::i32));
02662           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
02663                                    Arg, DAG.getConstant(1, DL, MVT::i32));
02664           if (!Subtarget.isLittle())
02665             std::swap(Lo, Hi);
02666           unsigned LocRegLo = VA.getLocReg();
02667           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
02668           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
02669           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
02670           continue;
02671         }
02672       }
02673       break;
02674     case CCValAssign::BCvt:
02675       Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
02676       break;
02677     case CCValAssign::SExtUpper:
02678       UseUpperBits = true;
02679       // Fallthrough
02680     case CCValAssign::SExt:
02681       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
02682       break;
02683     case CCValAssign::ZExtUpper:
02684       UseUpperBits = true;
02685       // Fallthrough
02686     case CCValAssign::ZExt:
02687       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
02688       break;
02689     case CCValAssign::AExtUpper:
02690       UseUpperBits = true;
02691       // Fallthrough
02692     case CCValAssign::AExt:
02693       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
02694       break;
02695     }
02696 
02697     if (UseUpperBits) {
02698       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
02699       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
02700       Arg = DAG.getNode(
02701           ISD::SHL, DL, VA.getLocVT(), Arg,
02702           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
02703     }
02704 
02705     // Arguments that can be passed on register must be kept at
02706     // RegsToPass vector
02707     if (VA.isRegLoc()) {
02708       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
02709       continue;
02710     }
02711 
02712     // Register can't get to this point...
02713     assert(VA.isMemLoc());
02714 
02715     // emit ISD::STORE whichs stores the
02716     // parameter value to a stack Location
02717     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
02718                                          Chain, Arg, DL, IsTailCall, DAG));
02719   }
02720 
02721   // Transform all store nodes into one single node because all store
02722   // nodes are independent of each other.
02723   if (!MemOpChains.empty())
02724     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
02725 
02726   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
02727   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
02728   // node so that legalize doesn't hack it.
02729   bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
02730                                            // jalr $25
02731   bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
02732   SDValue CalleeLo;
02733   EVT Ty = Callee.getValueType();
02734 
02735   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
02736     if (IsPICCall) {
02737       const GlobalValue *Val = G->getGlobal();
02738       InternalLinkage = Val->hasInternalLinkage();
02739 
02740       if (InternalLinkage)
02741         Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
02742       else if (LargeGOT) {
02743         Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
02744                                        MipsII::MO_CALL_LO16, Chain,
02745                                        FuncInfo->callPtrInfo(Val));
02746         IsCallReloc = true;
02747       } else {
02748         Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
02749                                FuncInfo->callPtrInfo(Val));
02750         IsCallReloc = true;
02751       }
02752     } else
02753       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
02754                                           getPointerTy(DAG.getDataLayout()), 0,
02755                                           MipsII::MO_NO_FLAG);
02756     GlobalOrExternal = true;
02757   }
02758   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
02759     const char *Sym = S->getSymbol();
02760 
02761     if (!ABI.IsN64() && !IsPIC) // !N64 && static
02762       Callee = DAG.getTargetExternalSymbol(
02763           Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
02764     else if (LargeGOT) {
02765       Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
02766                                      MipsII::MO_CALL_LO16, Chain,
02767                                      FuncInfo->callPtrInfo(Sym));
02768       IsCallReloc = true;
02769     } else { // N64 || PIC
02770       Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
02771                              FuncInfo->callPtrInfo(Sym));
02772       IsCallReloc = true;
02773     }
02774 
02775     GlobalOrExternal = true;
02776   }
02777 
02778   SmallVector<SDValue, 8> Ops(1, Chain);
02779   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
02780 
02781   getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
02782               IsCallReloc, CLI, Callee, Chain);
02783 
02784   if (IsTailCall)
02785     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
02786 
02787   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
02788   SDValue InFlag = Chain.getValue(1);
02789 
02790   // Create the CALLSEQ_END node.
02791   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
02792                              DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
02793   InFlag = Chain.getValue(1);
02794 
02795   // Handle result values, copying them out of physregs into vregs that we
02796   // return.
02797   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
02798                          InVals, CLI);
02799 }
02800 
02801 /// LowerCallResult - Lower the result values of a call into the
02802 /// appropriate copies out of appropriate physical registers.
02803 SDValue MipsTargetLowering::LowerCallResult(
02804     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
02805     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
02806     SmallVectorImpl<SDValue> &InVals,
02807     TargetLowering::CallLoweringInfo &CLI) const {
02808   // Assign locations to each value returned by this call.
02809   SmallVector<CCValAssign, 16> RVLocs;
02810   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
02811                      *DAG.getContext());
02812   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
02813 
02814   // Copy all of the result registers out of their specified physreg.
02815   for (unsigned i = 0; i != RVLocs.size(); ++i) {
02816     CCValAssign &VA = RVLocs[i];
02817     assert(VA.isRegLoc() && "Can only return in registers!");
02818 
02819     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
02820                                      RVLocs[i].getLocVT(), InFlag);
02821     Chain = Val.getValue(1);
02822     InFlag = Val.getValue(2);
02823 
02824     if (VA.isUpperBitsInLoc()) {
02825       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
02826       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
02827       unsigned Shift =
02828           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
02829       Val = DAG.getNode(
02830           Shift, DL, VA.getLocVT(), Val,
02831           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
02832     }
02833 
02834     switch (VA.getLocInfo()) {
02835     default:
02836       llvm_unreachable("Unknown loc info!");
02837     case CCValAssign::Full:
02838       break;
02839     case CCValAssign::BCvt:
02840       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
02841       break;
02842     case CCValAssign::AExt:
02843     case CCValAssign::AExtUpper:
02844       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
02845       break;
02846     case CCValAssign::ZExt:
02847     case CCValAssign::ZExtUpper:
02848       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
02849                         DAG.getValueType(VA.getValVT()));
02850       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
02851       break;
02852     case CCValAssign::SExt:
02853     case CCValAssign::SExtUpper:
02854       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
02855                         DAG.getValueType(VA.getValVT()));
02856       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
02857       break;
02858     }
02859 
02860     InVals.push_back(Val);
02861   }
02862 
02863   return Chain;
02864 }
02865 
02866 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
02867                                       EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
02868   MVT LocVT = VA.getLocVT();
02869   EVT ValVT = VA.getValVT();
02870 
02871   // Shift into the upper bits if necessary.
02872   switch (VA.getLocInfo()) {
02873   default:
02874     break;
02875   case CCValAssign::AExtUpper:
02876   case CCValAssign::SExtUpper:
02877   case CCValAssign::ZExtUpper: {
02878     unsigned ValSizeInBits = ArgVT.getSizeInBits();
02879     unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
02880     unsigned Opcode =
02881         VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
02882     Val = DAG.getNode(
02883         Opcode, DL, VA.getLocVT(), Val,
02884         DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
02885     break;
02886   }
02887   }
02888 
02889   // If this is an value smaller than the argument slot size (32-bit for O32,
02890   // 64-bit for N32/N64), it has been promoted in some way to the argument slot
02891   // size. Extract the value and insert any appropriate assertions regarding
02892   // sign/zero extension.
02893   switch (VA.getLocInfo()) {
02894   default:
02895     llvm_unreachable("Unknown loc info!");
02896   case CCValAssign::Full:
02897     break;
02898   case CCValAssign::AExtUpper:
02899   case CCValAssign::AExt:
02900     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
02901     break;
02902   case CCValAssign::SExtUpper:
02903   case CCValAssign::SExt:
02904     Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
02905     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
02906     break;
02907   case CCValAssign::ZExtUpper:
02908   case CCValAssign::ZExt:
02909     Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
02910     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
02911     break;
02912   case CCValAssign::BCvt:
02913     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
02914     break;
02915   }
02916 
02917   return Val;
02918 }
02919 
02920 //===----------------------------------------------------------------------===//
02921 //             Formal Arguments Calling Convention Implementation
02922 //===----------------------------------------------------------------------===//
02923 /// LowerFormalArguments - transform physical registers into virtual registers
02924 /// and generate load operations for arguments places on the stack.
02925 SDValue
02926 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
02927                                          CallingConv::ID CallConv,
02928                                          bool IsVarArg,
02929                                       const SmallVectorImpl<ISD::InputArg> &Ins,
02930                                          SDLoc DL, SelectionDAG &DAG,
02931                                          SmallVectorImpl<SDValue> &InVals)
02932                                           const {
02933   MachineFunction &MF = DAG.getMachineFunction();
02934   MachineFrameInfo *MFI = MF.getFrameInfo();
02935   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
02936 
02937   MipsFI->setVarArgsFrameIndex(0);
02938 
02939   // Used with vargs to acumulate store chains.
02940   std::vector<SDValue> OutChains;
02941 
02942   // Assign locations to all of the incoming arguments.
02943   SmallVector<CCValAssign, 16> ArgLocs;
02944   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
02945                      *DAG.getContext());
02946   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
02947   const Function *Func = DAG.getMachineFunction().getFunction();
02948   Function::const_arg_iterator FuncArg = Func->arg_begin();
02949 
02950   if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
02951     report_fatal_error(
02952         "Functions with the interrupt attribute cannot have arguments!");
02953 
02954   CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
02955   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
02956                            CCInfo.getInRegsParamsCount() > 0);
02957 
02958   unsigned CurArgIdx = 0;
02959   CCInfo.rewindByValRegsInfo();
02960 
02961   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02962     CCValAssign &VA = ArgLocs[i];
02963     if (Ins[i].isOrigArg()) {
02964       std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
02965       CurArgIdx = Ins[i].getOrigArgIndex();
02966     }
02967     EVT ValVT = VA.getValVT();
02968     ISD::ArgFlagsTy Flags = Ins[i].Flags;
02969     bool IsRegLoc = VA.isRegLoc();
02970 
02971     if (Flags.isByVal()) {
02972       assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
02973       unsigned FirstByValReg, LastByValReg;
02974       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
02975       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
02976 
02977       assert(Flags.getByValSize() &&
02978              "ByVal args of size 0 should have been ignored by front-end.");
02979       assert(ByValIdx < CCInfo.getInRegsParamsCount());
02980       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
02981                     FirstByValReg, LastByValReg, VA, CCInfo);
02982       CCInfo.nextInRegsParam();
02983       continue;
02984     }
02985 
02986     // Arguments stored on registers
02987     if (IsRegLoc) {
02988       MVT RegVT = VA.getLocVT();
02989       unsigned ArgReg = VA.getLocReg();
02990       const TargetRegisterClass *RC = getRegClassFor(RegVT);
02991 
02992       // Transform the arguments stored on
02993       // physical registers into virtual ones
02994       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
02995       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
02996 
02997       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
02998 
02999       // Handle floating point arguments passed in integer registers and
03000       // long double arguments passed in floating point registers.
03001       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
03002           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
03003           (RegVT == MVT::f64 && ValVT == MVT::i64))
03004         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
03005       else if (ABI.IsO32() && RegVT == MVT::i32 &&
03006                ValVT == MVT::f64) {
03007         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
03008                                   getNextIntArgReg(ArgReg), RC);
03009         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
03010         if (!Subtarget.isLittle())
03011           std::swap(ArgValue, ArgValue2);
03012         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
03013                                ArgValue, ArgValue2);
03014       }
03015 
03016       InVals.push_back(ArgValue);
03017     } else { // VA.isRegLoc()
03018       MVT LocVT = VA.getLocVT();
03019 
03020       if (ABI.IsO32()) {
03021         // We ought to be able to use LocVT directly but O32 sets it to i32
03022         // when allocating floating point values to integer registers.
03023         // This shouldn't influence how we load the value into registers unless
03024         // we are targeting softfloat.
03025         if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
03026           LocVT = VA.getValVT();
03027       }
03028 
03029       // sanity check
03030       assert(VA.isMemLoc());
03031 
03032       // The stack pointer offset is relative to the caller stack frame.
03033       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
03034                                       VA.getLocMemOffset(), true);
03035 
03036       // Create load nodes to retrieve arguments from the stack
03037       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
03038       SDValue ArgValue = DAG.getLoad(
03039           LocVT, DL, Chain, FIN,
03040           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
03041           false, false, false, 0);
03042       OutChains.push_back(ArgValue.getValue(1));
03043 
03044       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
03045 
03046       InVals.push_back(ArgValue);
03047     }
03048   }
03049 
03050   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
03051     // The mips ABIs for returning structs by value requires that we copy
03052     // the sret argument into $v0 for the return. Save the argument into
03053     // a virtual register so that we can access it from the return points.
03054     if (Ins[i].Flags.isSRet()) {
03055       unsigned Reg = MipsFI->getSRetReturnReg();
03056       if (!Reg) {
03057         Reg = MF.getRegInfo().createVirtualRegister(
03058             getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
03059         MipsFI->setSRetReturnReg(Reg);
03060       }
03061       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
03062       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
03063       break;
03064     }
03065   }
03066 
03067   if (IsVarArg)
03068     writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
03069 
03070   // All stores are grouped in one node to allow the matching between
03071   // the size of Ins and InVals. This only happens when on varg functions
03072   if (!OutChains.empty()) {
03073     OutChains.push_back(Chain);
03074     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
03075   }
03076 
03077   return Chain;
03078 }
03079 
03080 //===----------------------------------------------------------------------===//
03081 //               Return Value Calling Convention Implementation
03082 //===----------------------------------------------------------------------===//
03083 
03084 bool
03085 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
03086                                    MachineFunction &MF, bool IsVarArg,
03087                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
03088                                    LLVMContext &Context) const {
03089   SmallVector<CCValAssign, 16> RVLocs;
03090   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
03091   return CCInfo.CheckReturn(Outs, RetCC_Mips);
03092 }
03093 
03094 bool
03095 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
03096   if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
03097     if (Type == MVT::i32)
03098       return true;
03099   }
03100   return IsSigned;
03101 }
03102 
03103 SDValue
03104 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
03105                                          SDLoc DL, SelectionDAG &DAG) const {
03106 
03107   MachineFunction &MF = DAG.getMachineFunction();
03108   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
03109 
03110   MipsFI->setISR();
03111 
03112   return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
03113 }
03114 
03115 SDValue
03116 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
03117                                 bool IsVarArg,
03118                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
03119                                 const SmallVectorImpl<SDValue> &OutVals,
03120                                 SDLoc DL, SelectionDAG &DAG) const {
03121   // CCValAssign - represent the assignment of
03122   // the return value to a location
03123   SmallVector<CCValAssign, 16> RVLocs;
03124   MachineFunction &MF = DAG.getMachineFunction();
03125 
03126   // CCState - Info about the registers and stack slot.
03127   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
03128 
03129   // Analyze return values.
03130   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
03131 
03132   SDValue Flag;
03133   SmallVector<SDValue, 4> RetOps(1, Chain);
03134 
03135   // Copy the result values into the output registers.
03136   for (unsigned i = 0; i != RVLocs.size(); ++i) {
03137     SDValue Val = OutVals[i];
03138     CCValAssign &VA = RVLocs[i];
03139     assert(VA.isRegLoc() && "Can only return in registers!");
03140     bool UseUpperBits = false;
03141 
03142     switch (VA.getLocInfo()) {
03143     default:
03144       llvm_unreachable("Unknown loc info!");
03145     case CCValAssign::Full:
03146       break;
03147     case CCValAssign::BCvt:
03148       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
03149       break;
03150     case CCValAssign::AExtUpper:
03151       UseUpperBits = true;
03152       // Fallthrough
03153     case CCValAssign::AExt:
03154       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
03155       break;
03156     case CCValAssign::ZExtUpper:
03157       UseUpperBits = true;
03158       // Fallthrough
03159     case CCValAssign::ZExt:
03160       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
03161       break;
03162     case CCValAssign::SExtUpper:
03163       UseUpperBits = true;
03164       // Fallthrough
03165     case CCValAssign::SExt:
03166       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
03167       break;
03168     }
03169 
03170     if (UseUpperBits) {
03171       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
03172       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
03173       Val = DAG.getNode(
03174           ISD::SHL, DL, VA.getLocVT(), Val,
03175           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
03176     }
03177 
03178     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
03179 
03180     // Guarantee that all emitted copies are stuck together with flags.
03181     Flag = Chain.getValue(1);
03182     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
03183   }
03184 
03185   // The mips ABIs for returning structs by value requires that we copy
03186   // the sret argument into $v0 for the return. We saved the argument into
03187   // a virtual register in the entry block, so now we copy the value out
03188   // and into $v0.
03189   if (MF.getFunction()->hasStructRetAttr()) {
03190     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
03191     unsigned Reg = MipsFI->getSRetReturnReg();
03192 
03193     if (!Reg)
03194       llvm_unreachable("sret virtual register not created in the entry block");
03195     SDValue Val =
03196         DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
03197     unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
03198 
03199     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
03200     Flag = Chain.getValue(1);
03201     RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
03202   }
03203 
03204   RetOps[0] = Chain;  // Update chain.
03205 
03206   // Add the flag if we have it.
03207   if (Flag.getNode())
03208     RetOps.push_back(Flag);
03209 
03210   // ISRs must use "eret".
03211   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
03212     return LowerInterruptReturn(RetOps, DL, DAG);
03213 
03214   // Standard return on Mips is a "jr $ra"
03215   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
03216 }
03217 
03218 //===----------------------------------------------------------------------===//
03219 //                           Mips Inline Assembly Support
03220 //===----------------------------------------------------------------------===//
03221 
03222 /// getConstraintType - Given a constraint letter, return the type of
03223 /// constraint it is for this target.
03224 MipsTargetLowering::ConstraintType
03225 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
03226   // Mips specific constraints
03227   // GCC config/mips/constraints.md
03228   //
03229   // 'd' : An address register. Equivalent to r
03230   //       unless generating MIPS16 code.
03231   // 'y' : Equivalent to r; retained for
03232   //       backwards compatibility.
03233   // 'c' : A register suitable for use in an indirect
03234   //       jump. This will always be $25 for -mabicalls.
03235   // 'l' : The lo register. 1 word storage.
03236   // 'x' : The hilo register pair. Double word storage.
03237   if (Constraint.size() == 1) {
03238     switch (Constraint[0]) {
03239       default : break;
03240       case 'd':
03241       case 'y':
03242       case 'f':
03243       case 'c':
03244       case 'l':
03245       case 'x':
03246         return C_RegisterClass;
03247       case 'R':
03248         return C_Memory;
03249     }
03250   }
03251 
03252   if (Constraint == "ZC")
03253     return C_Memory;
03254 
03255   return TargetLowering::getConstraintType(Constraint);
03256 }
03257 
03258 /// Examine constraint type and operand type and determine a weight value.
03259 /// This object must already have been set up with the operand type
03260 /// and the current alternative constraint selected.
03261 TargetLowering::ConstraintWeight
03262 MipsTargetLowering::getSingleConstraintMatchWeight(
03263     AsmOperandInfo &info, const char *constraint) const {
03264   ConstraintWeight weight = CW_Invalid;
03265   Value *CallOperandVal = info.CallOperandVal;
03266     // If we don't have a value, we can't do a match,
03267     // but allow it at the lowest weight.
03268   if (!CallOperandVal)
03269     return CW_Default;
03270   Type *type = CallOperandVal->getType();
03271   // Look at the constraint type.
03272   switch (*constraint) {
03273   default:
03274     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
03275     break;
03276   case 'd':
03277   case 'y':
03278     if (type->isIntegerTy())
03279       weight = CW_Register;
03280     break;
03281   case 'f': // FPU or MSA register
03282     if (Subtarget.hasMSA() && type->isVectorTy() &&
03283         cast<VectorType>(type)->getBitWidth() == 128)
03284       weight = CW_Register;
03285     else if (type->isFloatTy())
03286       weight = CW_Register;
03287     break;
03288   case 'c': // $25 for indirect jumps
03289   case 'l': // lo register
03290   case 'x': // hilo register pair
03291     if (type->isIntegerTy())
03292       weight = CW_SpecificReg;
03293     break;
03294   case 'I': // signed 16 bit immediate
03295   case 'J': // integer zero
03296   case 'K': // unsigned 16 bit immediate
03297   case 'L': // signed 32 bit immediate where lower 16 bits are 0
03298   case 'N': // immediate in the range of -65535 to -1 (inclusive)
03299   case 'O': // signed 15 bit immediate (+- 16383)
03300   case 'P': // immediate in the range of 65535 to 1 (inclusive)
03301     if (isa<ConstantInt>(CallOperandVal))
03302       weight = CW_Constant;
03303     break;
03304   case 'R':
03305     weight = CW_Memory;
03306     break;
03307   }
03308   return weight;
03309 }
03310 
03311 /// This is a helper function to parse a physical register string and split it
03312 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
03313 /// that is returned indicates whether parsing was successful. The second flag
03314 /// is true if the numeric part exists.
03315 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
03316                                               unsigned long long &Reg) {
03317   if (C.front() != '{' || C.back() != '}')
03318     return std::make_pair(false, false);
03319 
03320   // Search for the first numeric character.
03321   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
03322   I = std::find_if(B, E, isdigit);
03323 
03324   Prefix = StringRef(B, I - B);
03325 
03326   // The second flag is set to false if no numeric characters were found.
03327   if (I == E)
03328     return std::make_pair(true, false);
03329 
03330   // Parse the numeric characters.
03331   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
03332                         true);
03333 }
03334 
03335 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
03336 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
03337   const TargetRegisterInfo *TRI =
03338       Subtarget.getRegisterInfo();
03339   const TargetRegisterClass *RC;
03340   StringRef Prefix;
03341   unsigned long long Reg;
03342 
03343   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
03344 
03345   if (!R.first)
03346     return std::make_pair(0U, nullptr);
03347 
03348   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
03349     // No numeric characters follow "hi" or "lo".
03350     if (R.second)
03351       return std::make_pair(0U, nullptr);
03352 
03353     RC = TRI->getRegClass(Prefix == "hi" ?
03354                           Mips::HI32RegClassID : Mips::LO32RegClassID);
03355     return std::make_pair(*(RC->begin()), RC);
03356   } else if (Prefix.startswith("$msa")) {
03357     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
03358 
03359     // No numeric characters follow the name.
03360     if (R.second)
03361       return std::make_pair(0U, nullptr);
03362 
03363     Reg = StringSwitch<unsigned long long>(Prefix)
03364               .Case("$msair", Mips::MSAIR)
03365               .Case("$msacsr", Mips::MSACSR)
03366               .Case("$msaaccess", Mips::MSAAccess)
03367               .Case("$msasave", Mips::MSASave)
03368               .Case("$msamodify", Mips::MSAModify)
03369               .Case("$msarequest", Mips::MSARequest)
03370               .Case("$msamap", Mips::MSAMap)
03371               .Case("$msaunmap", Mips::MSAUnmap)
03372               .Default(0);
03373 
03374     if (!Reg)
03375       return std::make_pair(0U, nullptr);
03376 
03377     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
03378     return std::make_pair(Reg, RC);
03379   }
03380 
03381   if (!R.second)
03382     return std::make_pair(0U, nullptr);
03383 
03384   if (Prefix == "$f") { // Parse $f0-$f31.
03385     // If the size of FP registers is 64-bit or Reg is an even number, select
03386     // the 64-bit register class. Otherwise, select the 32-bit register class.
03387     if (VT == MVT::Other)
03388       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
03389 
03390     RC = getRegClassFor(VT);
03391 
03392     if (RC == &Mips::AFGR64RegClass) {
03393       assert(Reg % 2 == 0);
03394       Reg >>= 1;
03395     }
03396   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
03397     RC = TRI->getRegClass(Mips::FCCRegClassID);
03398   else if (Prefix == "$w") { // Parse $w0-$w31.
03399     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
03400   } else { // Parse $0-$31.
03401     assert(Prefix == "$");
03402     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
03403   }
03404 
03405   assert(Reg < RC->getNumRegs());
03406   return std::make_pair(*(RC->begin() + Reg), RC);
03407 }
03408 
03409 /// Given a register class constraint, like 'r', if this corresponds directly
03410 /// to an LLVM register class, return a register of 0 and the register class
03411 /// pointer.
03412 std::pair<unsigned, const TargetRegisterClass *>
03413 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
03414                                                  StringRef Constraint,
03415                                                  MVT VT) const {
03416   if (Constraint.size() == 1) {
03417     switch (Constraint[0]) {
03418     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
03419     case 'y': // Same as 'r'. Exists for compatibility.
03420     case 'r':
03421       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
03422         if (Subtarget.inMips16Mode())
03423           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
03424         return std::make_pair(0U, &Mips::GPR32RegClass);
03425       }
03426       if (VT == MVT::i64 && !Subtarget.isGP64bit())
03427         return std::make_pair(0U, &Mips::GPR32RegClass);
03428       if (VT == MVT::i64 && Subtarget.isGP64bit())
03429         return std::make_pair(0U, &Mips::GPR64RegClass);
03430       // This will generate an error message
03431       return std::make_pair(0U, nullptr);
03432     case 'f': // FPU or MSA register
03433       if (VT == MVT::v16i8)
03434         return std::make_pair(0U, &Mips::MSA128BRegClass);
03435       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
03436         return std::make_pair(0U, &Mips::MSA128HRegClass);
03437       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
03438         return std::make_pair(0U, &Mips::MSA128WRegClass);
03439       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
03440         return std::make_pair(0U, &Mips::MSA128DRegClass);
03441       else if (VT == MVT::f32)
03442         return std::make_pair(0U, &Mips::FGR32RegClass);
03443       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
03444         if (Subtarget.isFP64bit())
03445           return std::make_pair(0U, &Mips::FGR64RegClass);
03446         return std::make_pair(0U, &Mips::AFGR64RegClass);
03447       }
03448       break;
03449     case 'c': // register suitable for indirect jump
03450       if (VT == MVT::i32)
03451         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
03452       assert(VT == MVT::i64 && "Unexpected type.");
03453       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
03454     case 'l': // register suitable for indirect jump
03455       if (VT == MVT::i32)
03456         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
03457       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
03458     case 'x': // register suitable for indirect jump
03459       // Fixme: Not triggering the use of both hi and low
03460       // This will generate an error message
03461       return std::make_pair(0U, nullptr);
03462     }
03463   }
03464 
03465   std::pair<unsigned, const TargetRegisterClass *> R;
03466   R = parseRegForInlineAsmConstraint(Constraint, VT);
03467 
03468   if (R.second)
03469     return R;
03470 
03471   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
03472 }
03473 
03474 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
03475 /// vector.  If it is invalid, don't add anything to Ops.
03476 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
03477                                                      std::string &Constraint,
03478                                                      std::vector<SDValue>&Ops,
03479                                                      SelectionDAG &DAG) const {
03480   SDLoc DL(Op);
03481   SDValue Result;
03482 
03483   // Only support length 1 constraints for now.
03484   if (Constraint.length() > 1) return;
03485 
03486   char ConstraintLetter = Constraint[0];
03487   switch (ConstraintLetter) {
03488   default: break; // This will fall through to the generic implementation
03489   case 'I': // Signed 16 bit constant
03490     // If this fails, the parent routine will give an error
03491     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03492       EVT Type = Op.getValueType();
03493       int64_t Val = C->getSExtValue();
03494       if (isInt<16>(Val)) {
03495         Result = DAG.getTargetConstant(Val, DL, Type);
03496         break;
03497       }
03498     }
03499     return;
03500   case 'J': // integer zero
03501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03502       EVT Type = Op.getValueType();
03503       int64_t Val = C->getZExtValue();
03504       if (Val == 0) {
03505         Result = DAG.getTargetConstant(0, DL, Type);
03506         break;
03507       }
03508     }
03509     return;
03510   case 'K': // unsigned 16 bit immediate
03511     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03512       EVT Type = Op.getValueType();
03513       uint64_t Val = (uint64_t)C->getZExtValue();
03514       if (isUInt<16>(Val)) {
03515         Result = DAG.getTargetConstant(Val, DL, Type);
03516         break;
03517       }
03518     }
03519     return;
03520   case 'L': // signed 32 bit immediate where lower 16 bits are 0
03521     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03522       EVT Type = Op.getValueType();
03523       int64_t Val = C->getSExtValue();
03524       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
03525         Result = DAG.getTargetConstant(Val, DL, Type);
03526         break;
03527       }
03528     }
03529     return;
03530   case 'N': // immediate in the range of -65535 to -1 (inclusive)
03531     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03532       EVT Type = Op.getValueType();
03533       int64_t Val = C->getSExtValue();
03534       if ((Val >= -65535) && (Val <= -1)) {
03535         Result = DAG.getTargetConstant(Val, DL, Type);
03536         break;
03537       }
03538     }
03539     return;
03540   case 'O': // signed 15 bit immediate
03541     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03542       EVT Type = Op.getValueType();
03543       int64_t Val = C->getSExtValue();
03544       if ((isInt<15>(Val))) {
03545         Result = DAG.getTargetConstant(Val, DL, Type);
03546         break;
03547       }
03548     }
03549     return;
03550   case 'P': // immediate in the range of 1 to 65535 (inclusive)
03551     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
03552       EVT Type = Op.getValueType();
03553       int64_t Val = C->getSExtValue();
03554       if ((Val <= 65535) && (Val >= 1)) {
03555         Result = DAG.getTargetConstant(Val, DL, Type);
03556         break;
03557       }
03558     }
03559     return;
03560   }
03561 
03562   if (Result.getNode()) {
03563     Ops.push_back(Result);
03564     return;
03565   }
03566 
03567   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
03568 }
03569 
03570 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
03571                                                const AddrMode &AM, Type *Ty,
03572                                                unsigned AS) const {
03573   // No global is ever allowed as a base.
03574   if (AM.BaseGV)
03575     return false;
03576 
03577   switch (AM.Scale) {
03578   case 0: // "r+i" or just "i", depending on HasBaseReg.
03579     break;
03580   case 1:
03581     if (!AM.HasBaseReg) // allow "r+i".
03582       break;
03583     return false; // disallow "r+r" or "r+r+i".
03584   default:
03585     return false;
03586   }
03587 
03588   return true;
03589 }
03590 
03591 bool
03592 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
03593   // The Mips target isn't yet aware of offsets.
03594   return false;
03595 }
03596 
03597 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
03598                                             unsigned SrcAlign,
03599                                             bool IsMemset, bool ZeroMemset,
03600                                             bool MemcpyStrSrc,
03601                                             MachineFunction &MF) const {
03602   if (Subtarget.hasMips64())
03603     return MVT::i64;
03604 
03605   return MVT::i32;
03606 }
03607 
03608 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
03609   if (VT != MVT::f32 && VT != MVT::f64)
03610     return false;
03611   if (Imm.isNegZero())
03612     return false;
03613   return Imm.isZero();
03614 }
03615 
03616 unsigned MipsTargetLowering::getJumpTableEncoding() const {
03617   if (ABI.IsN64())
03618     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
03619 
03620   return TargetLowering::getJumpTableEncoding();
03621 }
03622 
03623 bool MipsTargetLowering::useSoftFloat() const {
03624   return Subtarget.useSoftFloat();
03625 }
03626 
03627 void MipsTargetLowering::copyByValRegs(
03628     SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
03629     const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
03630     const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
03631     const CCValAssign &VA, MipsCCState &State) const {
03632   MachineFunction &MF = DAG.getMachineFunction();
03633   MachineFrameInfo *MFI = MF.getFrameInfo();
03634   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
03635   unsigned NumRegs = LastReg - FirstReg;
03636   unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
03637   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
03638   int FrameObjOffset;
03639   ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
03640 
03641   if (RegAreaSize)
03642     FrameObjOffset =
03643         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
03644         (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
03645   else
03646     FrameObjOffset = VA.getLocMemOffset();
03647 
03648   // Create frame object.
03649   EVT PtrTy = getPointerTy(DAG.getDataLayout());
03650   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
03651   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
03652   InVals.push_back(FIN);
03653 
03654   if (!NumRegs)
03655     return;
03656 
03657   // Copy arg registers.
03658   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
03659   const TargetRegisterClass *RC = getRegClassFor(RegTy);
03660 
03661   for (unsigned I = 0; I < NumRegs; ++I) {
03662     unsigned ArgReg = ByValArgRegs[FirstReg + I];
03663     unsigned VReg = addLiveIn(MF, ArgReg, RC);
03664     unsigned Offset = I * GPRSizeInBytes;
03665     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
03666                                    DAG.getConstant(Offset, DL, PtrTy));
03667     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
03668                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
03669                                  false, false, 0);
03670     OutChains.push_back(Store);
03671   }
03672 }
03673 
03674 // Copy byVal arg to registers and stack.
03675 void MipsTargetLowering::passByValArg(
03676     SDValue Chain, SDLoc DL,
03677     std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
03678     SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
03679     MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
03680     unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
03681     const CCValAssign &VA) const {
03682   unsigned ByValSizeInBytes = Flags.getByValSize();
03683   unsigned OffsetInBytes = 0; // From beginning of struct
03684   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03685   unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
03686   EVT PtrTy = getPointerTy(DAG.getDataLayout()),
03687       RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
03688   unsigned NumRegs = LastReg - FirstReg;
03689 
03690   if (NumRegs) {
03691     ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
03692     bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
03693     unsigned I = 0;
03694 
03695     // Copy words to registers.
03696     for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
03697       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
03698                                     DAG.getConstant(OffsetInBytes, DL, PtrTy));
03699       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
03700                                     MachinePointerInfo(), false, false, false,
03701                                     Alignment);
03702       MemOpChains.push_back(LoadVal.getValue(1));
03703       unsigned ArgReg = ArgRegs[FirstReg + I];
03704       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
03705     }
03706 
03707     // Return if the struct has been fully copied.
03708     if (ByValSizeInBytes == OffsetInBytes)
03709       return;
03710 
03711     // Copy the remainder of the byval argument with sub-word loads and shifts.
03712     if (LeftoverBytes) {
03713       SDValue Val;
03714 
03715       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
03716            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
03717         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
03718 
03719         if (RemainingSizeInBytes < LoadSizeInBytes)
03720           continue;
03721 
03722         // Load subword.
03723         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
03724                                       DAG.getConstant(OffsetInBytes, DL,
03725                                                       PtrTy));
03726         SDValue LoadVal = DAG.getExtLoad(
03727             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
03728             MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
03729             Alignment);
03730         MemOpChains.push_back(LoadVal.getValue(1));
03731 
03732         // Shift the loaded value.
03733         unsigned Shamt;
03734 
03735         if (isLittle)
03736           Shamt = TotalBytesLoaded * 8;
03737         else
03738           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
03739 
03740         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
03741                                     DAG.getConstant(Shamt, DL, MVT::i32));
03742 
03743         if (Val.getNode())
03744           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
03745         else
03746           Val = Shift;
03747 
03748         OffsetInBytes += LoadSizeInBytes;
03749         TotalBytesLoaded += LoadSizeInBytes;
03750         Alignment = std::min(Alignment, LoadSizeInBytes);
03751       }
03752 
03753       unsigned ArgReg = ArgRegs[FirstReg + I];
03754       RegsToPass.push_back(std::make_pair(ArgReg, Val));
03755       return;
03756     }
03757   }
03758 
03759   // Copy remainder of byval arg to it with memcpy.
03760   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
03761   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
03762                             DAG.getConstant(OffsetInBytes, DL, PtrTy));
03763   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
03764                             DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
03765   Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
03766                         DAG.getConstant(MemCpySize, DL, PtrTy),
03767                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
03768                         /*isTailCall=*/false,
03769                         MachinePointerInfo(), MachinePointerInfo());
03770   MemOpChains.push_back(Chain);
03771 }
03772 
03773 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
03774                                          SDValue Chain, SDLoc DL,
03775                                          SelectionDAG &DAG,
03776                                          CCState &State) const {
03777   ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
03778   unsigned Idx = State.getFirstUnallocated(ArgRegs);
03779   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03780   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
03781   const TargetRegisterClass *RC = getRegClassFor(RegTy);
03782   MachineFunction &MF = DAG.getMachineFunction();
03783   MachineFrameInfo *MFI = MF.getFrameInfo();
03784   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
03785 
03786   // Offset of the first variable argument from stack pointer.
03787   int VaArgOffset;
03788 
03789   if (ArgRegs.size() == Idx)
03790     VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
03791   else {
03792     VaArgOffset =
03793         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
03794         (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
03795   }
03796 
03797   // Record the frame index of the first variable argument
03798   // which is a value necessary to VASTART.
03799   int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
03800   MipsFI->setVarArgsFrameIndex(FI);
03801 
03802   // Copy the integer registers that have not been used for argument passing
03803   // to the argument register save area. For O32, the save area is allocated
03804   // in the caller's stack frame, while for N32/64, it is allocated in the
03805   // callee's stack frame.
03806   for (unsigned I = Idx; I < ArgRegs.size();
03807        ++I, VaArgOffset += RegSizeInBytes) {
03808     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
03809     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
03810     FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
03811     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
03812     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
03813                                  MachinePointerInfo(), false, false, 0);
03814     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
03815         (Value *)nullptr);
03816     OutChains.push_back(Store);
03817   }
03818 }
03819 
03820 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
03821                                      unsigned Align) const {
03822   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
03823 
03824   assert(Size && "Byval argument's size shouldn't be 0.");
03825 
03826   Align = std::min(Align, TFL->getStackAlignment());
03827 
03828   unsigned FirstReg = 0;
03829   unsigned NumRegs = 0;
03830 
03831   if (State->getCallingConv() != CallingConv::Fast) {
03832     unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
03833     ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
03834     // FIXME: The O32 case actually describes no shadow registers.
03835     const MCPhysReg *ShadowRegs =
03836         ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
03837 
03838     // We used to check the size as well but we can't do that anymore since
03839     // CCState::HandleByVal() rounds up the size after calling this function.
03840     assert(!(Align % RegSizeInBytes) &&
03841            "Byval argument's alignment should be a multiple of"
03842            "RegSizeInBytes.");
03843 
03844     FirstReg = State->getFirstUnallocated(IntArgRegs);
03845 
03846     // If Align > RegSizeInBytes, the first arg register must be even.
03847     // FIXME: This condition happens to do the right thing but it's not the
03848     //        right way to test it. We want to check that the stack frame offset
03849     //        of the register is aligned.
03850     if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
03851       State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
03852       ++FirstReg;
03853     }
03854 
03855     // Mark the registers allocated.
03856     Size = alignTo(Size, RegSizeInBytes);
03857     for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
03858          Size -= RegSizeInBytes, ++I, ++NumRegs)
03859       State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
03860   }
03861 
03862   State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
03863 }
03864 
03865 MachineBasicBlock *
03866 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
03867                                      bool isFPCmp, unsigned Opc) const {
03868   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
03869          "Subtarget already supports SELECT nodes with the use of"
03870          "conditional-move instructions.");
03871 
03872   const TargetInstrInfo *TII =
03873       Subtarget.getInstrInfo();
03874   DebugLoc DL = MI->getDebugLoc();
03875 
03876   // To "insert" a SELECT instruction, we actually have to insert the
03877   // diamond control-flow pattern.  The incoming instruction knows the
03878   // destination vreg to set, the condition code register to branch on, the
03879   // true/false values to select between, and a branch opcode to use.
03880   const BasicBlock *LLVM_BB = BB->getBasicBlock();
03881   MachineFunction::iterator It = ++BB->getIterator();
03882 
03883   //  thisMBB:
03884   //  ...
03885   //   TrueVal = ...
03886   //   setcc r1, r2, r3
03887   //   bNE   r1, r0, copy1MBB
03888   //   fallthrough --> copy0MBB
03889   MachineBasicBlock *thisMBB  = BB;
03890   MachineFunction *F = BB->getParent();
03891   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
03892   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
03893   F->insert(It, copy0MBB);
03894   F->insert(It, sinkMBB);
03895 
03896   // Transfer the remainder of BB and its successor edges to sinkMBB.
03897   sinkMBB->splice(sinkMBB->begin(), BB,
03898                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
03899   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
03900 
03901   // Next, add the true and fallthrough blocks as its successors.
03902   BB->addSuccessor(copy0MBB);
03903   BB->addSuccessor(sinkMBB);
03904 
03905   if (isFPCmp) {
03906     // bc1[tf] cc, sinkMBB
03907     BuildMI(BB, DL, TII->get(Opc))
03908       .addReg(MI->getOperand(1).getReg())
03909       .addMBB(sinkMBB);
03910   } else {
03911     // bne rs, $0, sinkMBB
03912     BuildMI(BB, DL, TII->get(Opc))
03913       .addReg(MI->getOperand(1).getReg())
03914       .addReg(Mips::ZERO)
03915       .addMBB(sinkMBB);
03916   }
03917 
03918   //  copy0MBB:
03919   //   %FalseValue = ...
03920   //   # fallthrough to sinkMBB
03921   BB = copy0MBB;
03922 
03923   // Update machine-CFG edges
03924   BB->addSuccessor(sinkMBB);
03925 
03926   //  sinkMBB:
03927   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
03928   //  ...
03929   BB = sinkMBB;
03930 
03931   BuildMI(*BB, BB->begin(), DL,
03932           TII->get(Mips::PHI), MI->getOperand(0).getReg())
03933     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
03934     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
03935 
03936   MI->eraseFromParent();   // The pseudo instruction is gone now.
03937 
03938   return BB;
03939 }
03940 
03941 // FIXME? Maybe this could be a TableGen attribute on some registers and
03942 // this table could be generated automatically from RegInfo.
03943 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
03944                                                SelectionDAG &DAG) const {
03945   // Named registers is expected to be fairly rare. For now, just support $28
03946   // since the linux kernel uses it.
03947   if (Subtarget.isGP64bit()) {
03948     unsigned Reg = StringSwitch<unsigned>(RegName)
03949                          .Case("$28", Mips::GP_64)
03950                          .Default(0);
03951     if (Reg)
03952       return Reg;
03953   } else {
03954     unsigned Reg = StringSwitch<unsigned>(RegName)
03955                          .Case("$28", Mips::GP)
03956                          .Default(0);
03957     if (Reg)
03958       return Reg;
03959   }
03960   report_fatal_error("Invalid register name global variable");
03961 }