LLVM API Documentation

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