LLVM  mainline
ARMISelLowering.cpp
Go to the documentation of this file.
00001 //===-- ARMISelLowering.cpp - ARM 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 ARM uses to lower LLVM code into a
00011 // selection DAG.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "ARMISelLowering.h"
00016 #include "ARMCallingConv.h"
00017 #include "ARMConstantPoolValue.h"
00018 #include "ARMMachineFunctionInfo.h"
00019 #include "ARMPerfectShuffle.h"
00020 #include "ARMSubtarget.h"
00021 #include "ARMTargetMachine.h"
00022 #include "ARMTargetObjectFile.h"
00023 #include "MCTargetDesc/ARMAddressingModes.h"
00024 #include "llvm/ADT/Statistic.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/ADT/StringSwitch.h"
00027 #include "llvm/CodeGen/CallingConvLower.h"
00028 #include "llvm/CodeGen/IntrinsicLowering.h"
00029 #include "llvm/CodeGen/MachineBasicBlock.h"
00030 #include "llvm/CodeGen/MachineFrameInfo.h"
00031 #include "llvm/CodeGen/MachineFunction.h"
00032 #include "llvm/CodeGen/MachineInstrBuilder.h"
00033 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00034 #include "llvm/CodeGen/MachineModuleInfo.h"
00035 #include "llvm/CodeGen/MachineRegisterInfo.h"
00036 #include "llvm/CodeGen/SelectionDAG.h"
00037 #include "llvm/IR/CallingConv.h"
00038 #include "llvm/IR/Constants.h"
00039 #include "llvm/IR/Function.h"
00040 #include "llvm/IR/GlobalValue.h"
00041 #include "llvm/IR/IRBuilder.h"
00042 #include "llvm/IR/Instruction.h"
00043 #include "llvm/IR/Instructions.h"
00044 #include "llvm/IR/IntrinsicInst.h"
00045 #include "llvm/IR/Intrinsics.h"
00046 #include "llvm/IR/Type.h"
00047 #include "llvm/MC/MCSectionMachO.h"
00048 #include "llvm/Support/CommandLine.h"
00049 #include "llvm/Support/Debug.h"
00050 #include "llvm/Support/ErrorHandling.h"
00051 #include "llvm/Support/MathExtras.h"
00052 #include "llvm/Support/raw_ostream.h"
00053 #include "llvm/Target/TargetOptions.h"
00054 #include <utility>
00055 using namespace llvm;
00056 
00057 #define DEBUG_TYPE "arm-isel"
00058 
00059 STATISTIC(NumTailCalls, "Number of tail calls");
00060 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
00061 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
00062 
00063 cl::opt<bool>
00064 EnableARMLongCalls("arm-long-calls", cl::Hidden,
00065   cl::desc("Generate calls via indirect call instructions"),
00066   cl::init(false));
00067 
00068 static cl::opt<bool>
00069 ARMInterworking("arm-interworking", cl::Hidden,
00070   cl::desc("Enable / disable ARM interworking (for debugging only)"),
00071   cl::init(true));
00072 
00073 namespace {
00074   class ARMCCState : public CCState {
00075   public:
00076     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
00077                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
00078                ParmContext PC)
00079         : CCState(CC, isVarArg, MF, locs, C) {
00080       assert(((PC == Call) || (PC == Prologue)) &&
00081              "ARMCCState users must specify whether their context is call"
00082              "or prologue generation.");
00083       CallOrPrologue = PC;
00084     }
00085   };
00086 }
00087 
00088 // The APCS parameter registers.
00089 static const MCPhysReg GPRArgRegs[] = {
00090   ARM::R0, ARM::R1, ARM::R2, ARM::R3
00091 };
00092 
00093 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
00094                                        MVT PromotedBitwiseVT) {
00095   if (VT != PromotedLdStVT) {
00096     setOperationAction(ISD::LOAD, VT, Promote);
00097     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
00098 
00099     setOperationAction(ISD::STORE, VT, Promote);
00100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
00101   }
00102 
00103   MVT ElemTy = VT.getVectorElementType();
00104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
00105     setOperationAction(ISD::SETCC, VT, Custom);
00106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
00107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
00108   if (ElemTy == MVT::i32) {
00109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
00110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
00111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
00112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
00113   } else {
00114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
00115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
00116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
00117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
00118   }
00119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
00120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
00121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
00122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
00123   setOperationAction(ISD::SELECT,            VT, Expand);
00124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
00125   setOperationAction(ISD::VSELECT,           VT, Expand);
00126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
00127   if (VT.isInteger()) {
00128     setOperationAction(ISD::SHL, VT, Custom);
00129     setOperationAction(ISD::SRA, VT, Custom);
00130     setOperationAction(ISD::SRL, VT, Custom);
00131   }
00132 
00133   // Promote all bit-wise operations.
00134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
00135     setOperationAction(ISD::AND, VT, Promote);
00136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
00137     setOperationAction(ISD::OR,  VT, Promote);
00138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
00139     setOperationAction(ISD::XOR, VT, Promote);
00140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
00141   }
00142 
00143   // Neon does not support vector divide/remainder operations.
00144   setOperationAction(ISD::SDIV, VT, Expand);
00145   setOperationAction(ISD::UDIV, VT, Expand);
00146   setOperationAction(ISD::FDIV, VT, Expand);
00147   setOperationAction(ISD::SREM, VT, Expand);
00148   setOperationAction(ISD::UREM, VT, Expand);
00149   setOperationAction(ISD::FREM, VT, Expand);
00150 }
00151 
00152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
00153   addRegisterClass(VT, &ARM::DPRRegClass);
00154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
00155 }
00156 
00157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
00158   addRegisterClass(VT, &ARM::DPairRegClass);
00159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
00160 }
00161 
00162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
00163                                      const ARMSubtarget &STI)
00164     : TargetLowering(TM), Subtarget(&STI) {
00165   RegInfo = Subtarget->getRegisterInfo();
00166   Itins = Subtarget->getInstrItineraryData();
00167 
00168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00169 
00170   if (Subtarget->isTargetMachO()) {
00171     // Uses VFP for Thumb libfuncs if available.
00172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
00173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
00174       // Single-precision floating-point arithmetic.
00175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
00176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
00177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
00178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
00179 
00180       // Double-precision floating-point arithmetic.
00181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
00182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
00183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
00184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
00185 
00186       // Single-precision comparisons.
00187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
00188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
00189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
00190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
00191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
00192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
00193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
00194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
00195 
00196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
00197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
00198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
00199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
00200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
00201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
00202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
00203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
00204 
00205       // Double-precision comparisons.
00206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
00207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
00208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
00209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
00210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
00211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
00212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
00213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
00214 
00215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
00216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
00217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
00218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
00219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
00220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
00221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
00222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
00223 
00224       // Floating-point to integer conversions.
00225       // i64 conversions are done via library routines even when generating VFP
00226       // instructions, so use the same ones.
00227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
00228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
00229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
00230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
00231 
00232       // Conversions between floating types.
00233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
00234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
00235 
00236       // Integer to floating-point conversions.
00237       // i64 conversions are done via library routines even when generating VFP
00238       // instructions, so use the same ones.
00239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
00240       // e.g., __floatunsidf vs. __floatunssidfvfp.
00241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
00242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
00243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
00244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
00245     }
00246   }
00247 
00248   // These libcalls are not available in 32-bit.
00249   setLibcallName(RTLIB::SHL_I128, nullptr);
00250   setLibcallName(RTLIB::SRL_I128, nullptr);
00251   setLibcallName(RTLIB::SRA_I128, nullptr);
00252 
00253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
00254       !Subtarget->isTargetWindows()) {
00255     static const struct {
00256       const RTLIB::Libcall Op;
00257       const char * const Name;
00258       const CallingConv::ID CC;
00259       const ISD::CondCode Cond;
00260     } LibraryCalls[] = {
00261       // Double-precision floating-point arithmetic helper functions
00262       // RTABI chapter 4.1.2, Table 2
00263       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00264       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00265       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00266       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00267 
00268       // Double-precision floating-point comparison helper functions
00269       // RTABI chapter 4.1.2, Table 3
00270       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
00271       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
00272       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
00273       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
00274       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
00275       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
00276       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
00277       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
00278 
00279       // Single-precision floating-point arithmetic helper functions
00280       // RTABI chapter 4.1.2, Table 4
00281       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00282       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00283       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00284       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00285 
00286       // Single-precision floating-point comparison helper functions
00287       // RTABI chapter 4.1.2, Table 5
00288       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
00289       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
00290       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
00291       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
00292       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
00293       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
00294       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
00295       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
00296 
00297       // Floating-point to integer conversions.
00298       // RTABI chapter 4.1.2, Table 6
00299       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00300       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00301       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00302       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00303       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00304       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00305       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00306       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00307 
00308       // Conversions between floating types.
00309       // RTABI chapter 4.1.2, Table 7
00310       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00311       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00312       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00313 
00314       // Integer to floating-point conversions.
00315       // RTABI chapter 4.1.2, Table 8
00316       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00317       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00318       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00319       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00320       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00321       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00322       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00323       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00324 
00325       // Long long helper functions
00326       // RTABI chapter 4.2, Table 9
00327       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00328       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00329       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00330       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00331 
00332       // Integer division functions
00333       // RTABI chapter 4.3.1
00334       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00335       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00336       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00337       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00338       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00339       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00340       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00341       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00342 
00343       // Memory operations
00344       // RTABI chapter 4.3.4
00345       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00346       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00347       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00348     };
00349 
00350     for (const auto &LC : LibraryCalls) {
00351       setLibcallName(LC.Op, LC.Name);
00352       setLibcallCallingConv(LC.Op, LC.CC);
00353       if (LC.Cond != ISD::SETCC_INVALID)
00354         setCmpLibcallCC(LC.Op, LC.Cond);
00355     }
00356   }
00357 
00358   if (Subtarget->isTargetWindows()) {
00359     static const struct {
00360       const RTLIB::Libcall Op;
00361       const char * const Name;
00362       const CallingConv::ID CC;
00363     } LibraryCalls[] = {
00364       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
00365       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
00366       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
00367       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
00368       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
00369       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
00370       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
00371       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
00372     };
00373 
00374     for (const auto &LC : LibraryCalls) {
00375       setLibcallName(LC.Op, LC.Name);
00376       setLibcallCallingConv(LC.Op, LC.CC);
00377     }
00378   }
00379 
00380   // Use divmod compiler-rt calls for iOS 5.0 and later.
00381   if (Subtarget->getTargetTriple().isiOS() &&
00382       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
00383     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
00384     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
00385   }
00386 
00387   // The half <-> float conversion functions are always soft-float, but are
00388   // needed for some targets which use a hard-float calling convention by
00389   // default.
00390   if (Subtarget->isAAPCS_ABI()) {
00391     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
00392     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
00393     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
00394   } else {
00395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
00396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
00397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
00398   }
00399 
00400   if (Subtarget->isThumb1Only())
00401     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
00402   else
00403     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
00404   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
00405       !Subtarget->isThumb1Only()) {
00406     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
00407     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
00408   }
00409 
00410   for (MVT VT : MVT::vector_valuetypes()) {
00411     for (MVT InnerVT : MVT::vector_valuetypes()) {
00412       setTruncStoreAction(VT, InnerVT, Expand);
00413       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
00414       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
00415       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
00416     }
00417 
00418     setOperationAction(ISD::MULHS, VT, Expand);
00419     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
00420     setOperationAction(ISD::MULHU, VT, Expand);
00421     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
00422 
00423     setOperationAction(ISD::BSWAP, VT, Expand);
00424   }
00425 
00426   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
00427   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
00428 
00429   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
00430   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
00431 
00432   if (Subtarget->hasNEON()) {
00433     addDRTypeForNEON(MVT::v2f32);
00434     addDRTypeForNEON(MVT::v8i8);
00435     addDRTypeForNEON(MVT::v4i16);
00436     addDRTypeForNEON(MVT::v2i32);
00437     addDRTypeForNEON(MVT::v1i64);
00438 
00439     addQRTypeForNEON(MVT::v4f32);
00440     addQRTypeForNEON(MVT::v2f64);
00441     addQRTypeForNEON(MVT::v16i8);
00442     addQRTypeForNEON(MVT::v8i16);
00443     addQRTypeForNEON(MVT::v4i32);
00444     addQRTypeForNEON(MVT::v2i64);
00445 
00446     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
00447     // neither Neon nor VFP support any arithmetic operations on it.
00448     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
00449     // supported for v4f32.
00450     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
00451     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
00452     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
00453     // FIXME: Code duplication: FDIV and FREM are expanded always, see
00454     // ARMTargetLowering::addTypeForNEON method for details.
00455     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
00456     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
00457     // FIXME: Create unittest.
00458     // In another words, find a way when "copysign" appears in DAG with vector
00459     // operands.
00460     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
00461     // FIXME: Code duplication: SETCC has custom operation action, see
00462     // ARMTargetLowering::addTypeForNEON method for details.
00463     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
00464     // FIXME: Create unittest for FNEG and for FABS.
00465     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
00466     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
00467     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
00468     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
00469     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
00470     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
00471     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
00472     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
00473     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
00474     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
00475     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
00476     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
00477     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
00478     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
00479     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
00480     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
00481     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
00482     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
00483     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
00484 
00485     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
00486     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
00487     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
00488     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
00489     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
00490     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
00491     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
00492     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
00493     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
00494     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
00495     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
00496     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
00497     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
00498     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
00499     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
00500 
00501     // Mark v2f32 intrinsics.
00502     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
00503     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
00504     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
00505     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
00506     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
00507     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
00508     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
00509     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
00510     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
00511     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
00512     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
00513     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
00514     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
00515     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
00516     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
00517 
00518     // Neon does not support some operations on v1i64 and v2i64 types.
00519     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
00520     // Custom handling for some quad-vector types to detect VMULL.
00521     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
00522     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
00523     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
00524     // Custom handling for some vector types to avoid expensive expansions
00525     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
00526     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
00527     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
00528     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
00529     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
00530     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
00531     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
00532     // a destination type that is wider than the source, and nor does
00533     // it have a FP_TO_[SU]INT instruction with a narrower destination than
00534     // source.
00535     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
00536     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
00537     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
00538     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
00539 
00540     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
00541     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
00542 
00543     // NEON does not have single instruction CTPOP for vectors with element
00544     // types wider than 8-bits.  However, custom lowering can leverage the
00545     // v8i8/v16i8 vcnt instruction.
00546     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
00547     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
00548     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
00549     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
00550 
00551     // NEON only has FMA instructions as of VFP4.
00552     if (!Subtarget->hasVFP4()) {
00553       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
00554       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
00555     }
00556 
00557     setTargetDAGCombine(ISD::INTRINSIC_VOID);
00558     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
00559     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
00560     setTargetDAGCombine(ISD::SHL);
00561     setTargetDAGCombine(ISD::SRL);
00562     setTargetDAGCombine(ISD::SRA);
00563     setTargetDAGCombine(ISD::SIGN_EXTEND);
00564     setTargetDAGCombine(ISD::ZERO_EXTEND);
00565     setTargetDAGCombine(ISD::ANY_EXTEND);
00566     setTargetDAGCombine(ISD::SELECT_CC);
00567     setTargetDAGCombine(ISD::BUILD_VECTOR);
00568     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
00569     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
00570     setTargetDAGCombine(ISD::STORE);
00571     setTargetDAGCombine(ISD::FP_TO_SINT);
00572     setTargetDAGCombine(ISD::FP_TO_UINT);
00573     setTargetDAGCombine(ISD::FDIV);
00574     setTargetDAGCombine(ISD::LOAD);
00575 
00576     // It is legal to extload from v4i8 to v4i16 or v4i32.
00577     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
00578                    MVT::v2i32}) {
00579       for (MVT VT : MVT::integer_vector_valuetypes()) {
00580         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
00581         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
00582         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
00583       }
00584     }
00585   }
00586 
00587   // ARM and Thumb2 support UMLAL/SMLAL.
00588   if (!Subtarget->isThumb1Only())
00589     setTargetDAGCombine(ISD::ADDC);
00590 
00591   if (Subtarget->isFPOnlySP()) {
00592     // When targetting a floating-point unit with only single-precision
00593     // operations, f64 is legal for the few double-precision instructions which
00594     // are present However, no double-precision operations other than moves,
00595     // loads and stores are provided by the hardware.
00596     setOperationAction(ISD::FADD,       MVT::f64, Expand);
00597     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
00598     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
00599     setOperationAction(ISD::FMA,        MVT::f64, Expand);
00600     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
00601     setOperationAction(ISD::FREM,       MVT::f64, Expand);
00602     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
00603     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
00604     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
00605     setOperationAction(ISD::FABS,       MVT::f64, Expand);
00606     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
00607     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
00608     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
00609     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
00610     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
00611     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
00612     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
00613     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
00614     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
00615     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
00616     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
00617     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
00618     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
00619     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
00620     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
00621     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00622     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
00623     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00624     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00625     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
00626     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
00627     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
00628     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
00629   }
00630 
00631   computeRegisterProperties(Subtarget->getRegisterInfo());
00632 
00633   // ARM does not have floating-point extending loads.
00634   for (MVT VT : MVT::fp_valuetypes()) {
00635     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
00636     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
00637   }
00638 
00639   // ... or truncating stores
00640   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00641   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
00642   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
00643 
00644   // ARM does not have i1 sign extending load.
00645   for (MVT VT : MVT::integer_valuetypes())
00646     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
00647 
00648   // ARM supports all 4 flavors of integer indexed load / store.
00649   if (!Subtarget->isThumb1Only()) {
00650     for (unsigned im = (unsigned)ISD::PRE_INC;
00651          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
00652       setIndexedLoadAction(im,  MVT::i1,  Legal);
00653       setIndexedLoadAction(im,  MVT::i8,  Legal);
00654       setIndexedLoadAction(im,  MVT::i16, Legal);
00655       setIndexedLoadAction(im,  MVT::i32, Legal);
00656       setIndexedStoreAction(im, MVT::i1,  Legal);
00657       setIndexedStoreAction(im, MVT::i8,  Legal);
00658       setIndexedStoreAction(im, MVT::i16, Legal);
00659       setIndexedStoreAction(im, MVT::i32, Legal);
00660     }
00661   }
00662 
00663   setOperationAction(ISD::SADDO, MVT::i32, Custom);
00664   setOperationAction(ISD::UADDO, MVT::i32, Custom);
00665   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
00666   setOperationAction(ISD::USUBO, MVT::i32, Custom);
00667 
00668   // i64 operation support.
00669   setOperationAction(ISD::MUL,     MVT::i64, Expand);
00670   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
00671   if (Subtarget->isThumb1Only()) {
00672     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
00673     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00674   }
00675   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
00676       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
00677     setOperationAction(ISD::MULHS, MVT::i32, Expand);
00678 
00679   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
00680   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
00681   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
00682   setOperationAction(ISD::SRL,       MVT::i64, Custom);
00683   setOperationAction(ISD::SRA,       MVT::i64, Custom);
00684 
00685   if (!Subtarget->isThumb1Only()) {
00686     // FIXME: We should do this for Thumb1 as well.
00687     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
00688     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
00689     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
00690     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
00691   }
00692 
00693   // ARM does not have ROTL.
00694   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
00695   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
00696   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
00697   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
00698     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
00699 
00700   // These just redirect to CTTZ and CTLZ on ARM.
00701   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
00702   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
00703 
00704   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
00705 
00706   // Only ARMv6 has BSWAP.
00707   if (!Subtarget->hasV6Ops())
00708     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00709 
00710   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
00711       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
00712     // These are expanded into libcalls if the cpu doesn't have HW divider.
00713     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
00714     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
00715   }
00716 
00717   // FIXME: Also set divmod for SREM on EABI
00718   setOperationAction(ISD::SREM,  MVT::i32, Expand);
00719   setOperationAction(ISD::UREM,  MVT::i32, Expand);
00720   // Register based DivRem for AEABI (RTABI 4.2)
00721   if (Subtarget->isTargetAEABI()) {
00722     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
00723     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
00724     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
00725     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
00726     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
00727     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
00728     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
00729     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
00730 
00731     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
00732     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
00733     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
00734     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
00735     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
00736     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
00737     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
00738     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
00739 
00740     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
00741     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
00742   } else {
00743     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
00744     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
00745   }
00746 
00747   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
00748   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
00749   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
00750   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00751   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
00752 
00753   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00754 
00755   // Use the default implementation.
00756   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
00757   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
00758   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
00759   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
00760   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
00761   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
00762 
00763   if (!Subtarget->isTargetMachO()) {
00764     // Non-MachO platforms may return values in these registers via the
00765     // personality function.
00766     setExceptionPointerRegister(ARM::R0);
00767     setExceptionSelectorRegister(ARM::R1);
00768   }
00769 
00770   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
00771     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
00772   else
00773     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
00774 
00775   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
00776   // the default expansion. If we are targeting a single threaded system,
00777   // then set them all for expand so we can lower them later into their
00778   // non-atomic form.
00779   if (TM.Options.ThreadModel == ThreadModel::Single)
00780     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
00781   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
00782     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
00783     // to ldrex/strex loops already.
00784     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
00785 
00786     // On v8, we have particularly efficient implementations of atomic fences
00787     // if they can be combined with nearby atomic loads and stores.
00788     if (!Subtarget->hasV8Ops()) {
00789       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
00790       setInsertFencesForAtomic(true);
00791     }
00792   } else {
00793     // If there's anything we can use as a barrier, go through custom lowering
00794     // for ATOMIC_FENCE.
00795     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
00796                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
00797 
00798     // Set them all for expansion, which will force libcalls.
00799     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
00800     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
00801     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
00802     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
00803     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
00804     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
00805     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
00806     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
00807     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
00808     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
00809     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
00810     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
00811     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
00812     // Unordered/Monotonic case.
00813     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
00814     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
00815   }
00816 
00817   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
00818 
00819   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
00820   if (!Subtarget->hasV6Ops()) {
00821     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00822     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
00823   }
00824   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00825 
00826   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
00827       !Subtarget->isThumb1Only()) {
00828     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
00829     // iff target supports vfp2.
00830     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
00831     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
00832   }
00833 
00834   // We want to custom lower some of our intrinsics.
00835   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00836   if (Subtarget->isTargetDarwin()) {
00837     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
00838     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
00839     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
00840   }
00841 
00842   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
00843   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
00844   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
00845   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
00846   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
00847   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
00848   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
00849   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00850   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00851 
00852   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
00853   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
00854   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
00855   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
00856   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
00857 
00858   // We don't support sin/cos/fmod/copysign/pow
00859   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
00860   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
00861   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
00862   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
00863   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
00864   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
00865   setOperationAction(ISD::FREM,      MVT::f64, Expand);
00866   setOperationAction(ISD::FREM,      MVT::f32, Expand);
00867   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
00868       !Subtarget->isThumb1Only()) {
00869     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
00870     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
00871   }
00872   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
00873   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
00874 
00875   if (!Subtarget->hasVFP4()) {
00876     setOperationAction(ISD::FMA, MVT::f64, Expand);
00877     setOperationAction(ISD::FMA, MVT::f32, Expand);
00878   }
00879 
00880   // Various VFP goodness
00881   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
00882     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
00883     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
00884       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
00885       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
00886     }
00887 
00888     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
00889     if (!Subtarget->hasFP16()) {
00890       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
00891       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
00892     }
00893   }
00894 
00895   // Combine sin / cos into one node or libcall if possible.
00896   if (Subtarget->hasSinCos()) {
00897     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
00898     setLibcallName(RTLIB::SINCOS_F64, "sincos");
00899     if (Subtarget->getTargetTriple().isiOS()) {
00900       // For iOS, we don't want to the normal expansion of a libcall to
00901       // sincos. We want to issue a libcall to __sincos_stret.
00902       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
00903       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
00904     }
00905   }
00906 
00907   // FP-ARMv8 implements a lot of rounding-like FP operations.
00908   if (Subtarget->hasFPARMv8()) {
00909     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
00910     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
00911     setOperationAction(ISD::FROUND, MVT::f32, Legal);
00912     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
00913     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
00914     setOperationAction(ISD::FRINT, MVT::f32, Legal);
00915     if (!Subtarget->isFPOnlySP()) {
00916       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
00917       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
00918       setOperationAction(ISD::FROUND, MVT::f64, Legal);
00919       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
00920       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
00921       setOperationAction(ISD::FRINT, MVT::f64, Legal);
00922     }
00923   }
00924   // We have target-specific dag combine patterns for the following nodes:
00925   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
00926   setTargetDAGCombine(ISD::ADD);
00927   setTargetDAGCombine(ISD::SUB);
00928   setTargetDAGCombine(ISD::MUL);
00929   setTargetDAGCombine(ISD::AND);
00930   setTargetDAGCombine(ISD::OR);
00931   setTargetDAGCombine(ISD::XOR);
00932 
00933   if (Subtarget->hasV6Ops())
00934     setTargetDAGCombine(ISD::SRL);
00935 
00936   setStackPointerRegisterToSaveRestore(ARM::SP);
00937 
00938   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
00939       !Subtarget->hasVFP2())
00940     setSchedulingPreference(Sched::RegPressure);
00941   else
00942     setSchedulingPreference(Sched::Hybrid);
00943 
00944   //// temporary - rewrite interface to use type
00945   MaxStoresPerMemset = 8;
00946   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
00947   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
00948   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
00949   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
00950   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
00951 
00952   // On ARM arguments smaller than 4 bytes are extended, so all arguments
00953   // are at least 4 bytes aligned.
00954   setMinStackArgumentAlignment(4);
00955 
00956   // Prefer likely predicted branches to selects on out-of-order cores.
00957   PredictableSelectIsExpensive = Subtarget->isLikeA9();
00958 
00959   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
00960 }
00961 
00962 bool ARMTargetLowering::useSoftFloat() const {
00963   return Subtarget->useSoftFloat();
00964 }
00965 
00966 // FIXME: It might make sense to define the representative register class as the
00967 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
00968 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
00969 // SPR's representative would be DPR_VFP2. This should work well if register
00970 // pressure tracking were modified such that a register use would increment the
00971 // pressure of the register class's representative and all of it's super
00972 // classes' representatives transitively. We have not implemented this because
00973 // of the difficulty prior to coalescing of modeling operand register classes
00974 // due to the common occurrence of cross class copies and subregister insertions
00975 // and extractions.
00976 std::pair<const TargetRegisterClass *, uint8_t>
00977 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
00978                                            MVT VT) const {
00979   const TargetRegisterClass *RRC = nullptr;
00980   uint8_t Cost = 1;
00981   switch (VT.SimpleTy) {
00982   default:
00983     return TargetLowering::findRepresentativeClass(TRI, VT);
00984   // Use DPR as representative register class for all floating point
00985   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
00986   // the cost is 1 for both f32 and f64.
00987   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
00988   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
00989     RRC = &ARM::DPRRegClass;
00990     // When NEON is used for SP, only half of the register file is available
00991     // because operations that define both SP and DP results will be constrained
00992     // to the VFP2 class (D0-D15). We currently model this constraint prior to
00993     // coalescing by double-counting the SP regs. See the FIXME above.
00994     if (Subtarget->useNEONForSinglePrecisionFP())
00995       Cost = 2;
00996     break;
00997   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
00998   case MVT::v4f32: case MVT::v2f64:
00999     RRC = &ARM::DPRRegClass;
01000     Cost = 2;
01001     break;
01002   case MVT::v4i64:
01003     RRC = &ARM::DPRRegClass;
01004     Cost = 4;
01005     break;
01006   case MVT::v8i64:
01007     RRC = &ARM::DPRRegClass;
01008     Cost = 8;
01009     break;
01010   }
01011   return std::make_pair(RRC, Cost);
01012 }
01013 
01014 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
01015   switch ((ARMISD::NodeType)Opcode) {
01016   case ARMISD::FIRST_NUMBER:  break;
01017   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
01018   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
01019   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
01020   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
01021   case ARMISD::CALL:          return "ARMISD::CALL";
01022   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
01023   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
01024   case ARMISD::tCALL:         return "ARMISD::tCALL";
01025   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
01026   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
01027   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
01028   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
01029   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
01030   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
01031   case ARMISD::CMP:           return "ARMISD::CMP";
01032   case ARMISD::CMN:           return "ARMISD::CMN";
01033   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
01034   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
01035   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
01036   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
01037   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
01038 
01039   case ARMISD::CMOV:          return "ARMISD::CMOV";
01040 
01041   case ARMISD::RBIT:          return "ARMISD::RBIT";
01042 
01043   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
01044   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
01045   case ARMISD::RRX:           return "ARMISD::RRX";
01046 
01047   case ARMISD::ADDC:          return "ARMISD::ADDC";
01048   case ARMISD::ADDE:          return "ARMISD::ADDE";
01049   case ARMISD::SUBC:          return "ARMISD::SUBC";
01050   case ARMISD::SUBE:          return "ARMISD::SUBE";
01051 
01052   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
01053   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
01054 
01055   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
01056   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
01057 
01058   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
01059 
01060   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
01061 
01062   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
01063 
01064   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
01065 
01066   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
01067 
01068   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
01069 
01070   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
01071   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
01072   case ARMISD::VCGE:          return "ARMISD::VCGE";
01073   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
01074   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
01075   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
01076   case ARMISD::VCGT:          return "ARMISD::VCGT";
01077   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
01078   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
01079   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
01080   case ARMISD::VTST:          return "ARMISD::VTST";
01081 
01082   case ARMISD::VSHL:          return "ARMISD::VSHL";
01083   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
01084   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
01085   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
01086   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
01087   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
01088   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
01089   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
01090   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
01091   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
01092   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
01093   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
01094   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
01095   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
01096   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
01097   case ARMISD::VSLI:          return "ARMISD::VSLI";
01098   case ARMISD::VSRI:          return "ARMISD::VSRI";
01099   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
01100   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
01101   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
01102   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
01103   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
01104   case ARMISD::VDUP:          return "ARMISD::VDUP";
01105   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
01106   case ARMISD::VEXT:          return "ARMISD::VEXT";
01107   case ARMISD::VREV64:        return "ARMISD::VREV64";
01108   case ARMISD::VREV32:        return "ARMISD::VREV32";
01109   case ARMISD::VREV16:        return "ARMISD::VREV16";
01110   case ARMISD::VZIP:          return "ARMISD::VZIP";
01111   case ARMISD::VUZP:          return "ARMISD::VUZP";
01112   case ARMISD::VTRN:          return "ARMISD::VTRN";
01113   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
01114   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
01115   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
01116   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
01117   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
01118   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
01119   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
01120   case ARMISD::FMAX:          return "ARMISD::FMAX";
01121   case ARMISD::FMIN:          return "ARMISD::FMIN";
01122   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
01123   case ARMISD::VMINNM:        return "ARMISD::VMIN";
01124   case ARMISD::BFI:           return "ARMISD::BFI";
01125   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
01126   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
01127   case ARMISD::VBSL:          return "ARMISD::VBSL";
01128   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
01129   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
01130   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
01131   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
01132   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
01133   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
01134   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
01135   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
01136   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
01137   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
01138   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
01139   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
01140   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
01141   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
01142   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
01143   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
01144   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
01145   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
01146   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
01147   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
01148   }
01149   return nullptr;
01150 }
01151 
01152 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
01153   if (!VT.isVector()) return getPointerTy();
01154   return VT.changeVectorElementTypeToInteger();
01155 }
01156 
01157 /// getRegClassFor - Return the register class that should be used for the
01158 /// specified value type.
01159 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
01160   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
01161   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
01162   // load / store 4 to 8 consecutive D registers.
01163   if (Subtarget->hasNEON()) {
01164     if (VT == MVT::v4i64)
01165       return &ARM::QQPRRegClass;
01166     if (VT == MVT::v8i64)
01167       return &ARM::QQQQPRRegClass;
01168   }
01169   return TargetLowering::getRegClassFor(VT);
01170 }
01171 
01172 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
01173 // source/dest is aligned and the copy size is large enough. We therefore want
01174 // to align such objects passed to memory intrinsics.
01175 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
01176                                                unsigned &PrefAlign) const {
01177   if (!isa<MemIntrinsic>(CI))
01178     return false;
01179   MinSize = 8;
01180   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
01181   // cycle faster than 4-byte aligned LDM.
01182   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
01183   return true;
01184 }
01185 
01186 // Create a fast isel object.
01187 FastISel *
01188 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
01189                                   const TargetLibraryInfo *libInfo) const {
01190   return ARM::createFastISel(funcInfo, libInfo);
01191 }
01192 
01193 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
01194   unsigned NumVals = N->getNumValues();
01195   if (!NumVals)
01196     return Sched::RegPressure;
01197 
01198   for (unsigned i = 0; i != NumVals; ++i) {
01199     EVT VT = N->getValueType(i);
01200     if (VT == MVT::Glue || VT == MVT::Other)
01201       continue;
01202     if (VT.isFloatingPoint() || VT.isVector())
01203       return Sched::ILP;
01204   }
01205 
01206   if (!N->isMachineOpcode())
01207     return Sched::RegPressure;
01208 
01209   // Load are scheduled for latency even if there instruction itinerary
01210   // is not available.
01211   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
01212   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01213 
01214   if (MCID.getNumDefs() == 0)
01215     return Sched::RegPressure;
01216   if (!Itins->isEmpty() &&
01217       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
01218     return Sched::ILP;
01219 
01220   return Sched::RegPressure;
01221 }
01222 
01223 //===----------------------------------------------------------------------===//
01224 // Lowering Code
01225 //===----------------------------------------------------------------------===//
01226 
01227 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
01228 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
01229   switch (CC) {
01230   default: llvm_unreachable("Unknown condition code!");
01231   case ISD::SETNE:  return ARMCC::NE;
01232   case ISD::SETEQ:  return ARMCC::EQ;
01233   case ISD::SETGT:  return ARMCC::GT;
01234   case ISD::SETGE:  return ARMCC::GE;
01235   case ISD::SETLT:  return ARMCC::LT;
01236   case ISD::SETLE:  return ARMCC::LE;
01237   case ISD::SETUGT: return ARMCC::HI;
01238   case ISD::SETUGE: return ARMCC::HS;
01239   case ISD::SETULT: return ARMCC::LO;
01240   case ISD::SETULE: return ARMCC::LS;
01241   }
01242 }
01243 
01244 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
01245 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
01246                         ARMCC::CondCodes &CondCode2) {
01247   CondCode2 = ARMCC::AL;
01248   switch (CC) {
01249   default: llvm_unreachable("Unknown FP condition!");
01250   case ISD::SETEQ:
01251   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
01252   case ISD::SETGT:
01253   case ISD::SETOGT: CondCode = ARMCC::GT; break;
01254   case ISD::SETGE:
01255   case ISD::SETOGE: CondCode = ARMCC::GE; break;
01256   case ISD::SETOLT: CondCode = ARMCC::MI; break;
01257   case ISD::SETOLE: CondCode = ARMCC::LS; break;
01258   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
01259   case ISD::SETO:   CondCode = ARMCC::VC; break;
01260   case ISD::SETUO:  CondCode = ARMCC::VS; break;
01261   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
01262   case ISD::SETUGT: CondCode = ARMCC::HI; break;
01263   case ISD::SETUGE: CondCode = ARMCC::PL; break;
01264   case ISD::SETLT:
01265   case ISD::SETULT: CondCode = ARMCC::LT; break;
01266   case ISD::SETLE:
01267   case ISD::SETULE: CondCode = ARMCC::LE; break;
01268   case ISD::SETNE:
01269   case ISD::SETUNE: CondCode = ARMCC::NE; break;
01270   }
01271 }
01272 
01273 //===----------------------------------------------------------------------===//
01274 //                      Calling Convention Implementation
01275 //===----------------------------------------------------------------------===//
01276 
01277 #include "ARMGenCallingConv.inc"
01278 
01279 /// getEffectiveCallingConv - Get the effective calling convention, taking into
01280 /// account presence of floating point hardware and calling convention
01281 /// limitations, such as support for variadic functions.
01282 CallingConv::ID
01283 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
01284                                            bool isVarArg) const {
01285   switch (CC) {
01286   default:
01287     llvm_unreachable("Unsupported calling convention");
01288   case CallingConv::ARM_AAPCS:
01289   case CallingConv::ARM_APCS:
01290   case CallingConv::GHC:
01291     return CC;
01292   case CallingConv::ARM_AAPCS_VFP:
01293     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
01294   case CallingConv::C:
01295     if (!Subtarget->isAAPCS_ABI())
01296       return CallingConv::ARM_APCS;
01297     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
01298              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
01299              !isVarArg)
01300       return CallingConv::ARM_AAPCS_VFP;
01301     else
01302       return CallingConv::ARM_AAPCS;
01303   case CallingConv::Fast:
01304     if (!Subtarget->isAAPCS_ABI()) {
01305       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
01306         return CallingConv::Fast;
01307       return CallingConv::ARM_APCS;
01308     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
01309       return CallingConv::ARM_AAPCS_VFP;
01310     else
01311       return CallingConv::ARM_AAPCS;
01312   }
01313 }
01314 
01315 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
01316 /// CallingConvention.
01317 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
01318                                                  bool Return,
01319                                                  bool isVarArg) const {
01320   switch (getEffectiveCallingConv(CC, isVarArg)) {
01321   default:
01322     llvm_unreachable("Unsupported calling convention");
01323   case CallingConv::ARM_APCS:
01324     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
01325   case CallingConv::ARM_AAPCS:
01326     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
01327   case CallingConv::ARM_AAPCS_VFP:
01328     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
01329   case CallingConv::Fast:
01330     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
01331   case CallingConv::GHC:
01332     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
01333   }
01334 }
01335 
01336 /// LowerCallResult - Lower the result values of a call into the
01337 /// appropriate copies out of appropriate physical registers.
01338 SDValue
01339 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
01340                                    CallingConv::ID CallConv, bool isVarArg,
01341                                    const SmallVectorImpl<ISD::InputArg> &Ins,
01342                                    SDLoc dl, SelectionDAG &DAG,
01343                                    SmallVectorImpl<SDValue> &InVals,
01344                                    bool isThisReturn, SDValue ThisVal) const {
01345 
01346   // Assign locations to each value returned by this call.
01347   SmallVector<CCValAssign, 16> RVLocs;
01348   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
01349                     *DAG.getContext(), Call);
01350   CCInfo.AnalyzeCallResult(Ins,
01351                            CCAssignFnForNode(CallConv, /* Return*/ true,
01352                                              isVarArg));
01353 
01354   // Copy all of the result registers out of their specified physreg.
01355   for (unsigned i = 0; i != RVLocs.size(); ++i) {
01356     CCValAssign VA = RVLocs[i];
01357 
01358     // Pass 'this' value directly from the argument to return value, to avoid
01359     // reg unit interference
01360     if (i == 0 && isThisReturn) {
01361       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
01362              "unexpected return calling convention register assignment");
01363       InVals.push_back(ThisVal);
01364       continue;
01365     }
01366 
01367     SDValue Val;
01368     if (VA.needsCustom()) {
01369       // Handle f64 or half of a v2f64.
01370       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
01371                                       InFlag);
01372       Chain = Lo.getValue(1);
01373       InFlag = Lo.getValue(2);
01374       VA = RVLocs[++i]; // skip ahead to next loc
01375       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
01376                                       InFlag);
01377       Chain = Hi.getValue(1);
01378       InFlag = Hi.getValue(2);
01379       if (!Subtarget->isLittle())
01380         std::swap (Lo, Hi);
01381       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
01382 
01383       if (VA.getLocVT() == MVT::v2f64) {
01384         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
01385         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
01386                           DAG.getConstant(0, dl, MVT::i32));
01387 
01388         VA = RVLocs[++i]; // skip ahead to next loc
01389         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
01390         Chain = Lo.getValue(1);
01391         InFlag = Lo.getValue(2);
01392         VA = RVLocs[++i]; // skip ahead to next loc
01393         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
01394         Chain = Hi.getValue(1);
01395         InFlag = Hi.getValue(2);
01396         if (!Subtarget->isLittle())
01397           std::swap (Lo, Hi);
01398         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
01399         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
01400                           DAG.getConstant(1, dl, MVT::i32));
01401       }
01402     } else {
01403       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
01404                                InFlag);
01405       Chain = Val.getValue(1);
01406       InFlag = Val.getValue(2);
01407     }
01408 
01409     switch (VA.getLocInfo()) {
01410     default: llvm_unreachable("Unknown loc info!");
01411     case CCValAssign::Full: break;
01412     case CCValAssign::BCvt:
01413       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
01414       break;
01415     }
01416 
01417     InVals.push_back(Val);
01418   }
01419 
01420   return Chain;
01421 }
01422 
01423 /// LowerMemOpCallTo - Store the argument to the stack.
01424 SDValue
01425 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
01426                                     SDValue StackPtr, SDValue Arg,
01427                                     SDLoc dl, SelectionDAG &DAG,
01428                                     const CCValAssign &VA,
01429                                     ISD::ArgFlagsTy Flags) const {
01430   unsigned LocMemOffset = VA.getLocMemOffset();
01431   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
01432   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
01433   return DAG.getStore(Chain, dl, Arg, PtrOff,
01434                       MachinePointerInfo::getStack(LocMemOffset),
01435                       false, false, 0);
01436 }
01437 
01438 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
01439                                          SDValue Chain, SDValue &Arg,
01440                                          RegsToPassVector &RegsToPass,
01441                                          CCValAssign &VA, CCValAssign &NextVA,
01442                                          SDValue &StackPtr,
01443                                          SmallVectorImpl<SDValue> &MemOpChains,
01444                                          ISD::ArgFlagsTy Flags) const {
01445 
01446   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
01447                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
01448   unsigned id = Subtarget->isLittle() ? 0 : 1;
01449   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
01450 
01451   if (NextVA.isRegLoc())
01452     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
01453   else {
01454     assert(NextVA.isMemLoc());
01455     if (!StackPtr.getNode())
01456       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
01457 
01458     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
01459                                            dl, DAG, NextVA,
01460                                            Flags));
01461   }
01462 }
01463 
01464 /// LowerCall - Lowering a call into a callseq_start <-
01465 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
01466 /// nodes.
01467 SDValue
01468 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
01469                              SmallVectorImpl<SDValue> &InVals) const {
01470   SelectionDAG &DAG                     = CLI.DAG;
01471   SDLoc &dl                             = CLI.DL;
01472   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
01473   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
01474   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
01475   SDValue Chain                         = CLI.Chain;
01476   SDValue Callee                        = CLI.Callee;
01477   bool &isTailCall                      = CLI.IsTailCall;
01478   CallingConv::ID CallConv              = CLI.CallConv;
01479   bool doesNotRet                       = CLI.DoesNotReturn;
01480   bool isVarArg                         = CLI.IsVarArg;
01481 
01482   MachineFunction &MF = DAG.getMachineFunction();
01483   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
01484   bool isThisReturn   = false;
01485   bool isSibCall      = false;
01486   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
01487 
01488   // Disable tail calls if they're not supported.
01489   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
01490     isTailCall = false;
01491 
01492   if (isTailCall) {
01493     // Check if it's really possible to do a tail call.
01494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
01495                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
01496                                                    Outs, OutVals, Ins, DAG);
01497     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
01498       report_fatal_error("failed to perform tail call elimination on a call "
01499                          "site marked musttail");
01500     // We don't support GuaranteedTailCallOpt for ARM, only automatically
01501     // detected sibcalls.
01502     if (isTailCall) {
01503       ++NumTailCalls;
01504       isSibCall = true;
01505     }
01506   }
01507 
01508   // Analyze operands of the call, assigning locations to each operand.
01509   SmallVector<CCValAssign, 16> ArgLocs;
01510   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
01511                     *DAG.getContext(), Call);
01512   CCInfo.AnalyzeCallOperands(Outs,
01513                              CCAssignFnForNode(CallConv, /* Return*/ false,
01514                                                isVarArg));
01515 
01516   // Get a count of how many bytes are to be pushed on the stack.
01517   unsigned NumBytes = CCInfo.getNextStackOffset();
01518 
01519   // For tail calls, memory operands are available in our caller's stack.
01520   if (isSibCall)
01521     NumBytes = 0;
01522 
01523   // Adjust the stack pointer for the new arguments...
01524   // These operations are automatically eliminated by the prolog/epilog pass
01525   if (!isSibCall)
01526     Chain = DAG.getCALLSEQ_START(Chain,
01527                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
01528 
01529   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
01530 
01531   RegsToPassVector RegsToPass;
01532   SmallVector<SDValue, 8> MemOpChains;
01533 
01534   // Walk the register/memloc assignments, inserting copies/loads.  In the case
01535   // of tail call optimization, arguments are handled later.
01536   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
01537        i != e;
01538        ++i, ++realArgIdx) {
01539     CCValAssign &VA = ArgLocs[i];
01540     SDValue Arg = OutVals[realArgIdx];
01541     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
01542     bool isByVal = Flags.isByVal();
01543 
01544     // Promote the value if needed.
01545     switch (VA.getLocInfo()) {
01546     default: llvm_unreachable("Unknown loc info!");
01547     case CCValAssign::Full: break;
01548     case CCValAssign::SExt:
01549       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
01550       break;
01551     case CCValAssign::ZExt:
01552       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
01553       break;
01554     case CCValAssign::AExt:
01555       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
01556       break;
01557     case CCValAssign::BCvt:
01558       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
01559       break;
01560     }
01561 
01562     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
01563     if (VA.needsCustom()) {
01564       if (VA.getLocVT() == MVT::v2f64) {
01565         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
01566                                   DAG.getConstant(0, dl, MVT::i32));
01567         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
01568                                   DAG.getConstant(1, dl, MVT::i32));
01569 
01570         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
01571                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
01572 
01573         VA = ArgLocs[++i]; // skip ahead to next loc
01574         if (VA.isRegLoc()) {
01575           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
01576                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
01577         } else {
01578           assert(VA.isMemLoc());
01579 
01580           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
01581                                                  dl, DAG, VA, Flags));
01582         }
01583       } else {
01584         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
01585                          StackPtr, MemOpChains, Flags);
01586       }
01587     } else if (VA.isRegLoc()) {
01588       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
01589         assert(VA.getLocVT() == MVT::i32 &&
01590                "unexpected calling convention register assignment");
01591         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
01592                "unexpected use of 'returned'");
01593         isThisReturn = true;
01594       }
01595       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
01596     } else if (isByVal) {
01597       assert(VA.isMemLoc());
01598       unsigned offset = 0;
01599 
01600       // True if this byval aggregate will be split between registers
01601       // and memory.
01602       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
01603       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
01604 
01605       if (CurByValIdx < ByValArgsCount) {
01606 
01607         unsigned RegBegin, RegEnd;
01608         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
01609 
01610         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01611         unsigned int i, j;
01612         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
01613           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
01614           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
01615           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
01616                                      MachinePointerInfo(),
01617                                      false, false, false,
01618                                      DAG.InferPtrAlignment(AddArg));
01619           MemOpChains.push_back(Load.getValue(1));
01620           RegsToPass.push_back(std::make_pair(j, Load));
01621         }
01622 
01623         // If parameter size outsides register area, "offset" value
01624         // helps us to calculate stack slot for remained part properly.
01625         offset = RegEnd - RegBegin;
01626 
01627         CCInfo.nextInRegsParam();
01628       }
01629 
01630       if (Flags.getByValSize() > 4*offset) {
01631         unsigned LocMemOffset = VA.getLocMemOffset();
01632         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
01633         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
01634                                   StkPtrOff);
01635         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
01636         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
01637         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
01638                                            MVT::i32);
01639         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
01640                                             MVT::i32);
01641 
01642         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
01643         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
01644         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
01645                                           Ops));
01646       }
01647     } else if (!isSibCall) {
01648       assert(VA.isMemLoc());
01649 
01650       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
01651                                              dl, DAG, VA, Flags));
01652     }
01653   }
01654 
01655   if (!MemOpChains.empty())
01656     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
01657 
01658   // Build a sequence of copy-to-reg nodes chained together with token chain
01659   // and flag operands which copy the outgoing args into the appropriate regs.
01660   SDValue InFlag;
01661   // Tail call byval lowering might overwrite argument registers so in case of
01662   // tail call optimization the copies to registers are lowered later.
01663   if (!isTailCall)
01664     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01665       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
01666                                RegsToPass[i].second, InFlag);
01667       InFlag = Chain.getValue(1);
01668     }
01669 
01670   // For tail calls lower the arguments to the 'real' stack slot.
01671   if (isTailCall) {
01672     // Force all the incoming stack arguments to be loaded from the stack
01673     // before any new outgoing arguments are stored to the stack, because the
01674     // outgoing stack slots may alias the incoming argument stack slots, and
01675     // the alias isn't otherwise explicit. This is slightly more conservative
01676     // than necessary, because it means that each store effectively depends
01677     // on every argument instead of just those arguments it would clobber.
01678 
01679     // Do not flag preceding copytoreg stuff together with the following stuff.
01680     InFlag = SDValue();
01681     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01682       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
01683                                RegsToPass[i].second, InFlag);
01684       InFlag = Chain.getValue(1);
01685     }
01686     InFlag = SDValue();
01687   }
01688 
01689   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
01690   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
01691   // node so that legalize doesn't hack it.
01692   bool isDirect = false;
01693   bool isARMFunc = false;
01694   bool isLocalARMFunc = false;
01695   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01696 
01697   if (EnableARMLongCalls) {
01698     assert((Subtarget->isTargetWindows() ||
01699             getTargetMachine().getRelocationModel() == Reloc::Static) &&
01700            "long-calls with non-static relocation model!");
01701     // Handle a global address or an external symbol. If it's not one of
01702     // those, the target's already in a register, so we don't need to do
01703     // anything extra.
01704     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01705       const GlobalValue *GV = G->getGlobal();
01706       // Create a constant pool entry for the callee address
01707       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01708       ARMConstantPoolValue *CPV =
01709         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
01710 
01711       // Get the address of the callee into a register
01712       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01713       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01714       Callee = DAG.getLoad(getPointerTy(), dl,
01715                            DAG.getEntryNode(), CPAddr,
01716                            MachinePointerInfo::getConstantPool(),
01717                            false, false, false, 0);
01718     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
01719       const char *Sym = S->getSymbol();
01720 
01721       // Create a constant pool entry for the callee address
01722       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01723       ARMConstantPoolValue *CPV =
01724         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
01725                                       ARMPCLabelIndex, 0);
01726       // Get the address of the callee into a register
01727       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01728       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01729       Callee = DAG.getLoad(getPointerTy(), dl,
01730                            DAG.getEntryNode(), CPAddr,
01731                            MachinePointerInfo::getConstantPool(),
01732                            false, false, false, 0);
01733     }
01734   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01735     const GlobalValue *GV = G->getGlobal();
01736     isDirect = true;
01737     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
01738     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
01739                    getTargetMachine().getRelocationModel() != Reloc::Static;
01740     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
01741     // ARM call to a local ARM function is predicable.
01742     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
01743     // tBX takes a register source operand.
01744     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
01745       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
01746       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
01747                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
01748                                                       0, ARMII::MO_NONLAZY));
01749       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
01750                            MachinePointerInfo::getGOT(), false, false, true, 0);
01751     } else if (Subtarget->isTargetCOFF()) {
01752       assert(Subtarget->isTargetWindows() &&
01753              "Windows is the only supported COFF target");
01754       unsigned TargetFlags = GV->hasDLLImportStorageClass()
01755                                  ? ARMII::MO_DLLIMPORT
01756                                  : ARMII::MO_NO_FLAG;
01757       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
01758                                           TargetFlags);
01759       if (GV->hasDLLImportStorageClass())
01760         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
01761                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
01762                                          Callee), MachinePointerInfo::getGOT(),
01763                              false, false, false, 0);
01764     } else {
01765       // On ELF targets for PIC code, direct calls should go through the PLT
01766       unsigned OpFlags = 0;
01767       if (Subtarget->isTargetELF() &&
01768           getTargetMachine().getRelocationModel() == Reloc::PIC_)
01769         OpFlags = ARMII::MO_PLT;
01770       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
01771     }
01772   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
01773     isDirect = true;
01774     bool isStub = Subtarget->isTargetMachO() &&
01775                   getTargetMachine().getRelocationModel() != Reloc::Static;
01776     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
01777     // tBX takes a register source operand.
01778     const char *Sym = S->getSymbol();
01779     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
01780       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01781       ARMConstantPoolValue *CPV =
01782         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
01783                                       ARMPCLabelIndex, 4);
01784       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01785       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01786       Callee = DAG.getLoad(getPointerTy(), dl,
01787                            DAG.getEntryNode(), CPAddr,
01788                            MachinePointerInfo::getConstantPool(),
01789                            false, false, false, 0);
01790       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
01791       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
01792                            getPointerTy(), Callee, PICLabel);
01793     } else {
01794       unsigned OpFlags = 0;
01795       // On ELF targets for PIC code, direct calls should go through the PLT
01796       if (Subtarget->isTargetELF() &&
01797                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
01798         OpFlags = ARMII::MO_PLT;
01799       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
01800     }
01801   }
01802 
01803   // FIXME: handle tail calls differently.
01804   unsigned CallOpc;
01805   bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
01806   if (Subtarget->isThumb()) {
01807     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
01808       CallOpc = ARMISD::CALL_NOLINK;
01809     else
01810       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
01811   } else {
01812     if (!isDirect && !Subtarget->hasV5TOps())
01813       CallOpc = ARMISD::CALL_NOLINK;
01814     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
01815                // Emit regular call when code size is the priority
01816                !HasMinSizeAttr)
01817       // "mov lr, pc; b _foo" to avoid confusing the RSP
01818       CallOpc = ARMISD::CALL_NOLINK;
01819     else
01820       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
01821   }
01822 
01823   std::vector<SDValue> Ops;
01824   Ops.push_back(Chain);
01825   Ops.push_back(Callee);
01826 
01827   // Add argument registers to the end of the list so that they are known live
01828   // into the call.
01829   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
01830     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
01831                                   RegsToPass[i].second.getValueType()));
01832 
01833   // Add a register mask operand representing the call-preserved registers.
01834   if (!isTailCall) {
01835     const uint32_t *Mask;
01836     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
01837     if (isThisReturn) {
01838       // For 'this' returns, use the R0-preserving mask if applicable
01839       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
01840       if (!Mask) {
01841         // Set isThisReturn to false if the calling convention is not one that
01842         // allows 'returned' to be modeled in this way, so LowerCallResult does
01843         // not try to pass 'this' straight through
01844         isThisReturn = false;
01845         Mask = ARI->getCallPreservedMask(MF, CallConv);
01846       }
01847     } else
01848       Mask = ARI->getCallPreservedMask(MF, CallConv);
01849 
01850     assert(Mask && "Missing call preserved mask for calling convention");
01851     Ops.push_back(DAG.getRegisterMask(Mask));
01852   }
01853 
01854   if (InFlag.getNode())
01855     Ops.push_back(InFlag);
01856 
01857   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
01858   if (isTailCall) {
01859     MF.getFrameInfo()->setHasTailCall();
01860     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
01861   }
01862 
01863   // Returns a chain and a flag for retval copy to use.
01864   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
01865   InFlag = Chain.getValue(1);
01866 
01867   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
01868                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
01869   if (!Ins.empty())
01870     InFlag = Chain.getValue(1);
01871 
01872   // Handle result values, copying them out of physregs into vregs that we
01873   // return.
01874   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
01875                          InVals, isThisReturn,
01876                          isThisReturn ? OutVals[0] : SDValue());
01877 }
01878 
01879 /// HandleByVal - Every parameter *after* a byval parameter is passed
01880 /// on the stack.  Remember the next parameter register to allocate,
01881 /// and then confiscate the rest of the parameter registers to insure
01882 /// this.
01883 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
01884                                     unsigned Align) const {
01885   assert((State->getCallOrPrologue() == Prologue ||
01886           State->getCallOrPrologue() == Call) &&
01887          "unhandled ParmContext");
01888 
01889   // Byval (as with any stack) slots are always at least 4 byte aligned.
01890   Align = std::max(Align, 4U);
01891 
01892   unsigned Reg = State->AllocateReg(GPRArgRegs);
01893   if (!Reg)
01894     return;
01895 
01896   unsigned AlignInRegs = Align / 4;
01897   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
01898   for (unsigned i = 0; i < Waste; ++i)
01899     Reg = State->AllocateReg(GPRArgRegs);
01900 
01901   if (!Reg)
01902     return;
01903 
01904   unsigned Excess = 4 * (ARM::R4 - Reg);
01905 
01906   // Special case when NSAA != SP and parameter size greater than size of
01907   // all remained GPR regs. In that case we can't split parameter, we must
01908   // send it to stack. We also must set NCRN to R4, so waste all
01909   // remained registers.
01910   const unsigned NSAAOffset = State->getNextStackOffset();
01911   if (NSAAOffset != 0 && Size > Excess) {
01912     while (State->AllocateReg(GPRArgRegs))
01913       ;
01914     return;
01915   }
01916 
01917   // First register for byval parameter is the first register that wasn't
01918   // allocated before this method call, so it would be "reg".
01919   // If parameter is small enough to be saved in range [reg, r4), then
01920   // the end (first after last) register would be reg + param-size-in-regs,
01921   // else parameter would be splitted between registers and stack,
01922   // end register would be r4 in this case.
01923   unsigned ByValRegBegin = Reg;
01924   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
01925   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
01926   // Note, first register is allocated in the beginning of function already,
01927   // allocate remained amount of registers we need.
01928   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
01929     State->AllocateReg(GPRArgRegs);
01930   // A byval parameter that is split between registers and memory needs its
01931   // size truncated here.
01932   // In the case where the entire structure fits in registers, we set the
01933   // size in memory to zero.
01934   Size = std::max<int>(Size - Excess, 0);
01935 }
01936 
01937 /// MatchingStackOffset - Return true if the given stack call argument is
01938 /// already available in the same position (relatively) of the caller's
01939 /// incoming argument stack.
01940 static
01941 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
01942                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
01943                          const TargetInstrInfo *TII) {
01944   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
01945   int FI = INT_MAX;
01946   if (Arg.getOpcode() == ISD::CopyFromReg) {
01947     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
01948     if (!TargetRegisterInfo::isVirtualRegister(VR))
01949       return false;
01950     MachineInstr *Def = MRI->getVRegDef(VR);
01951     if (!Def)
01952       return false;
01953     if (!Flags.isByVal()) {
01954       if (!TII->isLoadFromStackSlot(Def, FI))
01955         return false;
01956     } else {
01957       return false;
01958     }
01959   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
01960     if (Flags.isByVal())
01961       // ByVal argument is passed in as a pointer but it's now being
01962       // dereferenced. e.g.
01963       // define @foo(%struct.X* %A) {
01964       //   tail call @bar(%struct.X* byval %A)
01965       // }
01966       return false;
01967     SDValue Ptr = Ld->getBasePtr();
01968     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
01969     if (!FINode)
01970       return false;
01971     FI = FINode->getIndex();
01972   } else
01973     return false;
01974 
01975   assert(FI != INT_MAX);
01976   if (!MFI->isFixedObjectIndex(FI))
01977     return false;
01978   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
01979 }
01980 
01981 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
01982 /// for tail call optimization. Targets which want to do tail call
01983 /// optimization should implement this function.
01984 bool
01985 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
01986                                                      CallingConv::ID CalleeCC,
01987                                                      bool isVarArg,
01988                                                      bool isCalleeStructRet,
01989                                                      bool isCallerStructRet,
01990                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
01991                                     const SmallVectorImpl<SDValue> &OutVals,
01992                                     const SmallVectorImpl<ISD::InputArg> &Ins,
01993                                                      SelectionDAG& DAG) const {
01994   const Function *CallerF = DAG.getMachineFunction().getFunction();
01995   CallingConv::ID CallerCC = CallerF->getCallingConv();
01996   bool CCMatch = CallerCC == CalleeCC;
01997 
01998   // Look for obvious safe cases to perform tail call optimization that do not
01999   // require ABI changes. This is what gcc calls sibcall.
02000 
02001   // Do not sibcall optimize vararg calls unless the call site is not passing
02002   // any arguments.
02003   if (isVarArg && !Outs.empty())
02004     return false;
02005 
02006   // Exception-handling functions need a special set of instructions to indicate
02007   // a return to the hardware. Tail-calling another function would probably
02008   // break this.
02009   if (CallerF->hasFnAttribute("interrupt"))
02010     return false;
02011 
02012   // Also avoid sibcall optimization if either caller or callee uses struct
02013   // return semantics.
02014   if (isCalleeStructRet || isCallerStructRet)
02015     return false;
02016 
02017   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
02018   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
02019   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
02020   // support in the assembler and linker to be used. This would need to be
02021   // fixed to fully support tail calls in Thumb1.
02022   //
02023   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
02024   // LR.  This means if we need to reload LR, it takes an extra instructions,
02025   // which outweighs the value of the tail call; but here we don't know yet
02026   // whether LR is going to be used.  Probably the right approach is to
02027   // generate the tail call here and turn it back into CALL/RET in
02028   // emitEpilogue if LR is used.
02029 
02030   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
02031   // but we need to make sure there are enough registers; the only valid
02032   // registers are the 4 used for parameters.  We don't currently do this
02033   // case.
02034   if (Subtarget->isThumb1Only())
02035     return false;
02036 
02037   // Externally-defined functions with weak linkage should not be
02038   // tail-called on ARM when the OS does not support dynamic
02039   // pre-emption of symbols, as the AAELF spec requires normal calls
02040   // to undefined weak functions to be replaced with a NOP or jump to the
02041   // next instruction. The behaviour of branch instructions in this
02042   // situation (as used for tail calls) is implementation-defined, so we
02043   // cannot rely on the linker replacing the tail call with a return.
02044   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
02045     const GlobalValue *GV = G->getGlobal();
02046     const Triple &TT = getTargetMachine().getTargetTriple();
02047     if (GV->hasExternalWeakLinkage() &&
02048         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
02049       return false;
02050   }
02051 
02052   // If the calling conventions do not match, then we'd better make sure the
02053   // results are returned in the same way as what the caller expects.
02054   if (!CCMatch) {
02055     SmallVector<CCValAssign, 16> RVLocs1;
02056     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
02057                        *DAG.getContext(), Call);
02058     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
02059 
02060     SmallVector<CCValAssign, 16> RVLocs2;
02061     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
02062                        *DAG.getContext(), Call);
02063     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
02064 
02065     if (RVLocs1.size() != RVLocs2.size())
02066       return false;
02067     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
02068       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
02069         return false;
02070       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
02071         return false;
02072       if (RVLocs1[i].isRegLoc()) {
02073         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
02074           return false;
02075       } else {
02076         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
02077           return false;
02078       }
02079     }
02080   }
02081 
02082   // If Caller's vararg or byval argument has been split between registers and
02083   // stack, do not perform tail call, since part of the argument is in caller's
02084   // local frame.
02085   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
02086                                       getInfo<ARMFunctionInfo>();
02087   if (AFI_Caller->getArgRegsSaveSize())
02088     return false;
02089 
02090   // If the callee takes no arguments then go on to check the results of the
02091   // call.
02092   if (!Outs.empty()) {
02093     // Check if stack adjustment is needed. For now, do not do this if any
02094     // argument is passed on the stack.
02095     SmallVector<CCValAssign, 16> ArgLocs;
02096     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
02097                       *DAG.getContext(), Call);
02098     CCInfo.AnalyzeCallOperands(Outs,
02099                                CCAssignFnForNode(CalleeCC, false, isVarArg));
02100     if (CCInfo.getNextStackOffset()) {
02101       MachineFunction &MF = DAG.getMachineFunction();
02102 
02103       // Check if the arguments are already laid out in the right way as
02104       // the caller's fixed stack objects.
02105       MachineFrameInfo *MFI = MF.getFrameInfo();
02106       const MachineRegisterInfo *MRI = &MF.getRegInfo();
02107       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
02108       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
02109            i != e;
02110            ++i, ++realArgIdx) {
02111         CCValAssign &VA = ArgLocs[i];
02112         EVT RegVT = VA.getLocVT();
02113         SDValue Arg = OutVals[realArgIdx];
02114         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
02115         if (VA.getLocInfo() == CCValAssign::Indirect)
02116           return false;
02117         if (VA.needsCustom()) {
02118           // f64 and vector types are split into multiple registers or
02119           // register/stack-slot combinations.  The types will not match
02120           // the registers; give up on memory f64 refs until we figure
02121           // out what to do about this.
02122           if (!VA.isRegLoc())
02123             return false;
02124           if (!ArgLocs[++i].isRegLoc())
02125             return false;
02126           if (RegVT == MVT::v2f64) {
02127             if (!ArgLocs[++i].isRegLoc())
02128               return false;
02129             if (!ArgLocs[++i].isRegLoc())
02130               return false;
02131           }
02132         } else if (!VA.isRegLoc()) {
02133           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
02134                                    MFI, MRI, TII))
02135             return false;
02136         }
02137       }
02138     }
02139   }
02140 
02141   return true;
02142 }
02143 
02144 bool
02145 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
02146                                   MachineFunction &MF, bool isVarArg,
02147                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
02148                                   LLVMContext &Context) const {
02149   SmallVector<CCValAssign, 16> RVLocs;
02150   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
02151   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
02152                                                     isVarArg));
02153 }
02154 
02155 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
02156                                     SDLoc DL, SelectionDAG &DAG) {
02157   const MachineFunction &MF = DAG.getMachineFunction();
02158   const Function *F = MF.getFunction();
02159 
02160   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
02161 
02162   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
02163   // version of the "preferred return address". These offsets affect the return
02164   // instruction if this is a return from PL1 without hypervisor extensions.
02165   //    IRQ/FIQ: +4     "subs pc, lr, #4"
02166   //    SWI:     0      "subs pc, lr, #0"
02167   //    ABORT:   +4     "subs pc, lr, #4"
02168   //    UNDEF:   +4/+2  "subs pc, lr, #0"
02169   // UNDEF varies depending on where the exception came from ARM or Thumb
02170   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
02171 
02172   int64_t LROffset;
02173   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
02174       IntKind == "ABORT")
02175     LROffset = 4;
02176   else if (IntKind == "SWI" || IntKind == "UNDEF")
02177     LROffset = 0;
02178   else
02179     report_fatal_error("Unsupported interrupt attribute. If present, value "
02180                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
02181 
02182   RetOps.insert(RetOps.begin() + 1,
02183                 DAG.getConstant(LROffset, DL, MVT::i32, false));
02184 
02185   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
02186 }
02187 
02188 SDValue
02189 ARMTargetLowering::LowerReturn(SDValue Chain,
02190                                CallingConv::ID CallConv, bool isVarArg,
02191                                const SmallVectorImpl<ISD::OutputArg> &Outs,
02192                                const SmallVectorImpl<SDValue> &OutVals,
02193                                SDLoc dl, SelectionDAG &DAG) const {
02194 
02195   // CCValAssign - represent the assignment of the return value to a location.
02196   SmallVector<CCValAssign, 16> RVLocs;
02197 
02198   // CCState - Info about the registers and stack slots.
02199   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
02200                     *DAG.getContext(), Call);
02201 
02202   // Analyze outgoing return values.
02203   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
02204                                                isVarArg));
02205 
02206   SDValue Flag;
02207   SmallVector<SDValue, 4> RetOps;
02208   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
02209   bool isLittleEndian = Subtarget->isLittle();
02210 
02211   MachineFunction &MF = DAG.getMachineFunction();
02212   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02213   AFI->setReturnRegsCount(RVLocs.size());
02214 
02215   // Copy the result values into the output registers.
02216   for (unsigned i = 0, realRVLocIdx = 0;
02217        i != RVLocs.size();
02218        ++i, ++realRVLocIdx) {
02219     CCValAssign &VA = RVLocs[i];
02220     assert(VA.isRegLoc() && "Can only return in registers!");
02221 
02222     SDValue Arg = OutVals[realRVLocIdx];
02223 
02224     switch (VA.getLocInfo()) {
02225     default: llvm_unreachable("Unknown loc info!");
02226     case CCValAssign::Full: break;
02227     case CCValAssign::BCvt:
02228       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
02229       break;
02230     }
02231 
02232     if (VA.needsCustom()) {
02233       if (VA.getLocVT() == MVT::v2f64) {
02234         // Extract the first half and return it in two registers.
02235         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
02236                                    DAG.getConstant(0, dl, MVT::i32));
02237         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
02238                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
02239 
02240         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02241                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
02242                                  Flag);
02243         Flag = Chain.getValue(1);
02244         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02245         VA = RVLocs[++i]; // skip ahead to next loc
02246         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02247                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
02248                                  Flag);
02249         Flag = Chain.getValue(1);
02250         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02251         VA = RVLocs[++i]; // skip ahead to next loc
02252 
02253         // Extract the 2nd half and fall through to handle it as an f64 value.
02254         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
02255                           DAG.getConstant(1, dl, MVT::i32));
02256       }
02257       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
02258       // available.
02259       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
02260                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
02261       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02262                                fmrrd.getValue(isLittleEndian ? 0 : 1),
02263                                Flag);
02264       Flag = Chain.getValue(1);
02265       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02266       VA = RVLocs[++i]; // skip ahead to next loc
02267       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02268                                fmrrd.getValue(isLittleEndian ? 1 : 0),
02269                                Flag);
02270     } else
02271       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
02272 
02273     // Guarantee that all emitted copies are
02274     // stuck together, avoiding something bad.
02275     Flag = Chain.getValue(1);
02276     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02277   }
02278 
02279   // Update chain and glue.
02280   RetOps[0] = Chain;
02281   if (Flag.getNode())
02282     RetOps.push_back(Flag);
02283 
02284   // CPUs which aren't M-class use a special sequence to return from
02285   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
02286   // though we use "subs pc, lr, #N").
02287   //
02288   // M-class CPUs actually use a normal return sequence with a special
02289   // (hardware-provided) value in LR, so the normal code path works.
02290   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
02291       !Subtarget->isMClass()) {
02292     if (Subtarget->isThumb1Only())
02293       report_fatal_error("interrupt attribute is not supported in Thumb1");
02294     return LowerInterruptReturn(RetOps, dl, DAG);
02295   }
02296 
02297   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
02298 }
02299 
02300 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
02301   if (N->getNumValues() != 1)
02302     return false;
02303   if (!N->hasNUsesOfValue(1, 0))
02304     return false;
02305 
02306   SDValue TCChain = Chain;
02307   SDNode *Copy = *N->use_begin();
02308   if (Copy->getOpcode() == ISD::CopyToReg) {
02309     // If the copy has a glue operand, we conservatively assume it isn't safe to
02310     // perform a tail call.
02311     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
02312       return false;
02313     TCChain = Copy->getOperand(0);
02314   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
02315     SDNode *VMov = Copy;
02316     // f64 returned in a pair of GPRs.
02317     SmallPtrSet<SDNode*, 2> Copies;
02318     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
02319          UI != UE; ++UI) {
02320       if (UI->getOpcode() != ISD::CopyToReg)
02321         return false;
02322       Copies.insert(*UI);
02323     }
02324     if (Copies.size() > 2)
02325       return false;
02326 
02327     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
02328          UI != UE; ++UI) {
02329       SDValue UseChain = UI->getOperand(0);
02330       if (Copies.count(UseChain.getNode()))
02331         // Second CopyToReg
02332         Copy = *UI;
02333       else {
02334         // We are at the top of this chain.
02335         // If the copy has a glue operand, we conservatively assume it
02336         // isn't safe to perform a tail call.
02337         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
02338           return false;
02339         // First CopyToReg
02340         TCChain = UseChain;
02341       }
02342     }
02343   } else if (Copy->getOpcode() == ISD::BITCAST) {
02344     // f32 returned in a single GPR.
02345     if (!Copy->hasOneUse())
02346       return false;
02347     Copy = *Copy->use_begin();
02348     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
02349       return false;
02350     // If the copy has a glue operand, we conservatively assume it isn't safe to
02351     // perform a tail call.
02352     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
02353       return false;
02354     TCChain = Copy->getOperand(0);
02355   } else {
02356     return false;
02357   }
02358 
02359   bool HasRet = false;
02360   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
02361        UI != UE; ++UI) {
02362     if (UI->getOpcode() != ARMISD::RET_FLAG &&
02363         UI->getOpcode() != ARMISD::INTRET_FLAG)
02364       return false;
02365     HasRet = true;
02366   }
02367 
02368   if (!HasRet)
02369     return false;
02370 
02371   Chain = TCChain;
02372   return true;
02373 }
02374 
02375 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
02376   if (!Subtarget->supportsTailCall())
02377     return false;
02378 
02379   auto Attr =
02380       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
02381   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
02382     return false;
02383 
02384   return !Subtarget->isThumb1Only();
02385 }
02386 
02387 // Trying to write a 64 bit value so need to split into two 32 bit values first,
02388 // and pass the lower and high parts through.
02389 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
02390   SDLoc DL(Op);
02391   SDValue WriteValue = Op->getOperand(2);
02392 
02393   // This function is only supposed to be called for i64 type argument.
02394   assert(WriteValue.getValueType() == MVT::i64
02395           && "LowerWRITE_REGISTER called for non-i64 type argument.");
02396 
02397   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
02398                            DAG.getConstant(0, DL, MVT::i32));
02399   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
02400                            DAG.getConstant(1, DL, MVT::i32));
02401   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
02402   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
02403 }
02404 
02405 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
02406 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
02407 // one of the above mentioned nodes. It has to be wrapped because otherwise
02408 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
02409 // be used to form addressing mode. These wrapped nodes will be selected
02410 // into MOVi.
02411 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
02412   EVT PtrVT = Op.getValueType();
02413   // FIXME there is no actual debug info here
02414   SDLoc dl(Op);
02415   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
02416   SDValue Res;
02417   if (CP->isMachineConstantPoolEntry())
02418     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
02419                                     CP->getAlignment());
02420   else
02421     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
02422                                     CP->getAlignment());
02423   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
02424 }
02425 
02426 unsigned ARMTargetLowering::getJumpTableEncoding() const {
02427   return MachineJumpTableInfo::EK_Inline;
02428 }
02429 
02430 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
02431                                              SelectionDAG &DAG) const {
02432   MachineFunction &MF = DAG.getMachineFunction();
02433   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02434   unsigned ARMPCLabelIndex = 0;
02435   SDLoc DL(Op);
02436   EVT PtrVT = getPointerTy();
02437   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
02438   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02439   SDValue CPAddr;
02440   if (RelocM == Reloc::Static) {
02441     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
02442   } else {
02443     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
02444     ARMPCLabelIndex = AFI->createPICLabelUId();
02445     ARMConstantPoolValue *CPV =
02446       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
02447                                       ARMCP::CPBlockAddress, PCAdj);
02448     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02449   }
02450   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
02451   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
02452                                MachinePointerInfo::getConstantPool(),
02453                                false, false, false, 0);
02454   if (RelocM == Reloc::Static)
02455     return Result;
02456   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
02457   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
02458 }
02459 
02460 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
02461 SDValue
02462 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
02463                                                  SelectionDAG &DAG) const {
02464   SDLoc dl(GA);
02465   EVT PtrVT = getPointerTy();
02466   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
02467   MachineFunction &MF = DAG.getMachineFunction();
02468   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02469   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02470   ARMConstantPoolValue *CPV =
02471     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
02472                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
02473   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02474   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
02475   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
02476                          MachinePointerInfo::getConstantPool(),
02477                          false, false, false, 0);
02478   SDValue Chain = Argument.getValue(1);
02479 
02480   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
02481   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
02482 
02483   // call __tls_get_addr.
02484   ArgListTy Args;
02485   ArgListEntry Entry;
02486   Entry.Node = Argument;
02487   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
02488   Args.push_back(Entry);
02489 
02490   // FIXME: is there useful debug info available here?
02491   TargetLowering::CallLoweringInfo CLI(DAG);
02492   CLI.setDebugLoc(dl).setChain(Chain)
02493     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
02494                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
02495                0);
02496 
02497   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
02498   return CallResult.first;
02499 }
02500 
02501 // Lower ISD::GlobalTLSAddress using the "initial exec" or
02502 // "local exec" model.
02503 SDValue
02504 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
02505                                         SelectionDAG &DAG,
02506                                         TLSModel::Model model) const {
02507   const GlobalValue *GV = GA->getGlobal();
02508   SDLoc dl(GA);
02509   SDValue Offset;
02510   SDValue Chain = DAG.getEntryNode();
02511   EVT PtrVT = getPointerTy();
02512   // Get the Thread Pointer
02513   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
02514 
02515   if (model == TLSModel::InitialExec) {
02516     MachineFunction &MF = DAG.getMachineFunction();
02517     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02518     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02519     // Initial exec model.
02520     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
02521     ARMConstantPoolValue *CPV =
02522       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
02523                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
02524                                       true);
02525     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02526     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
02527     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02528                          MachinePointerInfo::getConstantPool(),
02529                          false, false, false, 0);
02530     Chain = Offset.getValue(1);
02531 
02532     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
02533     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
02534 
02535     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02536                          MachinePointerInfo::getConstantPool(),
02537                          false, false, false, 0);
02538   } else {
02539     // local exec model
02540     assert(model == TLSModel::LocalExec);
02541     ARMConstantPoolValue *CPV =
02542       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
02543     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02544     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
02545     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02546                          MachinePointerInfo::getConstantPool(),
02547                          false, false, false, 0);
02548   }
02549 
02550   // The address of the thread local variable is the add of the thread
02551   // pointer with the offset of the variable.
02552   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
02553 }
02554 
02555 SDValue
02556 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
02557   // TODO: implement the "local dynamic" model
02558   assert(Subtarget->isTargetELF() &&
02559          "TLS not implemented for non-ELF targets");
02560   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
02561 
02562   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
02563 
02564   switch (model) {
02565     case TLSModel::GeneralDynamic:
02566     case TLSModel::LocalDynamic:
02567       return LowerToTLSGeneralDynamicModel(GA, DAG);
02568     case TLSModel::InitialExec:
02569     case TLSModel::LocalExec:
02570       return LowerToTLSExecModels(GA, DAG, model);
02571   }
02572   llvm_unreachable("bogus TLS model");
02573 }
02574 
02575 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
02576                                                  SelectionDAG &DAG) const {
02577   EVT PtrVT = getPointerTy();
02578   SDLoc dl(Op);
02579   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02580   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
02581     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
02582     ARMConstantPoolValue *CPV =
02583       ARMConstantPoolConstant::Create(GV,
02584                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
02585     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02586     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02587     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
02588                                  CPAddr,
02589                                  MachinePointerInfo::getConstantPool(),
02590                                  false, false, false, 0);
02591     SDValue Chain = Result.getValue(1);
02592     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
02593     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
02594     if (!UseGOTOFF)
02595       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
02596                            MachinePointerInfo::getGOT(),
02597                            false, false, false, 0);
02598     return Result;
02599   }
02600 
02601   // If we have T2 ops, we can materialize the address directly via movt/movw
02602   // pair. This is always cheaper.
02603   if (Subtarget->useMovt(DAG.getMachineFunction())) {
02604     ++NumMovwMovt;
02605     // FIXME: Once remat is capable of dealing with instructions with register
02606     // operands, expand this into two nodes.
02607     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
02608                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
02609   } else {
02610     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
02611     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02612     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02613                        MachinePointerInfo::getConstantPool(),
02614                        false, false, false, 0);
02615   }
02616 }
02617 
02618 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
02619                                                     SelectionDAG &DAG) const {
02620   EVT PtrVT = getPointerTy();
02621   SDLoc dl(Op);
02622   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02623   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02624 
02625   if (Subtarget->useMovt(DAG.getMachineFunction()))
02626     ++NumMovwMovt;
02627 
02628   // FIXME: Once remat is capable of dealing with instructions with register
02629   // operands, expand this into multiple nodes
02630   unsigned Wrapper =
02631       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
02632 
02633   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
02634   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
02635 
02636   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
02637     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
02638                          MachinePointerInfo::getGOT(), false, false, false, 0);
02639   return Result;
02640 }
02641 
02642 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
02643                                                      SelectionDAG &DAG) const {
02644   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
02645   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
02646          "Windows on ARM expects to use movw/movt");
02647 
02648   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02649   const ARMII::TOF TargetFlags =
02650     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
02651   EVT PtrVT = getPointerTy();
02652   SDValue Result;
02653   SDLoc DL(Op);
02654 
02655   ++NumMovwMovt;
02656 
02657   // FIXME: Once remat is capable of dealing with instructions with register
02658   // operands, expand this into two nodes.
02659   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
02660                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
02661                                                   TargetFlags));
02662   if (GV->hasDLLImportStorageClass())
02663     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
02664                          MachinePointerInfo::getGOT(), false, false, false, 0);
02665   return Result;
02666 }
02667 
02668 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
02669                                                     SelectionDAG &DAG) const {
02670   assert(Subtarget->isTargetELF() &&
02671          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
02672   MachineFunction &MF = DAG.getMachineFunction();
02673   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02674   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02675   EVT PtrVT = getPointerTy();
02676   SDLoc dl(Op);
02677   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
02678   ARMConstantPoolValue *CPV =
02679     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
02680                                   ARMPCLabelIndex, PCAdj);
02681   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02682   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02683   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02684                                MachinePointerInfo::getConstantPool(),
02685                                false, false, false, 0);
02686   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
02687   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
02688 }
02689 
02690 SDValue
02691 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
02692   SDLoc dl(Op);
02693   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
02694   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
02695                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
02696                      Op.getOperand(1), Val);
02697 }
02698 
02699 SDValue
02700 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
02701   SDLoc dl(Op);
02702   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
02703                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
02704 }
02705 
02706 SDValue
02707 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
02708                                           const ARMSubtarget *Subtarget) const {
02709   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
02710   SDLoc dl(Op);
02711   switch (IntNo) {
02712   default: return SDValue();    // Don't custom lower most intrinsics.
02713   case Intrinsic::arm_rbit: {
02714     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
02715            "RBIT intrinsic must have i32 type!");
02716     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
02717   }
02718   case Intrinsic::arm_thread_pointer: {
02719     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02720     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
02721   }
02722   case Intrinsic::eh_sjlj_lsda: {
02723     MachineFunction &MF = DAG.getMachineFunction();
02724     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02725     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02726     EVT PtrVT = getPointerTy();
02727     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02728     SDValue CPAddr;
02729     unsigned PCAdj = (RelocM != Reloc::PIC_)
02730       ? 0 : (Subtarget->isThumb() ? 4 : 8);
02731     ARMConstantPoolValue *CPV =
02732       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
02733                                       ARMCP::CPLSDA, PCAdj);
02734     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02735     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02736     SDValue Result =
02737       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02738                   MachinePointerInfo::getConstantPool(),
02739                   false, false, false, 0);
02740 
02741     if (RelocM == Reloc::PIC_) {
02742       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
02743       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
02744     }
02745     return Result;
02746   }
02747   case Intrinsic::arm_neon_vmulls:
02748   case Intrinsic::arm_neon_vmullu: {
02749     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
02750       ? ARMISD::VMULLs : ARMISD::VMULLu;
02751     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
02752                        Op.getOperand(1), Op.getOperand(2));
02753   }
02754   }
02755 }
02756 
02757 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
02758                                  const ARMSubtarget *Subtarget) {
02759   // FIXME: handle "fence singlethread" more efficiently.
02760   SDLoc dl(Op);
02761   if (!Subtarget->hasDataBarrier()) {
02762     // Some ARMv6 cpus can support data barriers with an mcr instruction.
02763     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
02764     // here.
02765     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
02766            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
02767     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
02768                        DAG.getConstant(0, dl, MVT::i32));
02769   }
02770 
02771   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
02772   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
02773   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
02774   if (Subtarget->isMClass()) {
02775     // Only a full system barrier exists in the M-class architectures.
02776     Domain = ARM_MB::SY;
02777   } else if (Subtarget->isSwift() && Ord == Release) {
02778     // Swift happens to implement ISHST barriers in a way that's compatible with
02779     // Release semantics but weaker than ISH so we'd be fools not to use
02780     // it. Beware: other processors probably don't!
02781     Domain = ARM_MB::ISHST;
02782   }
02783 
02784   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
02785                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
02786                      DAG.getConstant(Domain, dl, MVT::i32));
02787 }
02788 
02789 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
02790                              const ARMSubtarget *Subtarget) {
02791   // ARM pre v5TE and Thumb1 does not have preload instructions.
02792   if (!(Subtarget->isThumb2() ||
02793         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
02794     // Just preserve the chain.
02795     return Op.getOperand(0);
02796 
02797   SDLoc dl(Op);
02798   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
02799   if (!isRead &&
02800       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
02801     // ARMv7 with MP extension has PLDW.
02802     return Op.getOperand(0);
02803 
02804   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
02805   if (Subtarget->isThumb()) {
02806     // Invert the bits.
02807     isRead = ~isRead & 1;
02808     isData = ~isData & 1;
02809   }
02810 
02811   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
02812                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
02813                      DAG.getConstant(isData, dl, MVT::i32));
02814 }
02815 
02816 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
02817   MachineFunction &MF = DAG.getMachineFunction();
02818   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
02819 
02820   // vastart just stores the address of the VarArgsFrameIndex slot into the
02821   // memory location argument.
02822   SDLoc dl(Op);
02823   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02824   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02825   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02826   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
02827                       MachinePointerInfo(SV), false, false, 0);
02828 }
02829 
02830 SDValue
02831 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
02832                                         SDValue &Root, SelectionDAG &DAG,
02833                                         SDLoc dl) const {
02834   MachineFunction &MF = DAG.getMachineFunction();
02835   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02836 
02837   const TargetRegisterClass *RC;
02838   if (AFI->isThumb1OnlyFunction())
02839     RC = &ARM::tGPRRegClass;
02840   else
02841     RC = &ARM::GPRRegClass;
02842 
02843   // Transform the arguments stored in physical registers into virtual ones.
02844   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
02845   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
02846 
02847   SDValue ArgValue2;
02848   if (NextVA.isMemLoc()) {
02849     MachineFrameInfo *MFI = MF.getFrameInfo();
02850     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
02851 
02852     // Create load node to retrieve arguments from the stack.
02853     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
02854     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
02855                             MachinePointerInfo::getFixedStack(FI),
02856                             false, false, false, 0);
02857   } else {
02858     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
02859     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
02860   }
02861   if (!Subtarget->isLittle())
02862     std::swap (ArgValue, ArgValue2);
02863   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
02864 }
02865 
02866 // The remaining GPRs hold either the beginning of variable-argument
02867 // data, or the beginning of an aggregate passed by value (usually
02868 // byval).  Either way, we allocate stack slots adjacent to the data
02869 // provided by our caller, and store the unallocated registers there.
02870 // If this is a variadic function, the va_list pointer will begin with
02871 // these values; otherwise, this reassembles a (byval) structure that
02872 // was split between registers and memory.
02873 // Return: The frame index registers were stored into.
02874 int
02875 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
02876                                   SDLoc dl, SDValue &Chain,
02877                                   const Value *OrigArg,
02878                                   unsigned InRegsParamRecordIdx,
02879                                   int ArgOffset,
02880                                   unsigned ArgSize) const {
02881   // Currently, two use-cases possible:
02882   // Case #1. Non-var-args function, and we meet first byval parameter.
02883   //          Setup first unallocated register as first byval register;
02884   //          eat all remained registers
02885   //          (these two actions are performed by HandleByVal method).
02886   //          Then, here, we initialize stack frame with
02887   //          "store-reg" instructions.
02888   // Case #2. Var-args function, that doesn't contain byval parameters.
02889   //          The same: eat all remained unallocated registers,
02890   //          initialize stack frame.
02891 
02892   MachineFunction &MF = DAG.getMachineFunction();
02893   MachineFrameInfo *MFI = MF.getFrameInfo();
02894   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02895   unsigned RBegin, REnd;
02896   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
02897     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
02898   } else {
02899     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
02900     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
02901     REnd = ARM::R4;
02902   }
02903 
02904   if (REnd != RBegin)
02905     ArgOffset = -4 * (ARM::R4 - RBegin);
02906 
02907   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
02908   SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
02909 
02910   SmallVector<SDValue, 4> MemOps;
02911   const TargetRegisterClass *RC =
02912       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
02913 
02914   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
02915     unsigned VReg = MF.addLiveIn(Reg, RC);
02916     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
02917     SDValue Store =
02918         DAG.getStore(Val.getValue(1), dl, Val, FIN,
02919                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
02920     MemOps.push_back(Store);
02921     FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
02922                       DAG.getConstant(4, dl, getPointerTy()));
02923   }
02924 
02925   if (!MemOps.empty())
02926     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
02927   return FrameIndex;
02928 }
02929 
02930 // Setup stack frame, the va_list pointer will start from.
02931 void
02932 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
02933                                         SDLoc dl, SDValue &Chain,
02934                                         unsigned ArgOffset,
02935                                         unsigned TotalArgRegsSaveSize,
02936                                         bool ForceMutable) const {
02937   MachineFunction &MF = DAG.getMachineFunction();
02938   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02939 
02940   // Try to store any remaining integer argument regs
02941   // to their spots on the stack so that they may be loaded by deferencing
02942   // the result of va_next.
02943   // If there is no regs to be stored, just point address after last
02944   // argument passed via stack.
02945   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
02946                                   CCInfo.getInRegsParamsCount(),
02947                                   CCInfo.getNextStackOffset(), 4);
02948   AFI->setVarArgsFrameIndex(FrameIndex);
02949 }
02950 
02951 SDValue
02952 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
02953                                         CallingConv::ID CallConv, bool isVarArg,
02954                                         const SmallVectorImpl<ISD::InputArg>
02955                                           &Ins,
02956                                         SDLoc dl, SelectionDAG &DAG,
02957                                         SmallVectorImpl<SDValue> &InVals)
02958                                           const {
02959   MachineFunction &MF = DAG.getMachineFunction();
02960   MachineFrameInfo *MFI = MF.getFrameInfo();
02961 
02962   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02963 
02964   // Assign locations to all of the incoming arguments.
02965   SmallVector<CCValAssign, 16> ArgLocs;
02966   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
02967                     *DAG.getContext(), Prologue);
02968   CCInfo.AnalyzeFormalArguments(Ins,
02969                                 CCAssignFnForNode(CallConv, /* Return*/ false,
02970                                                   isVarArg));
02971 
02972   SmallVector<SDValue, 16> ArgValues;
02973   SDValue ArgValue;
02974   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
02975   unsigned CurArgIdx = 0;
02976 
02977   // Initially ArgRegsSaveSize is zero.
02978   // Then we increase this value each time we meet byval parameter.
02979   // We also increase this value in case of varargs function.
02980   AFI->setArgRegsSaveSize(0);
02981 
02982   // Calculate the amount of stack space that we need to allocate to store
02983   // byval and variadic arguments that are passed in registers.
02984   // We need to know this before we allocate the first byval or variadic
02985   // argument, as they will be allocated a stack slot below the CFA (Canonical
02986   // Frame Address, the stack pointer at entry to the function).
02987   unsigned ArgRegBegin = ARM::R4;
02988   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
02989     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
02990       break;
02991 
02992     CCValAssign &VA = ArgLocs[i];
02993     unsigned Index = VA.getValNo();
02994     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
02995     if (!Flags.isByVal())
02996       continue;
02997 
02998     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
02999     unsigned RBegin, REnd;
03000     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
03001     ArgRegBegin = std::min(ArgRegBegin, RBegin);
03002 
03003     CCInfo.nextInRegsParam();
03004   }
03005   CCInfo.rewindByValRegsInfo();
03006 
03007   int lastInsIndex = -1;
03008   if (isVarArg && MFI->hasVAStart()) {
03009     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
03010     if (RegIdx != array_lengthof(GPRArgRegs))
03011       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
03012   }
03013 
03014   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
03015   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
03016 
03017   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
03018     CCValAssign &VA = ArgLocs[i];
03019     if (Ins[VA.getValNo()].isOrigArg()) {
03020       std::advance(CurOrigArg,
03021                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
03022       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
03023     }
03024     // Arguments stored in registers.
03025     if (VA.isRegLoc()) {
03026       EVT RegVT = VA.getLocVT();
03027 
03028       if (VA.needsCustom()) {
03029         // f64 and vector types are split up into multiple registers or
03030         // combinations of registers and stack slots.
03031         if (VA.getLocVT() == MVT::v2f64) {
03032           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
03033                                                    Chain, DAG, dl);
03034           VA = ArgLocs[++i]; // skip ahead to next loc
03035           SDValue ArgValue2;
03036           if (VA.isMemLoc()) {
03037             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
03038             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
03039             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
03040                                     MachinePointerInfo::getFixedStack(FI),
03041                                     false, false, false, 0);
03042           } else {
03043             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
03044                                              Chain, DAG, dl);
03045           }
03046           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
03047           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
03048                                  ArgValue, ArgValue1,
03049                                  DAG.getIntPtrConstant(0, dl));
03050           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
03051                                  ArgValue, ArgValue2,
03052                                  DAG.getIntPtrConstant(1, dl));
03053         } else
03054           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
03055 
03056       } else {
03057         const TargetRegisterClass *RC;
03058 
03059         if (RegVT == MVT::f32)
03060           RC = &ARM::SPRRegClass;
03061         else if (RegVT == MVT::f64)
03062           RC = &ARM::DPRRegClass;
03063         else if (RegVT == MVT::v2f64)
03064           RC = &ARM::QPRRegClass;
03065         else if (RegVT == MVT::i32)
03066           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
03067                                            : &ARM::GPRRegClass;
03068         else
03069           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
03070 
03071         // Transform the arguments in physical registers into virtual ones.
03072         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
03073         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
03074       }
03075 
03076       // If this is an 8 or 16-bit value, it is really passed promoted
03077       // to 32 bits.  Insert an assert[sz]ext to capture this, then
03078       // truncate to the right size.
03079       switch (VA.getLocInfo()) {
03080       default: llvm_unreachable("Unknown loc info!");
03081       case CCValAssign::Full: break;
03082       case CCValAssign::BCvt:
03083         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
03084         break;
03085       case CCValAssign::SExt:
03086         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
03087                                DAG.getValueType(VA.getValVT()));
03088         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
03089         break;
03090       case CCValAssign::ZExt:
03091         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
03092                                DAG.getValueType(VA.getValVT()));
03093         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
03094         break;
03095       }
03096 
03097       InVals.push_back(ArgValue);
03098 
03099     } else { // VA.isRegLoc()
03100 
03101       // sanity check
03102       assert(VA.isMemLoc());
03103       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
03104 
03105       int index = VA.getValNo();
03106 
03107       // Some Ins[] entries become multiple ArgLoc[] entries.
03108       // Process them only once.
03109       if (index != lastInsIndex)
03110         {
03111           ISD::ArgFlagsTy Flags = Ins[index].Flags;
03112           // FIXME: For now, all byval parameter objects are marked mutable.
03113           // This can be changed with more analysis.
03114           // In case of tail call optimization mark all arguments mutable.
03115           // Since they could be overwritten by lowering of arguments in case of
03116           // a tail call.
03117           if (Flags.isByVal()) {
03118             assert(Ins[index].isOrigArg() &&
03119                    "Byval arguments cannot be implicit");
03120             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
03121 
03122             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
03123                                             CurByValIndex, VA.getLocMemOffset(),
03124                                             Flags.getByValSize());
03125             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
03126             CCInfo.nextInRegsParam();
03127           } else {
03128             unsigned FIOffset = VA.getLocMemOffset();
03129             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
03130                                             FIOffset, true);
03131 
03132             // Create load nodes to retrieve arguments from the stack.
03133             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
03134             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
03135                                          MachinePointerInfo::getFixedStack(FI),
03136                                          false, false, false, 0));
03137           }
03138           lastInsIndex = index;
03139         }
03140     }
03141   }
03142 
03143   // varargs
03144   if (isVarArg && MFI->hasVAStart())
03145     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
03146                          CCInfo.getNextStackOffset(),
03147                          TotalArgRegsSaveSize);
03148 
03149   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
03150 
03151   return Chain;
03152 }
03153 
03154 /// isFloatingPointZero - Return true if this is +0.0.
03155 static bool isFloatingPointZero(SDValue Op) {
03156   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
03157     return CFP->getValueAPF().isPosZero();
03158   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
03159     // Maybe this has already been legalized into the constant pool?
03160     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
03161       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
03162       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
03163         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
03164           return CFP->getValueAPF().isPosZero();
03165     }
03166   } else if (Op->getOpcode() == ISD::BITCAST &&
03167              Op->getValueType(0) == MVT::f64) {
03168     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
03169     // created by LowerConstantFP().
03170     SDValue BitcastOp = Op->getOperand(0);
03171     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
03172       SDValue MoveOp = BitcastOp->getOperand(0);
03173       if (MoveOp->getOpcode() == ISD::TargetConstant &&
03174           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
03175         return true;
03176       }
03177     }
03178   }
03179   return false;
03180 }
03181 
03182 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
03183 /// the given operands.
03184 SDValue
03185 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
03186                              SDValue &ARMcc, SelectionDAG &DAG,
03187                              SDLoc dl) const {
03188   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
03189     unsigned C = RHSC->getZExtValue();
03190     if (!isLegalICmpImmediate(C)) {
03191       // Constant does not fit, try adjusting it by one?
03192       switch (CC) {
03193       default: break;
03194       case ISD::SETLT:
03195       case ISD::SETGE:
03196         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
03197           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
03198           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
03199         }
03200         break;
03201       case ISD::SETULT:
03202       case ISD::SETUGE:
03203         if (C != 0 && isLegalICmpImmediate(C-1)) {
03204           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
03205           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
03206         }
03207         break;
03208       case ISD::SETLE:
03209       case ISD::SETGT:
03210         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
03211           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
03212           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
03213         }
03214         break;
03215       case ISD::SETULE:
03216       case ISD::SETUGT:
03217         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
03218           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
03219           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
03220         }
03221         break;
03222       }
03223     }
03224   }
03225 
03226   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03227   ARMISD::NodeType CompareType;
03228   switch (CondCode) {
03229   default:
03230     CompareType = ARMISD::CMP;
03231     break;
03232   case ARMCC::EQ:
03233   case ARMCC::NE:
03234     // Uses only Z Flag
03235     CompareType = ARMISD::CMPZ;
03236     break;
03237   }
03238   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
03239   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
03240 }
03241 
03242 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
03243 SDValue
03244 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
03245                              SDLoc dl) const {
03246   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
03247   SDValue Cmp;
03248   if (!isFloatingPointZero(RHS))
03249     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
03250   else
03251     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
03252   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
03253 }
03254 
03255 /// duplicateCmp - Glue values can have only one use, so this function
03256 /// duplicates a comparison node.
03257 SDValue
03258 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
03259   unsigned Opc = Cmp.getOpcode();
03260   SDLoc DL(Cmp);
03261   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
03262     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
03263 
03264   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
03265   Cmp = Cmp.getOperand(0);
03266   Opc = Cmp.getOpcode();
03267   if (Opc == ARMISD::CMPFP)
03268     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
03269   else {
03270     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
03271     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
03272   }
03273   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
03274 }
03275 
03276 std::pair<SDValue, SDValue>
03277 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
03278                                  SDValue &ARMcc) const {
03279   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
03280 
03281   SDValue Value, OverflowCmp;
03282   SDValue LHS = Op.getOperand(0);
03283   SDValue RHS = Op.getOperand(1);
03284   SDLoc dl(Op);
03285 
03286   // FIXME: We are currently always generating CMPs because we don't support
03287   // generating CMN through the backend. This is not as good as the natural
03288   // CMP case because it causes a register dependency and cannot be folded
03289   // later.
03290 
03291   switch (Op.getOpcode()) {
03292   default:
03293     llvm_unreachable("Unknown overflow instruction!");
03294   case ISD::SADDO:
03295     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
03296     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
03297     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
03298     break;
03299   case ISD::UADDO:
03300     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
03301     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
03302     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
03303     break;
03304   case ISD::SSUBO:
03305     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
03306     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
03307     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
03308     break;
03309   case ISD::USUBO:
03310     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
03311     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
03312     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
03313     break;
03314   } // switch (...)
03315 
03316   return std::make_pair(Value, OverflowCmp);
03317 }
03318 
03319 
03320 SDValue
03321 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
03322   // Let legalize expand this if it isn't a legal type yet.
03323   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
03324     return SDValue();
03325 
03326   SDValue Value, OverflowCmp;
03327   SDValue ARMcc;
03328   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
03329   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03330   SDLoc dl(Op);
03331   // We use 0 and 1 as false and true values.
03332   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
03333   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
03334   EVT VT = Op.getValueType();
03335 
03336   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
03337                                  ARMcc, CCR, OverflowCmp);
03338 
03339   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
03340   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
03341 }
03342 
03343 
03344 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
03345   SDValue Cond = Op.getOperand(0);
03346   SDValue SelectTrue = Op.getOperand(1);
03347   SDValue SelectFalse = Op.getOperand(2);
03348   SDLoc dl(Op);
03349   unsigned Opc = Cond.getOpcode();
03350 
03351   if (Cond.getResNo() == 1 &&
03352       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
03353        Opc == ISD::USUBO)) {
03354     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
03355       return SDValue();
03356 
03357     SDValue Value, OverflowCmp;
03358     SDValue ARMcc;
03359     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
03360     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03361     EVT VT = Op.getValueType();
03362 
03363     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
03364                    OverflowCmp, DAG);
03365   }
03366 
03367   // Convert:
03368   //
03369   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
03370   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
03371   //
03372   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
03373     const ConstantSDNode *CMOVTrue =
03374       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
03375     const ConstantSDNode *CMOVFalse =
03376       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
03377 
03378     if (CMOVTrue && CMOVFalse) {
03379       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
03380       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
03381 
03382       SDValue True;
03383       SDValue False;
03384       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
03385         True = SelectTrue;
03386         False = SelectFalse;
03387       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
03388         True = SelectFalse;
03389         False = SelectTrue;
03390       }
03391 
03392       if (True.getNode() && False.getNode()) {
03393         EVT VT = Op.getValueType();
03394         SDValue ARMcc = Cond.getOperand(2);
03395         SDValue CCR = Cond.getOperand(3);
03396         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
03397         assert(True.getValueType() == VT);
03398         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
03399       }
03400     }
03401   }
03402 
03403   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
03404   // undefined bits before doing a full-word comparison with zero.
03405   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
03406                      DAG.getConstant(1, dl, Cond.getValueType()));
03407 
03408   return DAG.getSelectCC(dl, Cond,
03409                          DAG.getConstant(0, dl, Cond.getValueType()),
03410                          SelectTrue, SelectFalse, ISD::SETNE);
03411 }
03412 
03413 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
03414                                  bool &swpCmpOps, bool &swpVselOps) {
03415   // Start by selecting the GE condition code for opcodes that return true for
03416   // 'equality'
03417   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
03418       CC == ISD::SETULE)
03419     CondCode = ARMCC::GE;
03420 
03421   // and GT for opcodes that return false for 'equality'.
03422   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
03423            CC == ISD::SETULT)
03424     CondCode = ARMCC::GT;
03425 
03426   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
03427   // to swap the compare operands.
03428   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
03429       CC == ISD::SETULT)
03430     swpCmpOps = true;
03431 
03432   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
03433   // If we have an unordered opcode, we need to swap the operands to the VSEL
03434   // instruction (effectively negating the condition).
03435   //
03436   // This also has the effect of swapping which one of 'less' or 'greater'
03437   // returns true, so we also swap the compare operands. It also switches
03438   // whether we return true for 'equality', so we compensate by picking the
03439   // opposite condition code to our original choice.
03440   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
03441       CC == ISD::SETUGT) {
03442     swpCmpOps = !swpCmpOps;
03443     swpVselOps = !swpVselOps;
03444     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
03445   }
03446 
03447   // 'ordered' is 'anything but unordered', so use the VS condition code and
03448   // swap the VSEL operands.
03449   if (CC == ISD::SETO) {
03450     CondCode = ARMCC::VS;
03451     swpVselOps = true;
03452   }
03453 
03454   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
03455   // code and swap the VSEL operands.
03456   if (CC == ISD::SETUNE) {
03457     CondCode = ARMCC::EQ;
03458     swpVselOps = true;
03459   }
03460 }
03461 
03462 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
03463                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
03464                                    SDValue Cmp, SelectionDAG &DAG) const {
03465   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
03466     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
03467                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
03468     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
03469                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
03470 
03471     SDValue TrueLow = TrueVal.getValue(0);
03472     SDValue TrueHigh = TrueVal.getValue(1);
03473     SDValue FalseLow = FalseVal.getValue(0);
03474     SDValue FalseHigh = FalseVal.getValue(1);
03475 
03476     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
03477                               ARMcc, CCR, Cmp);
03478     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
03479                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
03480 
03481     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
03482   } else {
03483     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
03484                        Cmp);
03485   }
03486 }
03487 
03488 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
03489   EVT VT = Op.getValueType();
03490   SDValue LHS = Op.getOperand(0);
03491   SDValue RHS = Op.getOperand(1);
03492   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
03493   SDValue TrueVal = Op.getOperand(2);
03494   SDValue FalseVal = Op.getOperand(3);
03495   SDLoc dl(Op);
03496 
03497   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
03498     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
03499                                                     dl);
03500 
03501     // If softenSetCCOperands only returned one value, we should compare it to
03502     // zero.
03503     if (!RHS.getNode()) {
03504       RHS = DAG.getConstant(0, dl, LHS.getValueType());
03505       CC = ISD::SETNE;
03506     }
03507   }
03508 
03509   if (LHS.getValueType() == MVT::i32) {
03510     // Try to generate VSEL on ARMv8.
03511     // The VSEL instruction can't use all the usual ARM condition
03512     // codes: it only has two bits to select the condition code, so it's
03513     // constrained to use only GE, GT, VS and EQ.
03514     //
03515     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
03516     // swap the operands of the previous compare instruction (effectively
03517     // inverting the compare condition, swapping 'less' and 'greater') and
03518     // sometimes need to swap the operands to the VSEL (which inverts the
03519     // condition in the sense of firing whenever the previous condition didn't)
03520     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
03521                                     TrueVal.getValueType() == MVT::f64)) {
03522       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03523       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
03524           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
03525         CC = ISD::getSetCCInverse(CC, true);
03526         std::swap(TrueVal, FalseVal);
03527       }
03528     }
03529 
03530     SDValue ARMcc;
03531     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03532     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03533     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
03534   }
03535 
03536   ARMCC::CondCodes CondCode, CondCode2;
03537   FPCCToARMCC(CC, CondCode, CondCode2);
03538 
03539   // Try to generate VMAXNM/VMINNM on ARMv8.
03540   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
03541                                   TrueVal.getValueType() == MVT::f64)) {
03542     // We can use VMAXNM/VMINNM for a compare followed by a select with the
03543     // same operands, as follows:
03544     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
03545     //   select c, a, b
03546     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
03547     bool swapSides = false;
03548     if (!getTargetMachine().Options.NoNaNsFPMath) {
03549       // transformability may depend on which way around we compare
03550       switch (CC) {
03551       default:
03552         break;
03553       case ISD::SETOGT:
03554       case ISD::SETOGE:
03555       case ISD::SETOLT:
03556       case ISD::SETOLE:
03557         // the non-NaN should be RHS
03558         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
03559         break;
03560       case ISD::SETUGT:
03561       case ISD::SETUGE:
03562       case ISD::SETULT:
03563       case ISD::SETULE:
03564         // the non-NaN should be LHS
03565         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
03566         break;
03567       }
03568     }
03569     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
03570     if (swapSides) {
03571       CC = ISD::getSetCCSwappedOperands(CC);
03572       std::swap(LHS, RHS);
03573     }
03574     if (LHS == TrueVal && RHS == FalseVal) {
03575       bool canTransform = true;
03576       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
03577       if (!getTargetMachine().Options.UnsafeFPMath &&
03578           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
03579         const ConstantFPSDNode *Zero;
03580         switch (CC) {
03581         default:
03582           break;
03583         case ISD::SETOGT:
03584         case ISD::SETUGT:
03585         case ISD::SETGT:
03586           // RHS must not be -0
03587           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
03588                          !Zero->isNegative();
03589           break;
03590         case ISD::SETOGE:
03591         case ISD::SETUGE:
03592         case ISD::SETGE:
03593           // LHS must not be -0
03594           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
03595                          !Zero->isNegative();
03596           break;
03597         case ISD::SETOLT:
03598         case ISD::SETULT:
03599         case ISD::SETLT:
03600           // RHS must not be +0
03601           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
03602                           Zero->isNegative();
03603           break;
03604         case ISD::SETOLE:
03605         case ISD::SETULE:
03606         case ISD::SETLE:
03607           // LHS must not be +0
03608           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
03609                           Zero->isNegative();
03610           break;
03611         }
03612       }
03613       if (canTransform) {
03614         // Note: If one of the elements in a pair is a number and the other
03615         // element is NaN, the corresponding result element is the number.
03616         // This is consistent with the IEEE 754-2008 standard.
03617         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
03618         switch (CC) {
03619         default:
03620           break;
03621         case ISD::SETOGT:
03622         case ISD::SETOGE:
03623           if (!DAG.isKnownNeverNaN(RHS))
03624             break;
03625           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
03626         case ISD::SETUGT:
03627         case ISD::SETUGE:
03628           if (!DAG.isKnownNeverNaN(LHS))
03629             break;
03630         case ISD::SETGT:
03631         case ISD::SETGE:
03632           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
03633         case ISD::SETOLT:
03634         case ISD::SETOLE:
03635           if (!DAG.isKnownNeverNaN(RHS))
03636             break;
03637           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
03638         case ISD::SETULT:
03639         case ISD::SETULE:
03640           if (!DAG.isKnownNeverNaN(LHS))
03641             break;
03642         case ISD::SETLT:
03643         case ISD::SETLE:
03644           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
03645         }
03646       }
03647     }
03648 
03649     bool swpCmpOps = false;
03650     bool swpVselOps = false;
03651     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
03652 
03653     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
03654         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
03655       if (swpCmpOps)
03656         std::swap(LHS, RHS);
03657       if (swpVselOps)
03658         std::swap(TrueVal, FalseVal);
03659     }
03660   }
03661 
03662   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
03663   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
03664   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03665   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
03666   if (CondCode2 != ARMCC::AL) {
03667     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
03668     // FIXME: Needs another CMP because flag can have but one use.
03669     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
03670     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
03671   }
03672   return Result;
03673 }
03674 
03675 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
03676 /// to morph to an integer compare sequence.
03677 static bool canChangeToInt(SDValue Op, bool &SeenZero,
03678                            const ARMSubtarget *Subtarget) {
03679   SDNode *N = Op.getNode();
03680   if (!N->hasOneUse())
03681     // Otherwise it requires moving the value from fp to integer registers.
03682     return false;
03683   if (!N->getNumValues())
03684     return false;
03685   EVT VT = Op.getValueType();
03686   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
03687     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
03688     // vmrs are very slow, e.g. cortex-a8.
03689     return false;
03690 
03691   if (isFloatingPointZero(Op)) {
03692     SeenZero = true;
03693     return true;
03694   }
03695   return ISD::isNormalLoad(N);
03696 }
03697 
03698 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
03699   if (isFloatingPointZero(Op))
03700     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
03701 
03702   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
03703     return DAG.getLoad(MVT::i32, SDLoc(Op),
03704                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
03705                        Ld->isVolatile(), Ld->isNonTemporal(),
03706                        Ld->isInvariant(), Ld->getAlignment());
03707 
03708   llvm_unreachable("Unknown VFP cmp argument!");
03709 }
03710 
03711 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
03712                            SDValue &RetVal1, SDValue &RetVal2) {
03713   SDLoc dl(Op);
03714 
03715   if (isFloatingPointZero(Op)) {
03716     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
03717     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
03718     return;
03719   }
03720 
03721   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
03722     SDValue Ptr = Ld->getBasePtr();
03723     RetVal1 = DAG.getLoad(MVT::i32, dl,
03724                           Ld->getChain(), Ptr,
03725                           Ld->getPointerInfo(),
03726                           Ld->isVolatile(), Ld->isNonTemporal(),
03727                           Ld->isInvariant(), Ld->getAlignment());
03728 
03729     EVT PtrType = Ptr.getValueType();
03730     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
03731     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
03732                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
03733     RetVal2 = DAG.getLoad(MVT::i32, dl,
03734                           Ld->getChain(), NewPtr,
03735                           Ld->getPointerInfo().getWithOffset(4),
03736                           Ld->isVolatile(), Ld->isNonTemporal(),
03737                           Ld->isInvariant(), NewAlign);
03738     return;
03739   }
03740 
03741   llvm_unreachable("Unknown VFP cmp argument!");
03742 }
03743 
03744 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
03745 /// f32 and even f64 comparisons to integer ones.
03746 SDValue
03747 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
03748   SDValue Chain = Op.getOperand(0);
03749   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
03750   SDValue LHS = Op.getOperand(2);
03751   SDValue RHS = Op.getOperand(3);
03752   SDValue Dest = Op.getOperand(4);
03753   SDLoc dl(Op);
03754 
03755   bool LHSSeenZero = false;
03756   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
03757   bool RHSSeenZero = false;
03758   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
03759   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
03760     // If unsafe fp math optimization is enabled and there are no other uses of
03761     // the CMP operands, and the condition code is EQ or NE, we can optimize it
03762     // to an integer comparison.
03763     if (CC == ISD::SETOEQ)
03764       CC = ISD::SETEQ;
03765     else if (CC == ISD::SETUNE)
03766       CC = ISD::SETNE;
03767 
03768     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
03769     SDValue ARMcc;
03770     if (LHS.getValueType() == MVT::f32) {
03771       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
03772                         bitcastf32Toi32(LHS, DAG), Mask);
03773       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
03774                         bitcastf32Toi32(RHS, DAG), Mask);
03775       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03776       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03777       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
03778                          Chain, Dest, ARMcc, CCR, Cmp);
03779     }
03780 
03781     SDValue LHS1, LHS2;
03782     SDValue RHS1, RHS2;
03783     expandf64Toi32(LHS, DAG, LHS1, LHS2);
03784     expandf64Toi32(RHS, DAG, RHS1, RHS2);
03785     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
03786     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
03787     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03788     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
03789     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
03790     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
03791     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
03792   }
03793 
03794   return SDValue();
03795 }
03796 
03797 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
03798   SDValue Chain = Op.getOperand(0);
03799   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
03800   SDValue LHS = Op.getOperand(2);
03801   SDValue RHS = Op.getOperand(3);
03802   SDValue Dest = Op.getOperand(4);
03803   SDLoc dl(Op);
03804 
03805   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
03806     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
03807                                                     dl);
03808 
03809     // If softenSetCCOperands only returned one value, we should compare it to
03810     // zero.
03811     if (!RHS.getNode()) {
03812       RHS = DAG.getConstant(0, dl, LHS.getValueType());
03813       CC = ISD::SETNE;
03814     }
03815   }
03816 
03817   if (LHS.getValueType() == MVT::i32) {
03818     SDValue ARMcc;
03819     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03820     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03821     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
03822                        Chain, Dest, ARMcc, CCR, Cmp);
03823   }
03824 
03825   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
03826 
03827   if (getTargetMachine().Options.UnsafeFPMath &&
03828       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
03829        CC == ISD::SETNE || CC == ISD::SETUNE)) {
03830     SDValue Result = OptimizeVFPBrcond(Op, DAG);
03831     if (Result.getNode())
03832       return Result;
03833   }
03834 
03835   ARMCC::CondCodes CondCode, CondCode2;
03836   FPCCToARMCC(CC, CondCode, CondCode2);
03837 
03838   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
03839   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
03840   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03841   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
03842   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
03843   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
03844   if (CondCode2 != ARMCC::AL) {
03845     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
03846     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
03847     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
03848   }
03849   return Res;
03850 }
03851 
03852 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
03853   SDValue Chain = Op.getOperand(0);
03854   SDValue Table = Op.getOperand(1);
03855   SDValue Index = Op.getOperand(2);
03856   SDLoc dl(Op);
03857 
03858   EVT PTy = getPointerTy();
03859   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
03860   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
03861   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
03862   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
03863   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
03864   if (Subtarget->isThumb2()) {
03865     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
03866     // which does another jump to the destination. This also makes it easier
03867     // to translate it to TBB / TBH later.
03868     // FIXME: This might not work if the function is extremely large.
03869     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
03870                        Addr, Op.getOperand(2), JTI);
03871   }
03872   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
03873     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
03874                        MachinePointerInfo::getJumpTable(),
03875                        false, false, false, 0);
03876     Chain = Addr.getValue(1);
03877     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
03878     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
03879   } else {
03880     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
03881                        MachinePointerInfo::getJumpTable(),
03882                        false, false, false, 0);
03883     Chain = Addr.getValue(1);
03884     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
03885   }
03886 }
03887 
03888 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
03889   EVT VT = Op.getValueType();
03890   SDLoc dl(Op);
03891 
03892   if (Op.getValueType().getVectorElementType() == MVT::i32) {
03893     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
03894       return Op;
03895     return DAG.UnrollVectorOp(Op.getNode());
03896   }
03897 
03898   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
03899          "Invalid type for custom lowering!");
03900   if (VT != MVT::v4i16)
03901     return DAG.UnrollVectorOp(Op.getNode());
03902 
03903   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
03904   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
03905 }
03906 
03907 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
03908   EVT VT = Op.getValueType();
03909   if (VT.isVector())
03910     return LowerVectorFP_TO_INT(Op, DAG);
03911   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
03912     RTLIB::Libcall LC;
03913     if (Op.getOpcode() == ISD::FP_TO_SINT)
03914       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
03915                               Op.getValueType());
03916     else
03917       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
03918                               Op.getValueType());
03919     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
03920                        /*isSigned*/ false, SDLoc(Op)).first;
03921   }
03922 
03923   return Op;
03924 }
03925 
03926 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
03927   EVT VT = Op.getValueType();
03928   SDLoc dl(Op);
03929 
03930   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
03931     if (VT.getVectorElementType() == MVT::f32)
03932       return Op;
03933     return DAG.UnrollVectorOp(Op.getNode());
03934   }
03935 
03936   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
03937          "Invalid type for custom lowering!");
03938   if (VT != MVT::v4f32)
03939     return DAG.UnrollVectorOp(Op.getNode());
03940 
03941   unsigned CastOpc;
03942   unsigned Opc;
03943   switch (Op.getOpcode()) {
03944   default: llvm_unreachable("Invalid opcode!");
03945   case ISD::SINT_TO_FP:
03946     CastOpc = ISD::SIGN_EXTEND;
03947     Opc = ISD::SINT_TO_FP;
03948     break;
03949   case ISD::UINT_TO_FP:
03950     CastOpc = ISD::ZERO_EXTEND;
03951     Opc = ISD::UINT_TO_FP;
03952     break;
03953   }
03954 
03955   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
03956   return DAG.getNode(Opc, dl, VT, Op);
03957 }
03958 
03959 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
03960   EVT VT = Op.getValueType();
03961   if (VT.isVector())
03962     return LowerVectorINT_TO_FP(Op, DAG);
03963   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
03964     RTLIB::Libcall LC;
03965     if (Op.getOpcode() == ISD::SINT_TO_FP)
03966       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
03967                               Op.getValueType());
03968     else
03969       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
03970                               Op.getValueType());
03971     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
03972                        /*isSigned*/ false, SDLoc(Op)).first;
03973   }
03974 
03975   return Op;
03976 }
03977 
03978 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
03979   // Implement fcopysign with a fabs and a conditional fneg.
03980   SDValue Tmp0 = Op.getOperand(0);
03981   SDValue Tmp1 = Op.getOperand(1);
03982   SDLoc dl(Op);
03983   EVT VT = Op.getValueType();
03984   EVT SrcVT = Tmp1.getValueType();
03985   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
03986     Tmp0.getOpcode() == ARMISD::VMOVDRR;
03987   bool UseNEON = !InGPR && Subtarget->hasNEON();
03988 
03989   if (UseNEON) {
03990     // Use VBSL to copy the sign bit.
03991     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
03992     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
03993                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
03994     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
03995     if (VT == MVT::f64)
03996       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
03997                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
03998                          DAG.getConstant(32, dl, MVT::i32));
03999     else /*if (VT == MVT::f32)*/
04000       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
04001     if (SrcVT == MVT::f32) {
04002       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
04003       if (VT == MVT::f64)
04004         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
04005                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
04006                            DAG.getConstant(32, dl, MVT::i32));
04007     } else if (VT == MVT::f32)
04008       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
04009                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
04010                          DAG.getConstant(32, dl, MVT::i32));
04011     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
04012     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
04013 
04014     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
04015                                             dl, MVT::i32);
04016     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
04017     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
04018                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
04019 
04020     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
04021                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
04022                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
04023     if (VT == MVT::f32) {
04024       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
04025       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
04026                         DAG.getConstant(0, dl, MVT::i32));
04027     } else {
04028       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
04029     }
04030 
04031     return Res;
04032   }
04033 
04034   // Bitcast operand 1 to i32.
04035   if (SrcVT == MVT::f64)
04036     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
04037                        Tmp1).getValue(1);
04038   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
04039 
04040   // Or in the signbit with integer operations.
04041   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
04042   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
04043   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
04044   if (VT == MVT::f32) {
04045     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
04046                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
04047     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
04048                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
04049   }
04050 
04051   // f64: Or the high part with signbit and then combine two parts.
04052   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
04053                      Tmp0);
04054   SDValue Lo = Tmp0.getValue(0);
04055   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
04056   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
04057   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
04058 }
04059 
04060 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
04061   MachineFunction &MF = DAG.getMachineFunction();
04062   MachineFrameInfo *MFI = MF.getFrameInfo();
04063   MFI->setReturnAddressIsTaken(true);
04064 
04065   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
04066     return SDValue();
04067 
04068   EVT VT = Op.getValueType();
04069   SDLoc dl(Op);
04070   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
04071   if (Depth) {
04072     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
04073     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
04074     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
04075                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
04076                        MachinePointerInfo(), false, false, false, 0);
04077   }
04078 
04079   // Return LR, which contains the return address. Mark it an implicit live-in.
04080   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
04081   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
04082 }
04083 
04084 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
04085   const ARMBaseRegisterInfo &ARI =
04086     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
04087   MachineFunction &MF = DAG.getMachineFunction();
04088   MachineFrameInfo *MFI = MF.getFrameInfo();
04089   MFI->setFrameAddressIsTaken(true);
04090 
04091   EVT VT = Op.getValueType();
04092   SDLoc dl(Op);  // FIXME probably not meaningful
04093   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
04094   unsigned FrameReg = ARI.getFrameRegister(MF);
04095   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
04096   while (Depth--)
04097     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
04098                             MachinePointerInfo(),
04099                             false, false, false, 0);
04100   return FrameAddr;
04101 }
04102 
04103 // FIXME? Maybe this could be a TableGen attribute on some registers and
04104 // this table could be generated automatically from RegInfo.
04105 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
04106                                               EVT VT) const {
04107   unsigned Reg = StringSwitch<unsigned>(RegName)
04108                        .Case("sp", ARM::SP)
04109                        .Default(0);
04110   if (Reg)
04111     return Reg;
04112   report_fatal_error(Twine("Invalid register name \""
04113                               + StringRef(RegName)  + "\"."));
04114 }
04115 
04116 // Result is 64 bit value so split into two 32 bit values and return as a
04117 // pair of values.
04118 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
04119                                 SelectionDAG &DAG) {
04120   SDLoc DL(N);
04121 
04122   // This function is only supposed to be called for i64 type destination.
04123   assert(N->getValueType(0) == MVT::i64
04124           && "ExpandREAD_REGISTER called for non-i64 type result.");
04125 
04126   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
04127                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
04128                              N->getOperand(0),
04129                              N->getOperand(1));
04130 
04131   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
04132                     Read.getValue(1)));
04133   Results.push_back(Read.getOperand(0));
04134 }
04135 
04136 /// ExpandBITCAST - If the target supports VFP, this function is called to
04137 /// expand a bit convert where either the source or destination type is i64 to
04138 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
04139 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
04140 /// vectors), since the legalizer won't know what to do with that.
04141 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
04142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
04143   SDLoc dl(N);
04144   SDValue Op = N->getOperand(0);
04145 
04146   // This function is only supposed to be called for i64 types, either as the
04147   // source or destination of the bit convert.
04148   EVT SrcVT = Op.getValueType();
04149   EVT DstVT = N->getValueType(0);
04150   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
04151          "ExpandBITCAST called for non-i64 type");
04152 
04153   // Turn i64->f64 into VMOVDRR.
04154   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
04155     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
04156                              DAG.getConstant(0, dl, MVT::i32));
04157     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
04158                              DAG.getConstant(1, dl, MVT::i32));
04159     return DAG.getNode(ISD::BITCAST, dl, DstVT,
04160                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
04161   }
04162 
04163   // Turn f64->i64 into VMOVRRD.
04164   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
04165     SDValue Cvt;
04166     if (TLI.isBigEndian() && SrcVT.isVector() &&
04167         SrcVT.getVectorNumElements() > 1)
04168       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
04169                         DAG.getVTList(MVT::i32, MVT::i32),
04170                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
04171     else
04172       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
04173                         DAG.getVTList(MVT::i32, MVT::i32), Op);
04174     // Merge the pieces into a single i64 value.
04175     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
04176   }
04177 
04178   return SDValue();
04179 }
04180 
04181 /// getZeroVector - Returns a vector of specified type with all zero elements.
04182 /// Zero vectors are used to represent vector negation and in those cases
04183 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
04184 /// not support i64 elements, so sometimes the zero vectors will need to be
04185 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
04186 /// zero vector.
04187 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
04188   assert(VT.isVector() && "Expected a vector type");
04189   // The canonical modified immediate encoding of a zero vector is....0!
04190   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
04191   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
04192   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
04193   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
04194 }
04195 
04196 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
04197 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
04198 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
04199                                                 SelectionDAG &DAG) const {
04200   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04201   EVT VT = Op.getValueType();
04202   unsigned VTBits = VT.getSizeInBits();
04203   SDLoc dl(Op);
04204   SDValue ShOpLo = Op.getOperand(0);
04205   SDValue ShOpHi = Op.getOperand(1);
04206   SDValue ShAmt  = Op.getOperand(2);
04207   SDValue ARMcc;
04208   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
04209 
04210   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
04211 
04212   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
04213                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
04214   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
04215   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
04216                                    DAG.getConstant(VTBits, dl, MVT::i32));
04217   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
04218   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
04219   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
04220 
04221   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
04222   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
04223                           ISD::SETGE, ARMcc, DAG, dl);
04224   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
04225   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
04226                            CCR, Cmp);
04227 
04228   SDValue Ops[2] = { Lo, Hi };
04229   return DAG.getMergeValues(Ops, dl);
04230 }
04231 
04232 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
04233 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
04234 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
04235                                                SelectionDAG &DAG) const {
04236   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04237   EVT VT = Op.getValueType();
04238   unsigned VTBits = VT.getSizeInBits();
04239   SDLoc dl(Op);
04240   SDValue ShOpLo = Op.getOperand(0);
04241   SDValue ShOpHi = Op.getOperand(1);
04242   SDValue ShAmt  = Op.getOperand(2);
04243   SDValue ARMcc;
04244 
04245   assert(Op.getOpcode() == ISD::SHL_PARTS);
04246   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
04247                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
04248   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
04249   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
04250                                    DAG.getConstant(VTBits, dl, MVT::i32));
04251