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