LLVM API Documentation

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