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