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