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