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