LLVM API Documentation

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/CodeGen/CallingConvLower.h"
00027 #include "llvm/CodeGen/IntrinsicLowering.h"
00028 #include "llvm/CodeGen/MachineBasicBlock.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineFunction.h"
00031 #include "llvm/CodeGen/MachineInstrBuilder.h"
00032 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00033 #include "llvm/CodeGen/MachineModuleInfo.h"
00034 #include "llvm/CodeGen/MachineRegisterInfo.h"
00035 #include "llvm/CodeGen/SelectionDAG.h"
00036 #include "llvm/IR/CallingConv.h"
00037 #include "llvm/IR/Constants.h"
00038 #include "llvm/IR/Function.h"
00039 #include "llvm/IR/GlobalValue.h"
00040 #include "llvm/IR/IRBuilder.h"
00041 #include "llvm/IR/Instruction.h"
00042 #include "llvm/IR/Instructions.h"
00043 #include "llvm/IR/Intrinsics.h"
00044 #include "llvm/IR/Type.h"
00045 #include "llvm/MC/MCSectionMachO.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include "llvm/Support/Debug.h"
00048 #include "llvm/Support/ErrorHandling.h"
00049 #include "llvm/Support/MathExtras.h"
00050 #include "llvm/Target/TargetOptions.h"
00051 #include <utility>
00052 using namespace llvm;
00053 
00054 #define DEBUG_TYPE "arm-isel"
00055 
00056 STATISTIC(NumTailCalls, "Number of tail calls");
00057 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
00058 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
00059 
00060 cl::opt<bool>
00061 EnableARMLongCalls("arm-long-calls", cl::Hidden,
00062   cl::desc("Generate calls via indirect call instructions"),
00063   cl::init(false));
00064 
00065 static cl::opt<bool>
00066 ARMInterworking("arm-interworking", cl::Hidden,
00067   cl::desc("Enable / disable ARM interworking (for debugging only)"),
00068   cl::init(true));
00069 
00070 namespace {
00071   class ARMCCState : public CCState {
00072   public:
00073     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
00074                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
00075                ParmContext PC)
00076         : CCState(CC, isVarArg, MF, locs, C) {
00077       assert(((PC == Call) || (PC == Prologue)) &&
00078              "ARMCCState users must specify whether their context is call"
00079              "or prologue generation.");
00080       CallOrPrologue = PC;
00081     }
00082   };
00083 }
00084 
00085 // The APCS parameter registers.
00086 static const MCPhysReg GPRArgRegs[] = {
00087   ARM::R0, ARM::R1, ARM::R2, ARM::R3
00088 };
00089 
00090 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
00091                                        MVT PromotedBitwiseVT) {
00092   if (VT != PromotedLdStVT) {
00093     setOperationAction(ISD::LOAD, VT, Promote);
00094     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
00095 
00096     setOperationAction(ISD::STORE, VT, Promote);
00097     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
00098   }
00099 
00100   MVT ElemTy = VT.getVectorElementType();
00101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
00102     setOperationAction(ISD::SETCC, VT, Custom);
00103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
00104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
00105   if (ElemTy == MVT::i32) {
00106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
00107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
00108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
00109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
00110   } else {
00111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
00112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
00113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
00114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
00115   }
00116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
00117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
00118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
00119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
00120   setOperationAction(ISD::SELECT,            VT, Expand);
00121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
00122   setOperationAction(ISD::VSELECT,           VT, Expand);
00123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
00124   if (VT.isInteger()) {
00125     setOperationAction(ISD::SHL, VT, Custom);
00126     setOperationAction(ISD::SRA, VT, Custom);
00127     setOperationAction(ISD::SRL, VT, Custom);
00128   }
00129 
00130   // Promote all bit-wise operations.
00131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
00132     setOperationAction(ISD::AND, VT, Promote);
00133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
00134     setOperationAction(ISD::OR,  VT, Promote);
00135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
00136     setOperationAction(ISD::XOR, VT, Promote);
00137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
00138   }
00139 
00140   // Neon does not support vector divide/remainder operations.
00141   setOperationAction(ISD::SDIV, VT, Expand);
00142   setOperationAction(ISD::UDIV, VT, Expand);
00143   setOperationAction(ISD::FDIV, VT, Expand);
00144   setOperationAction(ISD::SREM, VT, Expand);
00145   setOperationAction(ISD::UREM, VT, Expand);
00146   setOperationAction(ISD::FREM, VT, Expand);
00147 }
00148 
00149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
00150   addRegisterClass(VT, &ARM::DPRRegClass);
00151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
00152 }
00153 
00154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
00155   addRegisterClass(VT, &ARM::DPairRegClass);
00156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
00157 }
00158 
00159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
00160                                      const ARMSubtarget &STI)
00161     : TargetLowering(TM), Subtarget(&STI) {
00162   RegInfo = Subtarget->getRegisterInfo();
00163   Itins = Subtarget->getInstrItineraryData();
00164 
00165   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
00166 
00167   if (Subtarget->isTargetMachO()) {
00168     // Uses VFP for Thumb libfuncs if available.
00169     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
00170         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
00171       // Single-precision floating-point arithmetic.
00172       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
00173       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
00174       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
00175       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
00176 
00177       // Double-precision floating-point arithmetic.
00178       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
00179       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
00180       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
00181       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
00182 
00183       // Single-precision comparisons.
00184       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
00185       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
00186       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
00187       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
00188       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
00189       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
00190       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
00191       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
00192 
00193       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
00194       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
00195       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
00196       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
00197       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
00198       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
00199       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
00200       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
00201 
00202       // Double-precision comparisons.
00203       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
00204       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
00205       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
00206       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
00207       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
00208       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
00209       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
00210       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
00211 
00212       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
00213       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
00214       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
00215       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
00216       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
00217       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
00218       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
00219       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
00220 
00221       // Floating-point to integer conversions.
00222       // i64 conversions are done via library routines even when generating VFP
00223       // instructions, so use the same ones.
00224       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
00225       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
00226       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
00227       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
00228 
00229       // Conversions between floating types.
00230       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
00231       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
00232 
00233       // Integer to floating-point conversions.
00234       // i64 conversions are done via library routines even when generating VFP
00235       // instructions, so use the same ones.
00236       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
00237       // e.g., __floatunsidf vs. __floatunssidfvfp.
00238       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
00239       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
00240       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
00241       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
00242     }
00243   }
00244 
00245   // These libcalls are not available in 32-bit.
00246   setLibcallName(RTLIB::SHL_I128, nullptr);
00247   setLibcallName(RTLIB::SRL_I128, nullptr);
00248   setLibcallName(RTLIB::SRA_I128, nullptr);
00249 
00250   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
00251       !Subtarget->isTargetWindows()) {
00252     static const struct {
00253       const RTLIB::Libcall Op;
00254       const char * const Name;
00255       const CallingConv::ID CC;
00256       const ISD::CondCode Cond;
00257     } LibraryCalls[] = {
00258       // Double-precision floating-point arithmetic helper functions
00259       // RTABI chapter 4.1.2, Table 2
00260       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00261       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00262       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00263       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00264 
00265       // Double-precision floating-point comparison helper functions
00266       // RTABI chapter 4.1.2, Table 3
00267       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
00268       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
00269       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
00270       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
00271       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
00272       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
00273       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
00274       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
00275 
00276       // Single-precision floating-point arithmetic helper functions
00277       // RTABI chapter 4.1.2, Table 4
00278       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00279       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00280       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00281       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00282 
00283       // Single-precision floating-point comparison helper functions
00284       // RTABI chapter 4.1.2, Table 5
00285       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
00286       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
00287       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
00288       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
00289       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
00290       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
00291       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
00292       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
00293 
00294       // Floating-point to integer conversions.
00295       // RTABI chapter 4.1.2, Table 6
00296       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00297       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00298       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00299       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00300       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00301       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00302       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00303       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00304 
00305       // Conversions between floating types.
00306       // RTABI chapter 4.1.2, Table 7
00307       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00308       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00309       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00310 
00311       // Integer to floating-point conversions.
00312       // RTABI chapter 4.1.2, Table 8
00313       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00314       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00315       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00316       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00317       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00318       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00319       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00320       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00321 
00322       // Long long helper functions
00323       // RTABI chapter 4.2, Table 9
00324       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00325       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00326       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00327       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00328 
00329       // Integer division functions
00330       // RTABI chapter 4.3.1
00331       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00332       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00333       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00334       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00335       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00336       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00337       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00338       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00339 
00340       // Memory operations
00341       // RTABI chapter 4.3.4
00342       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00343       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00344       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
00345     };
00346 
00347     for (const auto &LC : LibraryCalls) {
00348       setLibcallName(LC.Op, LC.Name);
00349       setLibcallCallingConv(LC.Op, LC.CC);
00350       if (LC.Cond != ISD::SETCC_INVALID)
00351         setCmpLibcallCC(LC.Op, LC.Cond);
00352     }
00353   }
00354 
00355   if (Subtarget->isTargetWindows()) {
00356     static const struct {
00357       const RTLIB::Libcall Op;
00358       const char * const Name;
00359       const CallingConv::ID CC;
00360     } LibraryCalls[] = {
00361       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
00362       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
00363       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
00364       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
00365       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
00366       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
00367       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
00368       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
00369     };
00370 
00371     for (const auto &LC : LibraryCalls) {
00372       setLibcallName(LC.Op, LC.Name);
00373       setLibcallCallingConv(LC.Op, LC.CC);
00374     }
00375   }
00376 
00377   // Use divmod compiler-rt calls for iOS 5.0 and later.
00378   if (Subtarget->getTargetTriple().isiOS() &&
00379       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
00380     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
00381     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
00382   }
00383 
00384   // The half <-> float conversion functions are always soft-float, but are
00385   // needed for some targets which use a hard-float calling convention by
00386   // default.
00387   if (Subtarget->isAAPCS_ABI()) {
00388     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
00389     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
00390     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
00391   } else {
00392     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
00393     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
00394     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
00395   }
00396 
00397   if (Subtarget->isThumb1Only())
00398     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
00399   else
00400     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
00401   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
00402       !Subtarget->isThumb1Only()) {
00403     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
00404     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
00405   }
00406 
00407   for (MVT VT : MVT::vector_valuetypes()) {
00408     for (MVT InnerVT : MVT::vector_valuetypes()) {
00409       setTruncStoreAction(VT, InnerVT, Expand);
00410       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
00411       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
00412       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
00413     }
00414 
00415     setOperationAction(ISD::MULHS, VT, Expand);
00416     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
00417     setOperationAction(ISD::MULHU, VT, Expand);
00418     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
00419 
00420     setOperationAction(ISD::BSWAP, VT, Expand);
00421   }
00422 
00423   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
00424   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
00425 
00426   if (Subtarget->hasNEON()) {
00427     addDRTypeForNEON(MVT::v2f32);
00428     addDRTypeForNEON(MVT::v8i8);
00429     addDRTypeForNEON(MVT::v4i16);
00430     addDRTypeForNEON(MVT::v2i32);
00431     addDRTypeForNEON(MVT::v1i64);
00432 
00433     addQRTypeForNEON(MVT::v4f32);
00434     addQRTypeForNEON(MVT::v2f64);
00435     addQRTypeForNEON(MVT::v16i8);
00436     addQRTypeForNEON(MVT::v8i16);
00437     addQRTypeForNEON(MVT::v4i32);
00438     addQRTypeForNEON(MVT::v2i64);
00439 
00440     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
00441     // neither Neon nor VFP support any arithmetic operations on it.
00442     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
00443     // supported for v4f32.
00444     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
00445     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
00446     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
00447     // FIXME: Code duplication: FDIV and FREM are expanded always, see
00448     // ARMTargetLowering::addTypeForNEON method for details.
00449     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
00450     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
00451     // FIXME: Create unittest.
00452     // In another words, find a way when "copysign" appears in DAG with vector
00453     // operands.
00454     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
00455     // FIXME: Code duplication: SETCC has custom operation action, see
00456     // ARMTargetLowering::addTypeForNEON method for details.
00457     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
00458     // FIXME: Create unittest for FNEG and for FABS.
00459     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
00460     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
00461     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
00462     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
00463     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
00464     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
00465     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
00466     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
00467     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
00468     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
00469     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
00470     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
00471     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
00472     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
00473     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
00474     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
00475     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
00476     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
00477     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
00478 
00479     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
00480     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
00481     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
00482     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
00483     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
00484     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
00485     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
00486     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
00487     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
00488     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
00489     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
00490     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
00491     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
00492     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
00493     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
00494 
00495     // Mark v2f32 intrinsics.
00496     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
00497     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
00498     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
00499     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
00500     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
00501     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
00502     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
00503     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
00504     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
00505     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
00506     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
00507     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
00508     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
00509     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
00510     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
00511 
00512     // Neon does not support some operations on v1i64 and v2i64 types.
00513     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
00514     // Custom handling for some quad-vector types to detect VMULL.
00515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
00516     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
00517     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
00518     // Custom handling for some vector types to avoid expensive expansions
00519     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
00520     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
00521     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
00522     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
00523     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
00524     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
00525     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
00526     // a destination type that is wider than the source, and nor does
00527     // it have a FP_TO_[SU]INT instruction with a narrower destination than
00528     // source.
00529     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
00530     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
00531     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
00532     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
00533 
00534     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
00535     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
00536 
00537     // NEON does not have single instruction CTPOP for vectors with element
00538     // types wider than 8-bits.  However, custom lowering can leverage the
00539     // v8i8/v16i8 vcnt instruction.
00540     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
00541     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
00542     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
00543     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
00544 
00545     // NEON only has FMA instructions as of VFP4.
00546     if (!Subtarget->hasVFP4()) {
00547       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
00548       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
00549     }
00550 
00551     setTargetDAGCombine(ISD::INTRINSIC_VOID);
00552     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
00553     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
00554     setTargetDAGCombine(ISD::SHL);
00555     setTargetDAGCombine(ISD::SRL);
00556     setTargetDAGCombine(ISD::SRA);
00557     setTargetDAGCombine(ISD::SIGN_EXTEND);
00558     setTargetDAGCombine(ISD::ZERO_EXTEND);
00559     setTargetDAGCombine(ISD::ANY_EXTEND);
00560     setTargetDAGCombine(ISD::SELECT_CC);
00561     setTargetDAGCombine(ISD::BUILD_VECTOR);
00562     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
00563     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
00564     setTargetDAGCombine(ISD::STORE);
00565     setTargetDAGCombine(ISD::FP_TO_SINT);
00566     setTargetDAGCombine(ISD::FP_TO_UINT);
00567     setTargetDAGCombine(ISD::FDIV);
00568     setTargetDAGCombine(ISD::LOAD);
00569 
00570     // It is legal to extload from v4i8 to v4i16 or v4i32.
00571     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
00572                   MVT::v4i16, MVT::v2i16,
00573                   MVT::v2i32};
00574     for (unsigned i = 0; i < 6; ++i) {
00575       for (MVT VT : MVT::integer_vector_valuetypes()) {
00576         setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
00577         setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
00578         setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
00579       }
00580     }
00581   }
00582 
00583   // ARM and Thumb2 support UMLAL/SMLAL.
00584   if (!Subtarget->isThumb1Only())
00585     setTargetDAGCombine(ISD::ADDC);
00586 
00587   if (Subtarget->isFPOnlySP()) {
00588     // When targetting a floating-point unit with only single-precision
00589     // operations, f64 is legal for the few double-precision instructions which
00590     // are present However, no double-precision operations other than moves,
00591     // loads and stores are provided by the hardware.
00592     setOperationAction(ISD::FADD,       MVT::f64, Expand);
00593     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
00594     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
00595     setOperationAction(ISD::FMA,        MVT::f64, Expand);
00596     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
00597     setOperationAction(ISD::FREM,       MVT::f64, Expand);
00598     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
00599     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
00600     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
00601     setOperationAction(ISD::FABS,       MVT::f64, Expand);
00602     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
00603     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
00604     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
00605     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
00606     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
00607     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
00608     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
00609     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
00610     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
00611     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
00612     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
00613     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
00614     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
00615     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
00616     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
00617     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
00618     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
00619   }
00620 
00621   computeRegisterProperties();
00622 
00623   // ARM does not have floating-point extending loads.
00624   for (MVT VT : MVT::fp_valuetypes()) {
00625     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
00626     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
00627   }
00628 
00629   // ... or truncating stores
00630   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
00631   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
00632   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
00633 
00634   // ARM does not have i1 sign extending load.
00635   for (MVT VT : MVT::integer_valuetypes())
00636     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
00637 
00638   // ARM supports all 4 flavors of integer indexed load / store.
00639   if (!Subtarget->isThumb1Only()) {
00640     for (unsigned im = (unsigned)ISD::PRE_INC;
00641          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
00642       setIndexedLoadAction(im,  MVT::i1,  Legal);
00643       setIndexedLoadAction(im,  MVT::i8,  Legal);
00644       setIndexedLoadAction(im,  MVT::i16, Legal);
00645       setIndexedLoadAction(im,  MVT::i32, Legal);
00646       setIndexedStoreAction(im, MVT::i1,  Legal);
00647       setIndexedStoreAction(im, MVT::i8,  Legal);
00648       setIndexedStoreAction(im, MVT::i16, Legal);
00649       setIndexedStoreAction(im, MVT::i32, Legal);
00650     }
00651   }
00652 
00653   setOperationAction(ISD::SADDO, MVT::i32, Custom);
00654   setOperationAction(ISD::UADDO, MVT::i32, Custom);
00655   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
00656   setOperationAction(ISD::USUBO, MVT::i32, Custom);
00657 
00658   // i64 operation support.
00659   setOperationAction(ISD::MUL,     MVT::i64, Expand);
00660   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
00661   if (Subtarget->isThumb1Only()) {
00662     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
00663     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00664   }
00665   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
00666       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
00667     setOperationAction(ISD::MULHS, MVT::i32, Expand);
00668 
00669   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
00670   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
00671   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
00672   setOperationAction(ISD::SRL,       MVT::i64, Custom);
00673   setOperationAction(ISD::SRA,       MVT::i64, Custom);
00674 
00675   if (!Subtarget->isThumb1Only()) {
00676     // FIXME: We should do this for Thumb1 as well.
00677     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
00678     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
00679     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
00680     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
00681   }
00682 
00683   // ARM does not have ROTL.
00684   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
00685   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
00686   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
00687   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
00688     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
00689 
00690   // These just redirect to CTTZ and CTLZ on ARM.
00691   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
00692   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
00693 
00694   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
00695 
00696   // Only ARMv6 has BSWAP.
00697   if (!Subtarget->hasV6Ops())
00698     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
00699 
00700   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
00701       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
00702     // These are expanded into libcalls if the cpu doesn't have HW divider.
00703     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
00704     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
00705   }
00706 
00707   // FIXME: Also set divmod for SREM on EABI
00708   setOperationAction(ISD::SREM,  MVT::i32, Expand);
00709   setOperationAction(ISD::UREM,  MVT::i32, Expand);
00710   // Register based DivRem for AEABI (RTABI 4.2)
00711   if (Subtarget->isTargetAEABI()) {
00712     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
00713     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
00714     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
00715     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
00716     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
00717     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
00718     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
00719     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
00720 
00721     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
00722     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
00723     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
00724     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
00725     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
00726     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
00727     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
00728     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
00729 
00730     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
00731     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
00732   } else {
00733     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
00734     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
00735   }
00736 
00737   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
00738   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
00739   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
00740   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00741   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
00742 
00743   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00744 
00745   // Use the default implementation.
00746   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
00747   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
00748   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
00749   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
00750   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
00751   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
00752 
00753   if (!Subtarget->isTargetMachO()) {
00754     // Non-MachO platforms may return values in these registers via the
00755     // personality function.
00756     setExceptionPointerRegister(ARM::R0);
00757     setExceptionSelectorRegister(ARM::R1);
00758   }
00759 
00760   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
00761     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
00762   else
00763     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
00764 
00765   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
00766   // the default expansion. If we are targeting a single threaded system,
00767   // then set them all for expand so we can lower them later into their
00768   // non-atomic form.
00769   if (TM.Options.ThreadModel == ThreadModel::Single)
00770     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
00771   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
00772     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
00773     // to ldrex/strex loops already.
00774     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
00775 
00776     // On v8, we have particularly efficient implementations of atomic fences
00777     // if they can be combined with nearby atomic loads and stores.
00778     if (!Subtarget->hasV8Ops()) {
00779       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
00780       setInsertFencesForAtomic(true);
00781     }
00782   } else {
00783     // If there's anything we can use as a barrier, go through custom lowering
00784     // for ATOMIC_FENCE.
00785     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
00786                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
00787 
00788     // Set them all for expansion, which will force libcalls.
00789     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
00790     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
00791     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
00792     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
00793     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
00794     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
00795     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
00796     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
00797     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
00798     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
00799     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
00800     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
00801     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
00802     // Unordered/Monotonic case.
00803     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
00804     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
00805   }
00806 
00807   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
00808 
00809   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
00810   if (!Subtarget->hasV6Ops()) {
00811     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
00812     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
00813   }
00814   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00815 
00816   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
00817       !Subtarget->isThumb1Only()) {
00818     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
00819     // iff target supports vfp2.
00820     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
00821     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
00822   }
00823 
00824   // We want to custom lower some of our intrinsics.
00825   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
00826   if (Subtarget->isTargetDarwin()) {
00827     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
00828     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
00829     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
00830   }
00831 
00832   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
00833   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
00834   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
00835   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
00836   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
00837   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
00838   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
00839   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
00840   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
00841 
00842   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
00843   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
00844   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
00845   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
00846   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
00847 
00848   // We don't support sin/cos/fmod/copysign/pow
00849   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
00850   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
00851   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
00852   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
00853   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
00854   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
00855   setOperationAction(ISD::FREM,      MVT::f64, Expand);
00856   setOperationAction(ISD::FREM,      MVT::f32, Expand);
00857   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
00858       !Subtarget->isThumb1Only()) {
00859     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
00860     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
00861   }
00862   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
00863   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
00864 
00865   if (!Subtarget->hasVFP4()) {
00866     setOperationAction(ISD::FMA, MVT::f64, Expand);
00867     setOperationAction(ISD::FMA, MVT::f32, Expand);
00868   }
00869 
00870   // Various VFP goodness
00871   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
00872     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
00873     if (Subtarget->hasVFP2()) {
00874       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
00875       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
00876       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
00877       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
00878     }
00879 
00880     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
00881     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
00882       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
00883       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
00884     }
00885 
00886     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
00887     if (!Subtarget->hasFP16()) {
00888       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
00889       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
00890     }
00891   }
00892 
00893   // Combine sin / cos into one node or libcall if possible.
00894   if (Subtarget->hasSinCos()) {
00895     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
00896     setLibcallName(RTLIB::SINCOS_F64, "sincos");
00897     if (Subtarget->getTargetTriple().isiOS()) {
00898       // For iOS, we don't want to the normal expansion of a libcall to
00899       // sincos. We want to issue a libcall to __sincos_stret.
00900       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
00901       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
00902     }
00903   }
00904 
00905   // FP-ARMv8 implements a lot of rounding-like FP operations.
00906   if (Subtarget->hasFPARMv8()) {
00907     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
00908     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
00909     setOperationAction(ISD::FROUND, MVT::f32, Legal);
00910     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
00911     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
00912     setOperationAction(ISD::FRINT, MVT::f32, Legal);
00913     if (!Subtarget->isFPOnlySP()) {
00914       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
00915       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
00916       setOperationAction(ISD::FROUND, MVT::f64, Legal);
00917       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
00918       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
00919       setOperationAction(ISD::FRINT, MVT::f64, Legal);
00920     }
00921   }
00922   // We have target-specific dag combine patterns for the following nodes:
00923   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
00924   setTargetDAGCombine(ISD::ADD);
00925   setTargetDAGCombine(ISD::SUB);
00926   setTargetDAGCombine(ISD::MUL);
00927   setTargetDAGCombine(ISD::AND);
00928   setTargetDAGCombine(ISD::OR);
00929   setTargetDAGCombine(ISD::XOR);
00930 
00931   if (Subtarget->hasV6Ops())
00932     setTargetDAGCombine(ISD::SRL);
00933 
00934   setStackPointerRegisterToSaveRestore(ARM::SP);
00935 
00936   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
00937       !Subtarget->hasVFP2())
00938     setSchedulingPreference(Sched::RegPressure);
00939   else
00940     setSchedulingPreference(Sched::Hybrid);
00941 
00942   //// temporary - rewrite interface to use type
00943   MaxStoresPerMemset = 8;
00944   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
00945   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
00946   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
00947   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
00948   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
00949 
00950   // On ARM arguments smaller than 4 bytes are extended, so all arguments
00951   // are at least 4 bytes aligned.
00952   setMinStackArgumentAlignment(4);
00953 
00954   // Prefer likely predicted branches to selects on out-of-order cores.
00955   PredictableSelectIsExpensive = Subtarget->isLikeA9();
00956 
00957   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
00958 }
00959 
00960 // FIXME: It might make sense to define the representative register class as the
00961 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
00962 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
00963 // SPR's representative would be DPR_VFP2. This should work well if register
00964 // pressure tracking were modified such that a register use would increment the
00965 // pressure of the register class's representative and all of it's super
00966 // classes' representatives transitively. We have not implemented this because
00967 // of the difficulty prior to coalescing of modeling operand register classes
00968 // due to the common occurrence of cross class copies and subregister insertions
00969 // and extractions.
00970 std::pair<const TargetRegisterClass*, uint8_t>
00971 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
00972   const TargetRegisterClass *RRC = nullptr;
00973   uint8_t Cost = 1;
00974   switch (VT.SimpleTy) {
00975   default:
00976     return TargetLowering::findRepresentativeClass(VT);
00977   // Use DPR as representative register class for all floating point
00978   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
00979   // the cost is 1 for both f32 and f64.
00980   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
00981   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
00982     RRC = &ARM::DPRRegClass;
00983     // When NEON is used for SP, only half of the register file is available
00984     // because operations that define both SP and DP results will be constrained
00985     // to the VFP2 class (D0-D15). We currently model this constraint prior to
00986     // coalescing by double-counting the SP regs. See the FIXME above.
00987     if (Subtarget->useNEONForSinglePrecisionFP())
00988       Cost = 2;
00989     break;
00990   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
00991   case MVT::v4f32: case MVT::v2f64:
00992     RRC = &ARM::DPRRegClass;
00993     Cost = 2;
00994     break;
00995   case MVT::v4i64:
00996     RRC = &ARM::DPRRegClass;
00997     Cost = 4;
00998     break;
00999   case MVT::v8i64:
01000     RRC = &ARM::DPRRegClass;
01001     Cost = 8;
01002     break;
01003   }
01004   return std::make_pair(RRC, Cost);
01005 }
01006 
01007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
01008   switch (Opcode) {
01009   default: return nullptr;
01010   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
01011   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
01012   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
01013   case ARMISD::CALL:          return "ARMISD::CALL";
01014   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
01015   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
01016   case ARMISD::tCALL:         return "ARMISD::tCALL";
01017   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
01018   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
01019   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
01020   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
01021   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
01022   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
01023   case ARMISD::CMP:           return "ARMISD::CMP";
01024   case ARMISD::CMN:           return "ARMISD::CMN";
01025   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
01026   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
01027   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
01028   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
01029   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
01030 
01031   case ARMISD::CMOV:          return "ARMISD::CMOV";
01032 
01033   case ARMISD::RBIT:          return "ARMISD::RBIT";
01034 
01035   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
01036   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
01037   case ARMISD::SITOF:         return "ARMISD::SITOF";
01038   case ARMISD::UITOF:         return "ARMISD::UITOF";
01039 
01040   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
01041   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
01042   case ARMISD::RRX:           return "ARMISD::RRX";
01043 
01044   case ARMISD::ADDC:          return "ARMISD::ADDC";
01045   case ARMISD::ADDE:          return "ARMISD::ADDE";
01046   case ARMISD::SUBC:          return "ARMISD::SUBC";
01047   case ARMISD::SUBE:          return "ARMISD::SUBE";
01048 
01049   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
01050   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
01051 
01052   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
01053   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
01054 
01055   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
01056 
01057   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
01058 
01059   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
01060 
01061   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
01062 
01063   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
01064 
01065   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
01066 
01067   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
01068   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
01069   case ARMISD::VCGE:          return "ARMISD::VCGE";
01070   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
01071   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
01072   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
01073   case ARMISD::VCGT:          return "ARMISD::VCGT";
01074   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
01075   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
01076   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
01077   case ARMISD::VTST:          return "ARMISD::VTST";
01078 
01079   case ARMISD::VSHL:          return "ARMISD::VSHL";
01080   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
01081   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
01082   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
01083   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
01084   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
01085   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
01086   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
01087   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
01088   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
01089   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
01090   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
01091   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
01092   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
01093   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
01094   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
01095   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
01096   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
01097   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
01098   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
01099   case ARMISD::VDUP:          return "ARMISD::VDUP";
01100   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
01101   case ARMISD::VEXT:          return "ARMISD::VEXT";
01102   case ARMISD::VREV64:        return "ARMISD::VREV64";
01103   case ARMISD::VREV32:        return "ARMISD::VREV32";
01104   case ARMISD::VREV16:        return "ARMISD::VREV16";
01105   case ARMISD::VZIP:          return "ARMISD::VZIP";
01106   case ARMISD::VUZP:          return "ARMISD::VUZP";
01107   case ARMISD::VTRN:          return "ARMISD::VTRN";
01108   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
01109   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
01110   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
01111   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
01112   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
01113   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
01114   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
01115   case ARMISD::FMAX:          return "ARMISD::FMAX";
01116   case ARMISD::FMIN:          return "ARMISD::FMIN";
01117   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
01118   case ARMISD::VMINNM:        return "ARMISD::VMIN";
01119   case ARMISD::BFI:           return "ARMISD::BFI";
01120   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
01121   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
01122   case ARMISD::VBSL:          return "ARMISD::VBSL";
01123   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
01124   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
01125   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
01126   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
01127   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
01128   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
01129   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
01130   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
01131   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
01132   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
01133   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
01134   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
01135   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
01136   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
01137   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
01138   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
01139   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
01140   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
01141   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
01142   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
01143   }
01144 }
01145 
01146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
01147   if (!VT.isVector()) return getPointerTy();
01148   return VT.changeVectorElementTypeToInteger();
01149 }
01150 
01151 /// getRegClassFor - Return the register class that should be used for the
01152 /// specified value type.
01153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
01154   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
01155   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
01156   // load / store 4 to 8 consecutive D registers.
01157   if (Subtarget->hasNEON()) {
01158     if (VT == MVT::v4i64)
01159       return &ARM::QQPRRegClass;
01160     if (VT == MVT::v8i64)
01161       return &ARM::QQQQPRRegClass;
01162   }
01163   return TargetLowering::getRegClassFor(VT);
01164 }
01165 
01166 // Create a fast isel object.
01167 FastISel *
01168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
01169                                   const TargetLibraryInfo *libInfo) const {
01170   return ARM::createFastISel(funcInfo, libInfo);
01171 }
01172 
01173 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
01174 /// be used for loads / stores from the global.
01175 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
01176   return (Subtarget->isThumb1Only() ? 127 : 4095);
01177 }
01178 
01179 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
01180   unsigned NumVals = N->getNumValues();
01181   if (!NumVals)
01182     return Sched::RegPressure;
01183 
01184   for (unsigned i = 0; i != NumVals; ++i) {
01185     EVT VT = N->getValueType(i);
01186     if (VT == MVT::Glue || VT == MVT::Other)
01187       continue;
01188     if (VT.isFloatingPoint() || VT.isVector())
01189       return Sched::ILP;
01190   }
01191 
01192   if (!N->isMachineOpcode())
01193     return Sched::RegPressure;
01194 
01195   // Load are scheduled for latency even if there instruction itinerary
01196   // is not available.
01197   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
01198   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01199 
01200   if (MCID.getNumDefs() == 0)
01201     return Sched::RegPressure;
01202   if (!Itins->isEmpty() &&
01203       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
01204     return Sched::ILP;
01205 
01206   return Sched::RegPressure;
01207 }
01208 
01209 //===----------------------------------------------------------------------===//
01210 // Lowering Code
01211 //===----------------------------------------------------------------------===//
01212 
01213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
01214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
01215   switch (CC) {
01216   default: llvm_unreachable("Unknown condition code!");
01217   case ISD::SETNE:  return ARMCC::NE;
01218   case ISD::SETEQ:  return ARMCC::EQ;
01219   case ISD::SETGT:  return ARMCC::GT;
01220   case ISD::SETGE:  return ARMCC::GE;
01221   case ISD::SETLT:  return ARMCC::LT;
01222   case ISD::SETLE:  return ARMCC::LE;
01223   case ISD::SETUGT: return ARMCC::HI;
01224   case ISD::SETUGE: return ARMCC::HS;
01225   case ISD::SETULT: return ARMCC::LO;
01226   case ISD::SETULE: return ARMCC::LS;
01227   }
01228 }
01229 
01230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
01231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
01232                         ARMCC::CondCodes &CondCode2) {
01233   CondCode2 = ARMCC::AL;
01234   switch (CC) {
01235   default: llvm_unreachable("Unknown FP condition!");
01236   case ISD::SETEQ:
01237   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
01238   case ISD::SETGT:
01239   case ISD::SETOGT: CondCode = ARMCC::GT; break;
01240   case ISD::SETGE:
01241   case ISD::SETOGE: CondCode = ARMCC::GE; break;
01242   case ISD::SETOLT: CondCode = ARMCC::MI; break;
01243   case ISD::SETOLE: CondCode = ARMCC::LS; break;
01244   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
01245   case ISD::SETO:   CondCode = ARMCC::VC; break;
01246   case ISD::SETUO:  CondCode = ARMCC::VS; break;
01247   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
01248   case ISD::SETUGT: CondCode = ARMCC::HI; break;
01249   case ISD::SETUGE: CondCode = ARMCC::PL; break;
01250   case ISD::SETLT:
01251   case ISD::SETULT: CondCode = ARMCC::LT; break;
01252   case ISD::SETLE:
01253   case ISD::SETULE: CondCode = ARMCC::LE; break;
01254   case ISD::SETNE:
01255   case ISD::SETUNE: CondCode = ARMCC::NE; break;
01256   }
01257 }
01258 
01259 //===----------------------------------------------------------------------===//
01260 //                      Calling Convention Implementation
01261 //===----------------------------------------------------------------------===//
01262 
01263 #include "ARMGenCallingConv.inc"
01264 
01265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
01266 /// account presence of floating point hardware and calling convention
01267 /// limitations, such as support for variadic functions.
01268 CallingConv::ID
01269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
01270                                            bool isVarArg) const {
01271   switch (CC) {
01272   default:
01273     llvm_unreachable("Unsupported calling convention");
01274   case CallingConv::ARM_AAPCS:
01275   case CallingConv::ARM_APCS:
01276   case CallingConv::GHC:
01277     return CC;
01278   case CallingConv::ARM_AAPCS_VFP:
01279     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
01280   case CallingConv::C:
01281     if (!Subtarget->isAAPCS_ABI())
01282       return CallingConv::ARM_APCS;
01283     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
01284              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
01285              !isVarArg)
01286       return CallingConv::ARM_AAPCS_VFP;
01287     else
01288       return CallingConv::ARM_AAPCS;
01289   case CallingConv::Fast:
01290     if (!Subtarget->isAAPCS_ABI()) {
01291       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
01292         return CallingConv::Fast;
01293       return CallingConv::ARM_APCS;
01294     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
01295       return CallingConv::ARM_AAPCS_VFP;
01296     else
01297       return CallingConv::ARM_AAPCS;
01298   }
01299 }
01300 
01301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
01302 /// CallingConvention.
01303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
01304                                                  bool Return,
01305                                                  bool isVarArg) const {
01306   switch (getEffectiveCallingConv(CC, isVarArg)) {
01307   default:
01308     llvm_unreachable("Unsupported calling convention");
01309   case CallingConv::ARM_APCS:
01310     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
01311   case CallingConv::ARM_AAPCS:
01312     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
01313   case CallingConv::ARM_AAPCS_VFP:
01314     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
01315   case CallingConv::Fast:
01316     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
01317   case CallingConv::GHC:
01318     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
01319   }
01320 }
01321 
01322 /// LowerCallResult - Lower the result values of a call into the
01323 /// appropriate copies out of appropriate physical registers.
01324 SDValue
01325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
01326                                    CallingConv::ID CallConv, bool isVarArg,
01327                                    const SmallVectorImpl<ISD::InputArg> &Ins,
01328                                    SDLoc dl, SelectionDAG &DAG,
01329                                    SmallVectorImpl<SDValue> &InVals,
01330                                    bool isThisReturn, SDValue ThisVal) const {
01331 
01332   // Assign locations to each value returned by this call.
01333   SmallVector<CCValAssign, 16> RVLocs;
01334   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
01335                     *DAG.getContext(), Call);
01336   CCInfo.AnalyzeCallResult(Ins,
01337                            CCAssignFnForNode(CallConv, /* Return*/ true,
01338                                              isVarArg));
01339 
01340   // Copy all of the result registers out of their specified physreg.
01341   for (unsigned i = 0; i != RVLocs.size(); ++i) {
01342     CCValAssign VA = RVLocs[i];
01343 
01344     // Pass 'this' value directly from the argument to return value, to avoid
01345     // reg unit interference
01346     if (i == 0 && isThisReturn) {
01347       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
01348              "unexpected return calling convention register assignment");
01349       InVals.push_back(ThisVal);
01350       continue;
01351     }
01352 
01353     SDValue Val;
01354     if (VA.needsCustom()) {
01355       // Handle f64 or half of a v2f64.
01356       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
01357                                       InFlag);
01358       Chain = Lo.getValue(1);
01359       InFlag = Lo.getValue(2);
01360       VA = RVLocs[++i]; // skip ahead to next loc
01361       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
01362                                       InFlag);
01363       Chain = Hi.getValue(1);
01364       InFlag = Hi.getValue(2);
01365       if (!Subtarget->isLittle())
01366         std::swap (Lo, Hi);
01367       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
01368 
01369       if (VA.getLocVT() == MVT::v2f64) {
01370         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
01371         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
01372                           DAG.getConstant(0, MVT::i32));
01373 
01374         VA = RVLocs[++i]; // skip ahead to next loc
01375         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
01376         Chain = Lo.getValue(1);
01377         InFlag = Lo.getValue(2);
01378         VA = RVLocs[++i]; // skip ahead to next loc
01379         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
01380         Chain = Hi.getValue(1);
01381         InFlag = Hi.getValue(2);
01382         if (!Subtarget->isLittle())
01383           std::swap (Lo, Hi);
01384         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
01385         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
01386                           DAG.getConstant(1, MVT::i32));
01387       }
01388     } else {
01389       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
01390                                InFlag);
01391       Chain = Val.getValue(1);
01392       InFlag = Val.getValue(2);
01393     }
01394 
01395     switch (VA.getLocInfo()) {
01396     default: llvm_unreachable("Unknown loc info!");
01397     case CCValAssign::Full: break;
01398     case CCValAssign::BCvt:
01399       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
01400       break;
01401     }
01402 
01403     InVals.push_back(Val);
01404   }
01405 
01406   return Chain;
01407 }
01408 
01409 /// LowerMemOpCallTo - Store the argument to the stack.
01410 SDValue
01411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
01412                                     SDValue StackPtr, SDValue Arg,
01413                                     SDLoc dl, SelectionDAG &DAG,
01414                                     const CCValAssign &VA,
01415                                     ISD::ArgFlagsTy Flags) const {
01416   unsigned LocMemOffset = VA.getLocMemOffset();
01417   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
01418   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
01419   return DAG.getStore(Chain, dl, Arg, PtrOff,
01420                       MachinePointerInfo::getStack(LocMemOffset),
01421                       false, false, 0);
01422 }
01423 
01424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
01425                                          SDValue Chain, SDValue &Arg,
01426                                          RegsToPassVector &RegsToPass,
01427                                          CCValAssign &VA, CCValAssign &NextVA,
01428                                          SDValue &StackPtr,
01429                                          SmallVectorImpl<SDValue> &MemOpChains,
01430                                          ISD::ArgFlagsTy Flags) const {
01431 
01432   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
01433                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
01434   unsigned id = Subtarget->isLittle() ? 0 : 1;
01435   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
01436 
01437   if (NextVA.isRegLoc())
01438     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
01439   else {
01440     assert(NextVA.isMemLoc());
01441     if (!StackPtr.getNode())
01442       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
01443 
01444     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
01445                                            dl, DAG, NextVA,
01446                                            Flags));
01447   }
01448 }
01449 
01450 /// LowerCall - Lowering a call into a callseq_start <-
01451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
01452 /// nodes.
01453 SDValue
01454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
01455                              SmallVectorImpl<SDValue> &InVals) const {
01456   SelectionDAG &DAG                     = CLI.DAG;
01457   SDLoc &dl                          = CLI.DL;
01458   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
01459   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
01460   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
01461   SDValue Chain                         = CLI.Chain;
01462   SDValue Callee                        = CLI.Callee;
01463   bool &isTailCall                      = CLI.IsTailCall;
01464   CallingConv::ID CallConv              = CLI.CallConv;
01465   bool doesNotRet                       = CLI.DoesNotReturn;
01466   bool isVarArg                         = CLI.IsVarArg;
01467 
01468   MachineFunction &MF = DAG.getMachineFunction();
01469   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
01470   bool isThisReturn   = false;
01471   bool isSibCall      = false;
01472 
01473   // Disable tail calls if they're not supported.
01474   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
01475     isTailCall = false;
01476 
01477   if (isTailCall) {
01478     // Check if it's really possible to do a tail call.
01479     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
01480                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
01481                                                    Outs, OutVals, Ins, DAG);
01482     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
01483       report_fatal_error("failed to perform tail call elimination on a call "
01484                          "site marked musttail");
01485     // We don't support GuaranteedTailCallOpt for ARM, only automatically
01486     // detected sibcalls.
01487     if (isTailCall) {
01488       ++NumTailCalls;
01489       isSibCall = true;
01490     }
01491   }
01492 
01493   // Analyze operands of the call, assigning locations to each operand.
01494   SmallVector<CCValAssign, 16> ArgLocs;
01495   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
01496                     *DAG.getContext(), Call);
01497   CCInfo.AnalyzeCallOperands(Outs,
01498                              CCAssignFnForNode(CallConv, /* Return*/ false,
01499                                                isVarArg));
01500 
01501   // Get a count of how many bytes are to be pushed on the stack.
01502   unsigned NumBytes = CCInfo.getNextStackOffset();
01503 
01504   // For tail calls, memory operands are available in our caller's stack.
01505   if (isSibCall)
01506     NumBytes = 0;
01507 
01508   // Adjust the stack pointer for the new arguments...
01509   // These operations are automatically eliminated by the prolog/epilog pass
01510   if (!isSibCall)
01511     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
01512                                  dl);
01513 
01514   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
01515 
01516   RegsToPassVector RegsToPass;
01517   SmallVector<SDValue, 8> MemOpChains;
01518 
01519   // Walk the register/memloc assignments, inserting copies/loads.  In the case
01520   // of tail call optimization, arguments are handled later.
01521   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
01522        i != e;
01523        ++i, ++realArgIdx) {
01524     CCValAssign &VA = ArgLocs[i];
01525     SDValue Arg = OutVals[realArgIdx];
01526     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
01527     bool isByVal = Flags.isByVal();
01528 
01529     // Promote the value if needed.
01530     switch (VA.getLocInfo()) {
01531     default: llvm_unreachable("Unknown loc info!");
01532     case CCValAssign::Full: break;
01533     case CCValAssign::SExt:
01534       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
01535       break;
01536     case CCValAssign::ZExt:
01537       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
01538       break;
01539     case CCValAssign::AExt:
01540       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
01541       break;
01542     case CCValAssign::BCvt:
01543       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
01544       break;
01545     }
01546 
01547     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
01548     if (VA.needsCustom()) {
01549       if (VA.getLocVT() == MVT::v2f64) {
01550         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
01551                                   DAG.getConstant(0, MVT::i32));
01552         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
01553                                   DAG.getConstant(1, MVT::i32));
01554 
01555         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
01556                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
01557 
01558         VA = ArgLocs[++i]; // skip ahead to next loc
01559         if (VA.isRegLoc()) {
01560           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
01561                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
01562         } else {
01563           assert(VA.isMemLoc());
01564 
01565           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
01566                                                  dl, DAG, VA, Flags));
01567         }
01568       } else {
01569         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
01570                          StackPtr, MemOpChains, Flags);
01571       }
01572     } else if (VA.isRegLoc()) {
01573       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
01574         assert(VA.getLocVT() == MVT::i32 &&
01575                "unexpected calling convention register assignment");
01576         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
01577                "unexpected use of 'returned'");
01578         isThisReturn = true;
01579       }
01580       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
01581     } else if (isByVal) {
01582       assert(VA.isMemLoc());
01583       unsigned offset = 0;
01584 
01585       // True if this byval aggregate will be split between registers
01586       // and memory.
01587       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
01588       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
01589 
01590       if (CurByValIdx < ByValArgsCount) {
01591 
01592         unsigned RegBegin, RegEnd;
01593         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
01594 
01595         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
01596         unsigned int i, j;
01597         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
01598           SDValue Const = DAG.getConstant(4*i, MVT::i32);
01599           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
01600           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
01601                                      MachinePointerInfo(),
01602                                      false, false, false,
01603                                      DAG.InferPtrAlignment(AddArg));
01604           MemOpChains.push_back(Load.getValue(1));
01605           RegsToPass.push_back(std::make_pair(j, Load));
01606         }
01607 
01608         // If parameter size outsides register area, "offset" value
01609         // helps us to calculate stack slot for remained part properly.
01610         offset = RegEnd - RegBegin;
01611 
01612         CCInfo.nextInRegsParam();
01613       }
01614 
01615       if (Flags.getByValSize() > 4*offset) {
01616         unsigned LocMemOffset = VA.getLocMemOffset();
01617         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
01618         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
01619                                   StkPtrOff);
01620         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
01621         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
01622         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
01623                                            MVT::i32);
01624         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
01625 
01626         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
01627         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
01628         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
01629                                           Ops));
01630       }
01631     } else if (!isSibCall) {
01632       assert(VA.isMemLoc());
01633 
01634       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
01635                                              dl, DAG, VA, Flags));
01636     }
01637   }
01638 
01639   if (!MemOpChains.empty())
01640     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
01641 
01642   // Build a sequence of copy-to-reg nodes chained together with token chain
01643   // and flag operands which copy the outgoing args into the appropriate regs.
01644   SDValue InFlag;
01645   // Tail call byval lowering might overwrite argument registers so in case of
01646   // tail call optimization the copies to registers are lowered later.
01647   if (!isTailCall)
01648     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01649       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
01650                                RegsToPass[i].second, InFlag);
01651       InFlag = Chain.getValue(1);
01652     }
01653 
01654   // For tail calls lower the arguments to the 'real' stack slot.
01655   if (isTailCall) {
01656     // Force all the incoming stack arguments to be loaded from the stack
01657     // before any new outgoing arguments are stored to the stack, because the
01658     // outgoing stack slots may alias the incoming argument stack slots, and
01659     // the alias isn't otherwise explicit. This is slightly more conservative
01660     // than necessary, because it means that each store effectively depends
01661     // on every argument instead of just those arguments it would clobber.
01662 
01663     // Do not flag preceding copytoreg stuff together with the following stuff.
01664     InFlag = SDValue();
01665     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
01666       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
01667                                RegsToPass[i].second, InFlag);
01668       InFlag = Chain.getValue(1);
01669     }
01670     InFlag = SDValue();
01671   }
01672 
01673   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
01674   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
01675   // node so that legalize doesn't hack it.
01676   bool isDirect = false;
01677   bool isARMFunc = false;
01678   bool isLocalARMFunc = false;
01679   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
01680 
01681   if (EnableARMLongCalls) {
01682     assert((Subtarget->isTargetWindows() ||
01683             getTargetMachine().getRelocationModel() == Reloc::Static) &&
01684            "long-calls with non-static relocation model!");
01685     // Handle a global address or an external symbol. If it's not one of
01686     // those, the target's already in a register, so we don't need to do
01687     // anything extra.
01688     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01689       const GlobalValue *GV = G->getGlobal();
01690       // Create a constant pool entry for the callee address
01691       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01692       ARMConstantPoolValue *CPV =
01693         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
01694 
01695       // Get the address of the callee into a register
01696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01698       Callee = DAG.getLoad(getPointerTy(), dl,
01699                            DAG.getEntryNode(), CPAddr,
01700                            MachinePointerInfo::getConstantPool(),
01701                            false, false, false, 0);
01702     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
01703       const char *Sym = S->getSymbol();
01704 
01705       // Create a constant pool entry for the callee address
01706       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01707       ARMConstantPoolValue *CPV =
01708         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
01709                                       ARMPCLabelIndex, 0);
01710       // Get the address of the callee into a register
01711       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01712       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01713       Callee = DAG.getLoad(getPointerTy(), dl,
01714                            DAG.getEntryNode(), CPAddr,
01715                            MachinePointerInfo::getConstantPool(),
01716                            false, false, false, 0);
01717     }
01718   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
01719     const GlobalValue *GV = G->getGlobal();
01720     isDirect = true;
01721     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
01722     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
01723                    getTargetMachine().getRelocationModel() != Reloc::Static;
01724     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
01725     // ARM call to a local ARM function is predicable.
01726     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
01727     // tBX takes a register source operand.
01728     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
01729       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
01730       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
01731                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
01732                                                       0, ARMII::MO_NONLAZY));
01733       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
01734                            MachinePointerInfo::getGOT(), false, false, true, 0);
01735     } else if (Subtarget->isTargetCOFF()) {
01736       assert(Subtarget->isTargetWindows() &&
01737              "Windows is the only supported COFF target");
01738       unsigned TargetFlags = GV->hasDLLImportStorageClass()
01739                                  ? ARMII::MO_DLLIMPORT
01740                                  : ARMII::MO_NO_FLAG;
01741       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
01742                                           TargetFlags);
01743       if (GV->hasDLLImportStorageClass())
01744         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
01745                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
01746                                          Callee), MachinePointerInfo::getGOT(),
01747                              false, false, false, 0);
01748     } else {
01749       // On ELF targets for PIC code, direct calls should go through the PLT
01750       unsigned OpFlags = 0;
01751       if (Subtarget->isTargetELF() &&
01752           getTargetMachine().getRelocationModel() == Reloc::PIC_)
01753         OpFlags = ARMII::MO_PLT;
01754       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
01755     }
01756   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
01757     isDirect = true;
01758     bool isStub = Subtarget->isTargetMachO() &&
01759                   getTargetMachine().getRelocationModel() != Reloc::Static;
01760     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
01761     // tBX takes a register source operand.
01762     const char *Sym = S->getSymbol();
01763     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
01764       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
01765       ARMConstantPoolValue *CPV =
01766         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
01767                                       ARMPCLabelIndex, 4);
01768       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
01769       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
01770       Callee = DAG.getLoad(getPointerTy(), dl,
01771                            DAG.getEntryNode(), CPAddr,
01772                            MachinePointerInfo::getConstantPool(),
01773                            false, false, false, 0);
01774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
01775       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
01776                            getPointerTy(), Callee, PICLabel);
01777     } else {
01778       unsigned OpFlags = 0;
01779       // On ELF targets for PIC code, direct calls should go through the PLT
01780       if (Subtarget->isTargetELF() &&
01781                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
01782         OpFlags = ARMII::MO_PLT;
01783       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
01784     }
01785   }
01786 
01787   // FIXME: handle tail calls differently.
01788   unsigned CallOpc;
01789   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
01790       AttributeSet::FunctionIndex, Attribute::MinSize);
01791   if (Subtarget->isThumb()) {
01792     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
01793       CallOpc = ARMISD::CALL_NOLINK;
01794     else
01795       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
01796   } else {
01797     if (!isDirect && !Subtarget->hasV5TOps())
01798       CallOpc = ARMISD::CALL_NOLINK;
01799     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
01800                // Emit regular call when code size is the priority
01801                !HasMinSizeAttr)
01802       // "mov lr, pc; b _foo" to avoid confusing the RSP
01803       CallOpc = ARMISD::CALL_NOLINK;
01804     else
01805       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
01806   }
01807 
01808   std::vector<SDValue> Ops;
01809   Ops.push_back(Chain);
01810   Ops.push_back(Callee);
01811 
01812   // Add argument registers to the end of the list so that they are known live
01813   // into the call.
01814   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
01815     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
01816                                   RegsToPass[i].second.getValueType()));
01817 
01818   // Add a register mask operand representing the call-preserved registers.
01819   if (!isTailCall) {
01820     const uint32_t *Mask;
01821     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
01822     if (isThisReturn) {
01823       // For 'this' returns, use the R0-preserving mask if applicable
01824       Mask = ARI->getThisReturnPreservedMask(CallConv);
01825       if (!Mask) {
01826         // Set isThisReturn to false if the calling convention is not one that
01827         // allows 'returned' to be modeled in this way, so LowerCallResult does
01828         // not try to pass 'this' straight through
01829         isThisReturn = false;
01830         Mask = ARI->getCallPreservedMask(CallConv);
01831       }
01832     } else
01833       Mask = ARI->getCallPreservedMask(CallConv);
01834 
01835     assert(Mask && "Missing call preserved mask for calling convention");
01836     Ops.push_back(DAG.getRegisterMask(Mask));
01837   }
01838 
01839   if (InFlag.getNode())
01840     Ops.push_back(InFlag);
01841 
01842   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
01843   if (isTailCall)
01844     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
01845 
01846   // Returns a chain and a flag for retval copy to use.
01847   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
01848   InFlag = Chain.getValue(1);
01849 
01850   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
01851                              DAG.getIntPtrConstant(0, true), InFlag, dl);
01852   if (!Ins.empty())
01853     InFlag = Chain.getValue(1);
01854 
01855   // Handle result values, copying them out of physregs into vregs that we
01856   // return.
01857   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
01858                          InVals, isThisReturn,
01859                          isThisReturn ? OutVals[0] : SDValue());
01860 }
01861 
01862 /// HandleByVal - Every parameter *after* a byval parameter is passed
01863 /// on the stack.  Remember the next parameter register to allocate,
01864 /// and then confiscate the rest of the parameter registers to insure
01865 /// this.
01866 void
01867 ARMTargetLowering::HandleByVal(
01868     CCState *State, unsigned &size, unsigned Align) const {
01869   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
01870   assert((State->getCallOrPrologue() == Prologue ||
01871           State->getCallOrPrologue() == Call) &&
01872          "unhandled ParmContext");
01873 
01874   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
01875     if (Subtarget->isAAPCS_ABI() && Align > 4) {
01876       unsigned AlignInRegs = Align / 4;
01877       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
01878       for (unsigned i = 0; i < Waste; ++i)
01879         reg = State->AllocateReg(GPRArgRegs, 4);
01880     }
01881     if (reg != 0) {
01882       unsigned excess = 4 * (ARM::R4 - reg);
01883 
01884       // Special case when NSAA != SP and parameter size greater than size of
01885       // all remained GPR regs. In that case we can't split parameter, we must
01886       // send it to stack. We also must set NCRN to R4, so waste all
01887       // remained registers.
01888       const unsigned NSAAOffset = State->getNextStackOffset();
01889       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
01890         while (State->AllocateReg(GPRArgRegs, 4))
01891           ;
01892         return;
01893       }
01894 
01895       // First register for byval parameter is the first register that wasn't
01896       // allocated before this method call, so it would be "reg".
01897       // If parameter is small enough to be saved in range [reg, r4), then
01898       // the end (first after last) register would be reg + param-size-in-regs,
01899       // else parameter would be splitted between registers and stack,
01900       // end register would be r4 in this case.
01901       unsigned ByValRegBegin = reg;
01902       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
01903       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
01904       // Note, first register is allocated in the beginning of function already,
01905       // allocate remained amount of registers we need.
01906       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
01907         State->AllocateReg(GPRArgRegs, 4);
01908       // A byval parameter that is split between registers and memory needs its
01909       // size truncated here.
01910       // In the case where the entire structure fits in registers, we set the
01911       // size in memory to zero.
01912       if (size < excess)
01913         size = 0;
01914       else
01915         size -= excess;
01916     }
01917   }
01918 }
01919 
01920 /// MatchingStackOffset - Return true if the given stack call argument is
01921 /// already available in the same position (relatively) of the caller's
01922 /// incoming argument stack.
01923 static
01924 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
01925                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
01926                          const TargetInstrInfo *TII) {
01927   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
01928   int FI = INT_MAX;
01929   if (Arg.getOpcode() == ISD::CopyFromReg) {
01930     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
01931     if (!TargetRegisterInfo::isVirtualRegister(VR))
01932       return false;
01933     MachineInstr *Def = MRI->getVRegDef(VR);
01934     if (!Def)
01935       return false;
01936     if (!Flags.isByVal()) {
01937       if (!TII->isLoadFromStackSlot(Def, FI))
01938         return false;
01939     } else {
01940       return false;
01941     }
01942   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
01943     if (Flags.isByVal())
01944       // ByVal argument is passed in as a pointer but it's now being
01945       // dereferenced. e.g.
01946       // define @foo(%struct.X* %A) {
01947       //   tail call @bar(%struct.X* byval %A)
01948       // }
01949       return false;
01950     SDValue Ptr = Ld->getBasePtr();
01951     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
01952     if (!FINode)
01953       return false;
01954     FI = FINode->getIndex();
01955   } else
01956     return false;
01957 
01958   assert(FI != INT_MAX);
01959   if (!MFI->isFixedObjectIndex(FI))
01960     return false;
01961   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
01962 }
01963 
01964 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
01965 /// for tail call optimization. Targets which want to do tail call
01966 /// optimization should implement this function.
01967 bool
01968 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
01969                                                      CallingConv::ID CalleeCC,
01970                                                      bool isVarArg,
01971                                                      bool isCalleeStructRet,
01972                                                      bool isCallerStructRet,
01973                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
01974                                     const SmallVectorImpl<SDValue> &OutVals,
01975                                     const SmallVectorImpl<ISD::InputArg> &Ins,
01976                                                      SelectionDAG& DAG) const {
01977   const Function *CallerF = DAG.getMachineFunction().getFunction();
01978   CallingConv::ID CallerCC = CallerF->getCallingConv();
01979   bool CCMatch = CallerCC == CalleeCC;
01980 
01981   // Look for obvious safe cases to perform tail call optimization that do not
01982   // require ABI changes. This is what gcc calls sibcall.
01983 
01984   // Do not sibcall optimize vararg calls unless the call site is not passing
01985   // any arguments.
01986   if (isVarArg && !Outs.empty())
01987     return false;
01988 
01989   // Exception-handling functions need a special set of instructions to indicate
01990   // a return to the hardware. Tail-calling another function would probably
01991   // break this.
01992   if (CallerF->hasFnAttribute("interrupt"))
01993     return false;
01994 
01995   // Also avoid sibcall optimization if either caller or callee uses struct
01996   // return semantics.
01997   if (isCalleeStructRet || isCallerStructRet)
01998     return false;
01999 
02000   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
02001   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
02002   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
02003   // support in the assembler and linker to be used. This would need to be
02004   // fixed to fully support tail calls in Thumb1.
02005   //
02006   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
02007   // LR.  This means if we need to reload LR, it takes an extra instructions,
02008   // which outweighs the value of the tail call; but here we don't know yet
02009   // whether LR is going to be used.  Probably the right approach is to
02010   // generate the tail call here and turn it back into CALL/RET in
02011   // emitEpilogue if LR is used.
02012 
02013   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
02014   // but we need to make sure there are enough registers; the only valid
02015   // registers are the 4 used for parameters.  We don't currently do this
02016   // case.
02017   if (Subtarget->isThumb1Only())
02018     return false;
02019 
02020   // Externally-defined functions with weak linkage should not be
02021   // tail-called on ARM when the OS does not support dynamic
02022   // pre-emption of symbols, as the AAELF spec requires normal calls
02023   // to undefined weak functions to be replaced with a NOP or jump to the
02024   // next instruction. The behaviour of branch instructions in this
02025   // situation (as used for tail calls) is implementation-defined, so we
02026   // cannot rely on the linker replacing the tail call with a return.
02027   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
02028     const GlobalValue *GV = G->getGlobal();
02029     const Triple TT(getTargetMachine().getTargetTriple());
02030     if (GV->hasExternalWeakLinkage() &&
02031         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
02032       return false;
02033   }
02034 
02035   // If the calling conventions do not match, then we'd better make sure the
02036   // results are returned in the same way as what the caller expects.
02037   if (!CCMatch) {
02038     SmallVector<CCValAssign, 16> RVLocs1;
02039     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
02040                        *DAG.getContext(), Call);
02041     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
02042 
02043     SmallVector<CCValAssign, 16> RVLocs2;
02044     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
02045                        *DAG.getContext(), Call);
02046     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
02047 
02048     if (RVLocs1.size() != RVLocs2.size())
02049       return false;
02050     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
02051       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
02052         return false;
02053       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
02054         return false;
02055       if (RVLocs1[i].isRegLoc()) {
02056         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
02057           return false;
02058       } else {
02059         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
02060           return false;
02061       }
02062     }
02063   }
02064 
02065   // If Caller's vararg or byval argument has been split between registers and
02066   // stack, do not perform tail call, since part of the argument is in caller's
02067   // local frame.
02068   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
02069                                       getInfo<ARMFunctionInfo>();
02070   if (AFI_Caller->getArgRegsSaveSize())
02071     return false;
02072 
02073   // If the callee takes no arguments then go on to check the results of the
02074   // call.
02075   if (!Outs.empty()) {
02076     // Check if stack adjustment is needed. For now, do not do this if any
02077     // argument is passed on the stack.
02078     SmallVector<CCValAssign, 16> ArgLocs;
02079     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
02080                       *DAG.getContext(), Call);
02081     CCInfo.AnalyzeCallOperands(Outs,
02082                                CCAssignFnForNode(CalleeCC, false, isVarArg));
02083     if (CCInfo.getNextStackOffset()) {
02084       MachineFunction &MF = DAG.getMachineFunction();
02085 
02086       // Check if the arguments are already laid out in the right way as
02087       // the caller's fixed stack objects.
02088       MachineFrameInfo *MFI = MF.getFrameInfo();
02089       const MachineRegisterInfo *MRI = &MF.getRegInfo();
02090       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
02091       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
02092            i != e;
02093            ++i, ++realArgIdx) {
02094         CCValAssign &VA = ArgLocs[i];
02095         EVT RegVT = VA.getLocVT();
02096         SDValue Arg = OutVals[realArgIdx];
02097         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
02098         if (VA.getLocInfo() == CCValAssign::Indirect)
02099           return false;
02100         if (VA.needsCustom()) {
02101           // f64 and vector types are split into multiple registers or
02102           // register/stack-slot combinations.  The types will not match
02103           // the registers; give up on memory f64 refs until we figure
02104           // out what to do about this.
02105           if (!VA.isRegLoc())
02106             return false;
02107           if (!ArgLocs[++i].isRegLoc())
02108             return false;
02109           if (RegVT == MVT::v2f64) {
02110             if (!ArgLocs[++i].isRegLoc())
02111               return false;
02112             if (!ArgLocs[++i].isRegLoc())
02113               return false;
02114           }
02115         } else if (!VA.isRegLoc()) {
02116           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
02117                                    MFI, MRI, TII))
02118             return false;
02119         }
02120       }
02121     }
02122   }
02123 
02124   return true;
02125 }
02126 
02127 bool
02128 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
02129                                   MachineFunction &MF, bool isVarArg,
02130                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
02131                                   LLVMContext &Context) const {
02132   SmallVector<CCValAssign, 16> RVLocs;
02133   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
02134   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
02135                                                     isVarArg));
02136 }
02137 
02138 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
02139                                     SDLoc DL, SelectionDAG &DAG) {
02140   const MachineFunction &MF = DAG.getMachineFunction();
02141   const Function *F = MF.getFunction();
02142 
02143   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
02144 
02145   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
02146   // version of the "preferred return address". These offsets affect the return
02147   // instruction if this is a return from PL1 without hypervisor extensions.
02148   //    IRQ/FIQ: +4     "subs pc, lr, #4"
02149   //    SWI:     0      "subs pc, lr, #0"
02150   //    ABORT:   +4     "subs pc, lr, #4"
02151   //    UNDEF:   +4/+2  "subs pc, lr, #0"
02152   // UNDEF varies depending on where the exception came from ARM or Thumb
02153   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
02154 
02155   int64_t LROffset;
02156   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
02157       IntKind == "ABORT")
02158     LROffset = 4;
02159   else if (IntKind == "SWI" || IntKind == "UNDEF")
02160     LROffset = 0;
02161   else
02162     report_fatal_error("Unsupported interrupt attribute. If present, value "
02163                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
02164 
02165   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
02166 
02167   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
02168 }
02169 
02170 SDValue
02171 ARMTargetLowering::LowerReturn(SDValue Chain,
02172                                CallingConv::ID CallConv, bool isVarArg,
02173                                const SmallVectorImpl<ISD::OutputArg> &Outs,
02174                                const SmallVectorImpl<SDValue> &OutVals,
02175                                SDLoc dl, SelectionDAG &DAG) const {
02176 
02177   // CCValAssign - represent the assignment of the return value to a location.
02178   SmallVector<CCValAssign, 16> RVLocs;
02179 
02180   // CCState - Info about the registers and stack slots.
02181   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
02182                     *DAG.getContext(), Call);
02183 
02184   // Analyze outgoing return values.
02185   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
02186                                                isVarArg));
02187 
02188   SDValue Flag;
02189   SmallVector<SDValue, 4> RetOps;
02190   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
02191   bool isLittleEndian = Subtarget->isLittle();
02192 
02193   MachineFunction &MF = DAG.getMachineFunction();
02194   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02195   AFI->setReturnRegsCount(RVLocs.size());
02196 
02197   // Copy the result values into the output registers.
02198   for (unsigned i = 0, realRVLocIdx = 0;
02199        i != RVLocs.size();
02200        ++i, ++realRVLocIdx) {
02201     CCValAssign &VA = RVLocs[i];
02202     assert(VA.isRegLoc() && "Can only return in registers!");
02203 
02204     SDValue Arg = OutVals[realRVLocIdx];
02205 
02206     switch (VA.getLocInfo()) {
02207     default: llvm_unreachable("Unknown loc info!");
02208     case CCValAssign::Full: break;
02209     case CCValAssign::BCvt:
02210       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
02211       break;
02212     }
02213 
02214     if (VA.needsCustom()) {
02215       if (VA.getLocVT() == MVT::v2f64) {
02216         // Extract the first half and return it in two registers.
02217         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
02218                                    DAG.getConstant(0, MVT::i32));
02219         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
02220                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
02221 
02222         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02223                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
02224                                  Flag);
02225         Flag = Chain.getValue(1);
02226         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02227         VA = RVLocs[++i]; // skip ahead to next loc
02228         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02229                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
02230                                  Flag);
02231         Flag = Chain.getValue(1);
02232         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02233         VA = RVLocs[++i]; // skip ahead to next loc
02234 
02235         // Extract the 2nd half and fall through to handle it as an f64 value.
02236         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
02237                           DAG.getConstant(1, MVT::i32));
02238       }
02239       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
02240       // available.
02241       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
02242                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
02243       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02244                                fmrrd.getValue(isLittleEndian ? 0 : 1),
02245                                Flag);
02246       Flag = Chain.getValue(1);
02247       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02248       VA = RVLocs[++i]; // skip ahead to next loc
02249       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
02250                                fmrrd.getValue(isLittleEndian ? 1 : 0),
02251                                Flag);
02252     } else
02253       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
02254 
02255     // Guarantee that all emitted copies are
02256     // stuck together, avoiding something bad.
02257     Flag = Chain.getValue(1);
02258     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
02259   }
02260 
02261   // Update chain and glue.
02262   RetOps[0] = Chain;
02263   if (Flag.getNode())
02264     RetOps.push_back(Flag);
02265 
02266   // CPUs which aren't M-class use a special sequence to return from
02267   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
02268   // though we use "subs pc, lr, #N").
02269   //
02270   // M-class CPUs actually use a normal return sequence with a special
02271   // (hardware-provided) value in LR, so the normal code path works.
02272   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
02273       !Subtarget->isMClass()) {
02274     if (Subtarget->isThumb1Only())
02275       report_fatal_error("interrupt attribute is not supported in Thumb1");
02276     return LowerInterruptReturn(RetOps, dl, DAG);
02277   }
02278 
02279   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
02280 }
02281 
02282 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
02283   if (N->getNumValues() != 1)
02284     return false;
02285   if (!N->hasNUsesOfValue(1, 0))
02286     return false;
02287 
02288   SDValue TCChain = Chain;
02289   SDNode *Copy = *N->use_begin();
02290   if (Copy->getOpcode() == ISD::CopyToReg) {
02291     // If the copy has a glue operand, we conservatively assume it isn't safe to
02292     // perform a tail call.
02293     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
02294       return false;
02295     TCChain = Copy->getOperand(0);
02296   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
02297     SDNode *VMov = Copy;
02298     // f64 returned in a pair of GPRs.
02299     SmallPtrSet<SDNode*, 2> Copies;
02300     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
02301          UI != UE; ++UI) {
02302       if (UI->getOpcode() != ISD::CopyToReg)
02303         return false;
02304       Copies.insert(*UI);
02305     }
02306     if (Copies.size() > 2)
02307       return false;
02308 
02309     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
02310          UI != UE; ++UI) {
02311       SDValue UseChain = UI->getOperand(0);
02312       if (Copies.count(UseChain.getNode()))
02313         // Second CopyToReg
02314         Copy = *UI;
02315       else {
02316         // We are at the top of this chain.
02317         // If the copy has a glue operand, we conservatively assume it
02318         // isn't safe to perform a tail call.
02319         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
02320           return false;
02321         // First CopyToReg
02322         TCChain = UseChain;
02323       }
02324     }
02325   } else if (Copy->getOpcode() == ISD::BITCAST) {
02326     // f32 returned in a single GPR.
02327     if (!Copy->hasOneUse())
02328       return false;
02329     Copy = *Copy->use_begin();
02330     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
02331       return false;
02332     // If the copy has a glue operand, we conservatively assume it isn't safe to
02333     // perform a tail call.
02334     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
02335       return false;
02336     TCChain = Copy->getOperand(0);
02337   } else {
02338     return false;
02339   }
02340 
02341   bool HasRet = false;
02342   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
02343        UI != UE; ++UI) {
02344     if (UI->getOpcode() != ARMISD::RET_FLAG &&
02345         UI->getOpcode() != ARMISD::INTRET_FLAG)
02346       return false;
02347     HasRet = true;
02348   }
02349 
02350   if (!HasRet)
02351     return false;
02352 
02353   Chain = TCChain;
02354   return true;
02355 }
02356 
02357 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
02358   if (!Subtarget->supportsTailCall())
02359     return false;
02360 
02361   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
02362     return false;
02363 
02364   return !Subtarget->isThumb1Only();
02365 }
02366 
02367 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
02368 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
02369 // one of the above mentioned nodes. It has to be wrapped because otherwise
02370 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
02371 // be used to form addressing mode. These wrapped nodes will be selected
02372 // into MOVi.
02373 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
02374   EVT PtrVT = Op.getValueType();
02375   // FIXME there is no actual debug info here
02376   SDLoc dl(Op);
02377   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
02378   SDValue Res;
02379   if (CP->isMachineConstantPoolEntry())
02380     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
02381                                     CP->getAlignment());
02382   else
02383     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
02384                                     CP->getAlignment());
02385   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
02386 }
02387 
02388 unsigned ARMTargetLowering::getJumpTableEncoding() const {
02389   return MachineJumpTableInfo::EK_Inline;
02390 }
02391 
02392 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
02393                                              SelectionDAG &DAG) const {
02394   MachineFunction &MF = DAG.getMachineFunction();
02395   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02396   unsigned ARMPCLabelIndex = 0;
02397   SDLoc DL(Op);
02398   EVT PtrVT = getPointerTy();
02399   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
02400   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02401   SDValue CPAddr;
02402   if (RelocM == Reloc::Static) {
02403     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
02404   } else {
02405     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
02406     ARMPCLabelIndex = AFI->createPICLabelUId();
02407     ARMConstantPoolValue *CPV =
02408       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
02409                                       ARMCP::CPBlockAddress, PCAdj);
02410     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02411   }
02412   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
02413   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
02414                                MachinePointerInfo::getConstantPool(),
02415                                false, false, false, 0);
02416   if (RelocM == Reloc::Static)
02417     return Result;
02418   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02419   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
02420 }
02421 
02422 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
02423 SDValue
02424 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
02425                                                  SelectionDAG &DAG) const {
02426   SDLoc dl(GA);
02427   EVT PtrVT = getPointerTy();
02428   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
02429   MachineFunction &MF = DAG.getMachineFunction();
02430   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02431   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02432   ARMConstantPoolValue *CPV =
02433     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
02434                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
02435   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02436   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
02437   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
02438                          MachinePointerInfo::getConstantPool(),
02439                          false, false, false, 0);
02440   SDValue Chain = Argument.getValue(1);
02441 
02442   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02443   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
02444 
02445   // call __tls_get_addr.
02446   ArgListTy Args;
02447   ArgListEntry Entry;
02448   Entry.Node = Argument;
02449   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
02450   Args.push_back(Entry);
02451 
02452   // FIXME: is there useful debug info available here?
02453   TargetLowering::CallLoweringInfo CLI(DAG);
02454   CLI.setDebugLoc(dl).setChain(Chain)
02455     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
02456                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
02457                0);
02458 
02459   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
02460   return CallResult.first;
02461 }
02462 
02463 // Lower ISD::GlobalTLSAddress using the "initial exec" or
02464 // "local exec" model.
02465 SDValue
02466 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
02467                                         SelectionDAG &DAG,
02468                                         TLSModel::Model model) const {
02469   const GlobalValue *GV = GA->getGlobal();
02470   SDLoc dl(GA);
02471   SDValue Offset;
02472   SDValue Chain = DAG.getEntryNode();
02473   EVT PtrVT = getPointerTy();
02474   // Get the Thread Pointer
02475   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
02476 
02477   if (model == TLSModel::InitialExec) {
02478     MachineFunction &MF = DAG.getMachineFunction();
02479     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02480     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02481     // Initial exec model.
02482     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
02483     ARMConstantPoolValue *CPV =
02484       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
02485                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
02486                                       true);
02487     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02488     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
02489     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02490                          MachinePointerInfo::getConstantPool(),
02491                          false, false, false, 0);
02492     Chain = Offset.getValue(1);
02493 
02494     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02495     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
02496 
02497     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02498                          MachinePointerInfo::getConstantPool(),
02499                          false, false, false, 0);
02500   } else {
02501     // local exec model
02502     assert(model == TLSModel::LocalExec);
02503     ARMConstantPoolValue *CPV =
02504       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
02505     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02506     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
02507     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
02508                          MachinePointerInfo::getConstantPool(),
02509                          false, false, false, 0);
02510   }
02511 
02512   // The address of the thread local variable is the add of the thread
02513   // pointer with the offset of the variable.
02514   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
02515 }
02516 
02517 SDValue
02518 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
02519   // TODO: implement the "local dynamic" model
02520   assert(Subtarget->isTargetELF() &&
02521          "TLS not implemented for non-ELF targets");
02522   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
02523 
02524   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
02525 
02526   switch (model) {
02527     case TLSModel::GeneralDynamic:
02528     case TLSModel::LocalDynamic:
02529       return LowerToTLSGeneralDynamicModel(GA, DAG);
02530     case TLSModel::InitialExec:
02531     case TLSModel::LocalExec:
02532       return LowerToTLSExecModels(GA, DAG, model);
02533   }
02534   llvm_unreachable("bogus TLS model");
02535 }
02536 
02537 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
02538                                                  SelectionDAG &DAG) const {
02539   EVT PtrVT = getPointerTy();
02540   SDLoc dl(Op);
02541   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02542   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
02543     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
02544     ARMConstantPoolValue *CPV =
02545       ARMConstantPoolConstant::Create(GV,
02546                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
02547     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02548     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02549     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
02550                                  CPAddr,
02551                                  MachinePointerInfo::getConstantPool(),
02552                                  false, false, false, 0);
02553     SDValue Chain = Result.getValue(1);
02554     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
02555     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
02556     if (!UseGOTOFF)
02557       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
02558                            MachinePointerInfo::getGOT(),
02559                            false, false, false, 0);
02560     return Result;
02561   }
02562 
02563   // If we have T2 ops, we can materialize the address directly via movt/movw
02564   // pair. This is always cheaper.
02565   if (Subtarget->useMovt(DAG.getMachineFunction())) {
02566     ++NumMovwMovt;
02567     // FIXME: Once remat is capable of dealing with instructions with register
02568     // operands, expand this into two nodes.
02569     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
02570                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
02571   } else {
02572     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
02573     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02574     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02575                        MachinePointerInfo::getConstantPool(),
02576                        false, false, false, 0);
02577   }
02578 }
02579 
02580 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
02581                                                     SelectionDAG &DAG) const {
02582   EVT PtrVT = getPointerTy();
02583   SDLoc dl(Op);
02584   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02585   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02586 
02587   if (Subtarget->useMovt(DAG.getMachineFunction()))
02588     ++NumMovwMovt;
02589 
02590   // FIXME: Once remat is capable of dealing with instructions with register
02591   // operands, expand this into multiple nodes
02592   unsigned Wrapper =
02593       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
02594 
02595   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
02596   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
02597 
02598   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
02599     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
02600                          MachinePointerInfo::getGOT(), false, false, false, 0);
02601   return Result;
02602 }
02603 
02604 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
02605                                                      SelectionDAG &DAG) const {
02606   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
02607   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
02608          "Windows on ARM expects to use movw/movt");
02609 
02610   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
02611   const ARMII::TOF TargetFlags =
02612     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
02613   EVT PtrVT = getPointerTy();
02614   SDValue Result;
02615   SDLoc DL(Op);
02616 
02617   ++NumMovwMovt;
02618 
02619   // FIXME: Once remat is capable of dealing with instructions with register
02620   // operands, expand this into two nodes.
02621   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
02622                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
02623                                                   TargetFlags));
02624   if (GV->hasDLLImportStorageClass())
02625     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
02626                          MachinePointerInfo::getGOT(), false, false, false, 0);
02627   return Result;
02628 }
02629 
02630 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
02631                                                     SelectionDAG &DAG) const {
02632   assert(Subtarget->isTargetELF() &&
02633          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
02634   MachineFunction &MF = DAG.getMachineFunction();
02635   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02636   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02637   EVT PtrVT = getPointerTy();
02638   SDLoc dl(Op);
02639   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
02640   ARMConstantPoolValue *CPV =
02641     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
02642                                   ARMPCLabelIndex, PCAdj);
02643   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02644   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02645   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02646                                MachinePointerInfo::getConstantPool(),
02647                                false, false, false, 0);
02648   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02649   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
02650 }
02651 
02652 SDValue
02653 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
02654   SDLoc dl(Op);
02655   SDValue Val = DAG.getConstant(0, MVT::i32);
02656   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
02657                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
02658                      Op.getOperand(1), Val);
02659 }
02660 
02661 SDValue
02662 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
02663   SDLoc dl(Op);
02664   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
02665                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
02666 }
02667 
02668 SDValue
02669 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
02670                                           const ARMSubtarget *Subtarget) const {
02671   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
02672   SDLoc dl(Op);
02673   switch (IntNo) {
02674   default: return SDValue();    // Don't custom lower most intrinsics.
02675   case Intrinsic::arm_rbit: {
02676     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
02677            "RBIT intrinsic must have i32 type!");
02678     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
02679   }
02680   case Intrinsic::arm_thread_pointer: {
02681     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02682     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
02683   }
02684   case Intrinsic::eh_sjlj_lsda: {
02685     MachineFunction &MF = DAG.getMachineFunction();
02686     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02687     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
02688     EVT PtrVT = getPointerTy();
02689     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
02690     SDValue CPAddr;
02691     unsigned PCAdj = (RelocM != Reloc::PIC_)
02692       ? 0 : (Subtarget->isThumb() ? 4 : 8);
02693     ARMConstantPoolValue *CPV =
02694       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
02695                                       ARMCP::CPLSDA, PCAdj);
02696     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
02697     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
02698     SDValue Result =
02699       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
02700                   MachinePointerInfo::getConstantPool(),
02701                   false, false, false, 0);
02702 
02703     if (RelocM == Reloc::PIC_) {
02704       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
02705       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
02706     }
02707     return Result;
02708   }
02709   case Intrinsic::arm_neon_vmulls:
02710   case Intrinsic::arm_neon_vmullu: {
02711     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
02712       ? ARMISD::VMULLs : ARMISD::VMULLu;
02713     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
02714                        Op.getOperand(1), Op.getOperand(2));
02715   }
02716   }
02717 }
02718 
02719 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
02720                                  const ARMSubtarget *Subtarget) {
02721   // FIXME: handle "fence singlethread" more efficiently.
02722   SDLoc dl(Op);
02723   if (!Subtarget->hasDataBarrier()) {
02724     // Some ARMv6 cpus can support data barriers with an mcr instruction.
02725     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
02726     // here.
02727     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
02728            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
02729     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
02730                        DAG.getConstant(0, MVT::i32));
02731   }
02732 
02733   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
02734   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
02735   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
02736   if (Subtarget->isMClass()) {
02737     // Only a full system barrier exists in the M-class architectures.
02738     Domain = ARM_MB::SY;
02739   } else if (Subtarget->isSwift() && Ord == Release) {
02740     // Swift happens to implement ISHST barriers in a way that's compatible with
02741     // Release semantics but weaker than ISH so we'd be fools not to use
02742     // it. Beware: other processors probably don't!
02743     Domain = ARM_MB::ISHST;
02744   }
02745 
02746   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
02747                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
02748                      DAG.getConstant(Domain, MVT::i32));
02749 }
02750 
02751 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
02752                              const ARMSubtarget *Subtarget) {
02753   // ARM pre v5TE and Thumb1 does not have preload instructions.
02754   if (!(Subtarget->isThumb2() ||
02755         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
02756     // Just preserve the chain.
02757     return Op.getOperand(0);
02758 
02759   SDLoc dl(Op);
02760   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
02761   if (!isRead &&
02762       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
02763     // ARMv7 with MP extension has PLDW.
02764     return Op.getOperand(0);
02765 
02766   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
02767   if (Subtarget->isThumb()) {
02768     // Invert the bits.
02769     isRead = ~isRead & 1;
02770     isData = ~isData & 1;
02771   }
02772 
02773   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
02774                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
02775                      DAG.getConstant(isData, MVT::i32));
02776 }
02777 
02778 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
02779   MachineFunction &MF = DAG.getMachineFunction();
02780   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
02781 
02782   // vastart just stores the address of the VarArgsFrameIndex slot into the
02783   // memory location argument.
02784   SDLoc dl(Op);
02785   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
02786   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
02787   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
02788   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
02789                       MachinePointerInfo(SV), false, false, 0);
02790 }
02791 
02792 SDValue
02793 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
02794                                         SDValue &Root, SelectionDAG &DAG,
02795                                         SDLoc dl) const {
02796   MachineFunction &MF = DAG.getMachineFunction();
02797   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02798 
02799   const TargetRegisterClass *RC;
02800   if (AFI->isThumb1OnlyFunction())
02801     RC = &ARM::tGPRRegClass;
02802   else
02803     RC = &ARM::GPRRegClass;
02804 
02805   // Transform the arguments stored in physical registers into virtual ones.
02806   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
02807   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
02808 
02809   SDValue ArgValue2;
02810   if (NextVA.isMemLoc()) {
02811     MachineFrameInfo *MFI = MF.getFrameInfo();
02812     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
02813 
02814     // Create load node to retrieve arguments from the stack.
02815     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
02816     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
02817                             MachinePointerInfo::getFixedStack(FI),
02818                             false, false, false, 0);
02819   } else {
02820     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
02821     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
02822   }
02823   if (!Subtarget->isLittle())
02824     std::swap (ArgValue, ArgValue2);
02825   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
02826 }
02827 
02828 void
02829 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
02830                                   unsigned InRegsParamRecordIdx,
02831                                   unsigned ArgSize,
02832                                   unsigned &ArgRegsSize,
02833                                   unsigned &ArgRegsSaveSize)
02834   const {
02835   unsigned NumGPRs;
02836   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
02837     unsigned RBegin, REnd;
02838     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
02839     NumGPRs = REnd - RBegin;
02840   } else {
02841     unsigned int firstUnalloced;
02842     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
02843                                                 sizeof(GPRArgRegs) /
02844                                                 sizeof(GPRArgRegs[0]));
02845     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
02846   }
02847 
02848   unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
02849   ArgRegsSize = NumGPRs * 4;
02850 
02851   // If parameter is split between stack and GPRs...
02852   if (NumGPRs && Align > 4 &&
02853       (ArgRegsSize < ArgSize ||
02854         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
02855     // Add padding for part of param recovered from GPRs.  For example,
02856     // if Align == 8, its last byte must be at address K*8 - 1.
02857     // We need to do it, since remained (stack) part of parameter has
02858     // stack alignment, and we need to "attach" "GPRs head" without gaps
02859     // to it:
02860     // Stack:
02861     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
02862     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
02863     //
02864     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02865     unsigned Padding =
02866         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
02867     ArgRegsSaveSize = ArgRegsSize + Padding;
02868   } else
02869     // We don't need to extend regs save size for byval parameters if they
02870     // are passed via GPRs only.
02871     ArgRegsSaveSize = ArgRegsSize;
02872 }
02873 
02874 // The remaining GPRs hold either the beginning of variable-argument
02875 // data, or the beginning of an aggregate passed by value (usually
02876 // byval).  Either way, we allocate stack slots adjacent to the data
02877 // provided by our caller, and store the unallocated registers there.
02878 // If this is a variadic function, the va_list pointer will begin with
02879 // these values; otherwise, this reassembles a (byval) structure that
02880 // was split between registers and memory.
02881 // Return: The frame index registers were stored into.
02882 int
02883 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
02884                                   SDLoc dl, SDValue &Chain,
02885                                   const Value *OrigArg,
02886                                   unsigned InRegsParamRecordIdx,
02887                                   unsigned OffsetFromOrigArg,
02888                                   unsigned ArgOffset,
02889                                   unsigned ArgSize,
02890                                   bool ForceMutable,
02891                                   unsigned ByValStoreOffset,
02892                                   unsigned TotalArgRegsSaveSize) const {
02893 
02894   // Currently, two use-cases possible:
02895   // Case #1. Non-var-args function, and we meet first byval parameter.
02896   //          Setup first unallocated register as first byval register;
02897   //          eat all remained registers
02898   //          (these two actions are performed by HandleByVal method).
02899   //          Then, here, we initialize stack frame with
02900   //          "store-reg" instructions.
02901   // Case #2. Var-args function, that doesn't contain byval parameters.
02902   //          The same: eat all remained unallocated registers,
02903   //          initialize stack frame.
02904 
02905   MachineFunction &MF = DAG.getMachineFunction();
02906   MachineFrameInfo *MFI = MF.getFrameInfo();
02907   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02908   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
02909   unsigned RBegin, REnd;
02910   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
02911     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
02912     firstRegToSaveIndex = RBegin - ARM::R0;
02913     lastRegToSaveIndex = REnd - ARM::R0;
02914   } else {
02915     firstRegToSaveIndex = CCInfo.getFirstUnallocated
02916       (GPRArgRegs, array_lengthof(GPRArgRegs));
02917     lastRegToSaveIndex = 4;
02918   }
02919 
02920   unsigned ArgRegsSize, ArgRegsSaveSize;
02921   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
02922                  ArgRegsSize, ArgRegsSaveSize);
02923 
02924   // Store any by-val regs to their spots on the stack so that they may be
02925   // loaded by deferencing the result of formal parameter pointer or va_next.
02926   // Note: once stack area for byval/varargs registers
02927   // was initialized, it can't be initialized again.
02928   if (ArgRegsSaveSize) {
02929     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
02930 
02931     if (Padding) {
02932       assert(AFI->getStoredByValParamsPadding() == 0 &&
02933              "The only parameter may be padded.");
02934       AFI->setStoredByValParamsPadding(Padding);
02935     }
02936 
02937     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
02938                                             Padding +
02939                                               ByValStoreOffset -
02940                                               (int64_t)TotalArgRegsSaveSize,
02941                                             false);
02942     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
02943     if (Padding) {
02944        MFI->CreateFixedObject(Padding,
02945                               ArgOffset + ByValStoreOffset -
02946                                 (int64_t)ArgRegsSaveSize,
02947                               false);
02948     }
02949 
02950     SmallVector<SDValue, 4> MemOps;
02951     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
02952          ++firstRegToSaveIndex, ++i) {
02953       const TargetRegisterClass *RC;
02954       if (AFI->isThumb1OnlyFunction())
02955         RC = &ARM::tGPRRegClass;
02956       else
02957         RC = &ARM::GPRRegClass;
02958 
02959       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
02960       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
02961       SDValue Store =
02962         DAG.getStore(Val.getValue(1), dl, Val, FIN,
02963                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
02964                      false, false, 0);
02965       MemOps.push_back(Store);
02966       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
02967                         DAG.getConstant(4, getPointerTy()));
02968     }
02969 
02970     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
02971 
02972     if (!MemOps.empty())
02973       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
02974     return FrameIndex;
02975   } else {
02976     if (ArgSize == 0) {
02977       // We cannot allocate a zero-byte object for the first variadic argument,
02978       // so just make up a size.
02979       ArgSize = 4;
02980     }
02981     // This will point to the next argument passed via stack.
02982     return MFI->CreateFixedObject(
02983       ArgSize, ArgOffset, !ForceMutable);
02984   }
02985 }
02986 
02987 // Setup stack frame, the va_list pointer will start from.
02988 void
02989 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
02990                                         SDLoc dl, SDValue &Chain,
02991                                         unsigned ArgOffset,
02992                                         unsigned TotalArgRegsSaveSize,
02993                                         bool ForceMutable) const {
02994   MachineFunction &MF = DAG.getMachineFunction();
02995   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
02996 
02997   // Try to store any remaining integer argument regs
02998   // to their spots on the stack so that they may be loaded by deferencing
02999   // the result of va_next.
03000   // If there is no regs to be stored, just point address after last
03001   // argument passed via stack.
03002   int FrameIndex =
03003     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
03004                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
03005                    0, TotalArgRegsSaveSize);
03006 
03007   AFI->setVarArgsFrameIndex(FrameIndex);
03008 }
03009 
03010 SDValue
03011 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
03012                                         CallingConv::ID CallConv, bool isVarArg,
03013                                         const SmallVectorImpl<ISD::InputArg>
03014                                           &Ins,
03015                                         SDLoc dl, SelectionDAG &DAG,
03016                                         SmallVectorImpl<SDValue> &InVals)
03017                                           const {
03018   MachineFunction &MF = DAG.getMachineFunction();
03019   MachineFrameInfo *MFI = MF.getFrameInfo();
03020 
03021   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
03022 
03023   // Assign locations to all of the incoming arguments.
03024   SmallVector<CCValAssign, 16> ArgLocs;
03025   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
03026                     *DAG.getContext(), Prologue);
03027   CCInfo.AnalyzeFormalArguments(Ins,
03028                                 CCAssignFnForNode(CallConv, /* Return*/ false,
03029                                                   isVarArg));
03030 
03031   SmallVector<SDValue, 16> ArgValues;
03032   int lastInsIndex = -1;
03033   SDValue ArgValue;
03034   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
03035   unsigned CurArgIdx = 0;
03036 
03037   // Initially ArgRegsSaveSize is zero.
03038   // Then we increase this value each time we meet byval parameter.
03039   // We also increase this value in case of varargs function.
03040   AFI->setArgRegsSaveSize(0);
03041 
03042   unsigned ByValStoreOffset = 0;
03043   unsigned TotalArgRegsSaveSize = 0;
03044   unsigned ArgRegsSaveSizeMaxAlign = 4;
03045 
03046   // Calculate the amount of stack space that we need to allocate to store
03047   // byval and variadic arguments that are passed in registers.
03048   // We need to know this before we allocate the first byval or variadic
03049   // argument, as they will be allocated a stack slot below the CFA (Canonical
03050   // Frame Address, the stack pointer at entry to the function).
03051   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
03052     CCValAssign &VA = ArgLocs[i];
03053     if (VA.isMemLoc()) {
03054       int index = VA.getValNo();
03055       if (index != lastInsIndex) {
03056         ISD::ArgFlagsTy Flags = Ins[index].Flags;
03057         if (Flags.isByVal()) {
03058           unsigned ExtraArgRegsSize;
03059           unsigned ExtraArgRegsSaveSize;
03060           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
03061                          Flags.getByValSize(),
03062                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
03063 
03064           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
03065           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
03066               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
03067           CCInfo.nextInRegsParam();
03068         }
03069         lastInsIndex = index;
03070       }
03071     }
03072   }
03073   CCInfo.rewindByValRegsInfo();
03074   lastInsIndex = -1;
03075   if (isVarArg && MFI->hasVAStart()) {
03076     unsigned ExtraArgRegsSize;
03077     unsigned ExtraArgRegsSaveSize;
03078     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
03079                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
03080     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
03081   }
03082   // If the arg regs save area contains N-byte aligned values, the
03083   // bottom of it must be at least N-byte aligned.
03084   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
03085   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
03086 
03087   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
03088     CCValAssign &VA = ArgLocs[i];
03089     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
03090     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
03091     // Arguments stored in registers.
03092     if (VA.isRegLoc()) {
03093       EVT RegVT = VA.getLocVT();
03094 
03095       if (VA.needsCustom()) {
03096         // f64 and vector types are split up into multiple registers or
03097         // combinations of registers and stack slots.
03098         if (VA.getLocVT() == MVT::v2f64) {
03099           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
03100                                                    Chain, DAG, dl);
03101           VA = ArgLocs[++i]; // skip ahead to next loc
03102           SDValue ArgValue2;
03103           if (VA.isMemLoc()) {
03104             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
03105             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
03106             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
03107                                     MachinePointerInfo::getFixedStack(FI),
03108                                     false, false, false, 0);
03109           } else {
03110             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
03111                                              Chain, DAG, dl);
03112           }
03113           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
03114           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
03115                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
03116           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
03117                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
03118         } else
03119           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
03120 
03121       } else {
03122         const TargetRegisterClass *RC;
03123 
03124         if (RegVT == MVT::f32)
03125           RC = &ARM::SPRRegClass;
03126         else if (RegVT == MVT::f64)
03127           RC = &ARM::DPRRegClass;
03128         else if (RegVT == MVT::v2f64)
03129           RC = &ARM::QPRRegClass;
03130         else if (RegVT == MVT::i32)
03131           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
03132                                            : &ARM::GPRRegClass;
03133         else
03134           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
03135 
03136         // Transform the arguments in physical registers into virtual ones.
03137         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
03138         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
03139       }
03140 
03141       // If this is an 8 or 16-bit value, it is really passed promoted
03142       // to 32 bits.  Insert an assert[sz]ext to capture this, then
03143       // truncate to the right size.
03144       switch (VA.getLocInfo()) {
03145       default: llvm_unreachable("Unknown loc info!");
03146       case CCValAssign::Full: break;
03147       case CCValAssign::BCvt:
03148         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
03149         break;
03150       case CCValAssign::SExt:
03151         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
03152                                DAG.getValueType(VA.getValVT()));
03153         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
03154         break;
03155       case CCValAssign::ZExt:
03156         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
03157                                DAG.getValueType(VA.getValVT()));
03158         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
03159         break;
03160       }
03161 
03162       InVals.push_back(ArgValue);
03163 
03164     } else { // VA.isRegLoc()
03165 
03166       // sanity check
03167       assert(VA.isMemLoc());
03168       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
03169 
03170       int index = ArgLocs[i].getValNo();
03171 
03172       // Some Ins[] entries become multiple ArgLoc[] entries.
03173       // Process them only once.
03174       if (index != lastInsIndex)
03175         {
03176           ISD::ArgFlagsTy Flags = Ins[index].Flags;
03177           // FIXME: For now, all byval parameter objects are marked mutable.
03178           // This can be changed with more analysis.
03179           // In case of tail call optimization mark all arguments mutable.
03180           // Since they could be overwritten by lowering of arguments in case of
03181           // a tail call.
03182           if (Flags.isByVal()) {
03183             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
03184 
03185             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
03186             int FrameIndex = StoreByValRegs(
03187                 CCInfo, DAG, dl, Chain, CurOrigArg,
03188                 CurByValIndex,
03189                 Ins[VA.getValNo()].PartOffset,
03190                 VA.getLocMemOffset(),
03191                 Flags.getByValSize(),
03192                 true /*force mutable frames*/,
03193                 ByValStoreOffset,
03194                 TotalArgRegsSaveSize);
03195             ByValStoreOffset += Flags.getByValSize();
03196             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
03197             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
03198             CCInfo.nextInRegsParam();
03199           } else {
03200             unsigned FIOffset = VA.getLocMemOffset();
03201             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
03202                                             FIOffset, true);
03203 
03204             // Create load nodes to retrieve arguments from the stack.
03205             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
03206             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
03207                                          MachinePointerInfo::getFixedStack(FI),
03208                                          false, false, false, 0));
03209           }
03210           lastInsIndex = index;
03211         }
03212     }
03213   }
03214 
03215   // varargs
03216   if (isVarArg && MFI->hasVAStart())
03217     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
03218                          CCInfo.getNextStackOffset(),
03219                          TotalArgRegsSaveSize);
03220 
03221   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
03222 
03223   return Chain;
03224 }
03225 
03226 /// isFloatingPointZero - Return true if this is +0.0.
03227 static bool isFloatingPointZero(SDValue Op) {
03228   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
03229     return CFP->getValueAPF().isPosZero();
03230   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
03231     // Maybe this has already been legalized into the constant pool?
03232     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
03233       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
03234       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
03235         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
03236           return CFP->getValueAPF().isPosZero();
03237     }
03238   } else if (Op->getOpcode() == ISD::BITCAST &&
03239              Op->getValueType(0) == MVT::f64) {
03240     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
03241     // created by LowerConstantFP().
03242     SDValue BitcastOp = Op->getOperand(0);
03243     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
03244       SDValue MoveOp = BitcastOp->getOperand(0);
03245       if (MoveOp->getOpcode() == ISD::TargetConstant &&
03246           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
03247         return true;
03248       }
03249     }
03250   }
03251   return false;
03252 }
03253 
03254 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
03255 /// the given operands.
03256 SDValue
03257 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
03258                              SDValue &ARMcc, SelectionDAG &DAG,
03259                              SDLoc dl) const {
03260   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
03261     unsigned C = RHSC->getZExtValue();
03262     if (!isLegalICmpImmediate(C)) {
03263       // Constant does not fit, try adjusting it by one?
03264       switch (CC) {
03265       default: break;
03266       case ISD::SETLT:
03267       case ISD::SETGE:
03268         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
03269           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
03270           RHS = DAG.getConstant(C-1, MVT::i32);
03271         }
03272         break;
03273       case ISD::SETULT:
03274       case ISD::SETUGE:
03275         if (C != 0 && isLegalICmpImmediate(C-1)) {
03276           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
03277           RHS = DAG.getConstant(C-1, MVT::i32);
03278         }
03279         break;
03280       case ISD::SETLE:
03281       case ISD::SETGT:
03282         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
03283           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
03284           RHS = DAG.getConstant(C+1, MVT::i32);
03285         }
03286         break;
03287       case ISD::SETULE:
03288       case ISD::SETUGT:
03289         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
03290           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
03291           RHS = DAG.getConstant(C+1, MVT::i32);
03292         }
03293         break;
03294       }
03295     }
03296   }
03297 
03298   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03299   ARMISD::NodeType CompareType;
03300   switch (CondCode) {
03301   default:
03302     CompareType = ARMISD::CMP;
03303     break;
03304   case ARMCC::EQ:
03305   case ARMCC::NE:
03306     // Uses only Z Flag
03307     CompareType = ARMISD::CMPZ;
03308     break;
03309   }
03310   ARMcc = DAG.getConstant(CondCode, MVT::i32);
03311   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
03312 }
03313 
03314 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
03315 SDValue
03316 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
03317                              SDLoc dl) const {
03318   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
03319   SDValue Cmp;
03320   if (!isFloatingPointZero(RHS))
03321     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
03322   else
03323     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
03324   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
03325 }
03326 
03327 /// duplicateCmp - Glue values can have only one use, so this function
03328 /// duplicates a comparison node.
03329 SDValue
03330 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
03331   unsigned Opc = Cmp.getOpcode();
03332   SDLoc DL(Cmp);
03333   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
03334     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
03335 
03336   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
03337   Cmp = Cmp.getOperand(0);
03338   Opc = Cmp.getOpcode();
03339   if (Opc == ARMISD::CMPFP)
03340     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
03341   else {
03342     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
03343     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
03344   }
03345   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
03346 }
03347 
03348 std::pair<SDValue, SDValue>
03349 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
03350                                  SDValue &ARMcc) const {
03351   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
03352 
03353   SDValue Value, OverflowCmp;
03354   SDValue LHS = Op.getOperand(0);
03355   SDValue RHS = Op.getOperand(1);
03356 
03357 
03358   // FIXME: We are currently always generating CMPs because we don't support
03359   // generating CMN through the backend. This is not as good as the natural
03360   // CMP case because it causes a register dependency and cannot be folded
03361   // later.
03362 
03363   switch (Op.getOpcode()) {
03364   default:
03365     llvm_unreachable("Unknown overflow instruction!");
03366   case ISD::SADDO:
03367     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
03368     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
03369     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
03370     break;
03371   case ISD::UADDO:
03372     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
03373     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
03374     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
03375     break;
03376   case ISD::SSUBO:
03377     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
03378     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
03379     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
03380     break;
03381   case ISD::USUBO:
03382     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
03383     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
03384     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
03385     break;
03386   } // switch (...)
03387 
03388   return std::make_pair(Value, OverflowCmp);
03389 }
03390 
03391 
03392 SDValue
03393 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
03394   // Let legalize expand this if it isn't a legal type yet.
03395   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
03396     return SDValue();
03397 
03398   SDValue Value, OverflowCmp;
03399   SDValue ARMcc;
03400   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
03401   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03402   // We use 0 and 1 as false and true values.
03403   SDValue TVal = DAG.getConstant(1, MVT::i32);
03404   SDValue FVal = DAG.getConstant(0, MVT::i32);
03405   EVT VT = Op.getValueType();
03406 
03407   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
03408                                  ARMcc, CCR, OverflowCmp);
03409 
03410   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
03411   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
03412 }
03413 
03414 
03415 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
03416   SDValue Cond = Op.getOperand(0);
03417   SDValue SelectTrue = Op.getOperand(1);
03418   SDValue SelectFalse = Op.getOperand(2);
03419   SDLoc dl(Op);
03420   unsigned Opc = Cond.getOpcode();
03421 
03422   if (Cond.getResNo() == 1 &&
03423       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
03424        Opc == ISD::USUBO)) {
03425     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
03426       return SDValue();
03427 
03428     SDValue Value, OverflowCmp;
03429     SDValue ARMcc;
03430     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
03431     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03432     EVT VT = Op.getValueType();
03433 
03434     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
03435                    OverflowCmp, DAG);
03436   }
03437 
03438   // Convert:
03439   //
03440   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
03441   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
03442   //
03443   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
03444     const ConstantSDNode *CMOVTrue =
03445       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
03446     const ConstantSDNode *CMOVFalse =
03447       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
03448 
03449     if (CMOVTrue && CMOVFalse) {
03450       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
03451       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
03452 
03453       SDValue True;
03454       SDValue False;
03455       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
03456         True = SelectTrue;
03457         False = SelectFalse;
03458       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
03459         True = SelectFalse;
03460         False = SelectTrue;
03461       }
03462 
03463       if (True.getNode() && False.getNode()) {
03464         EVT VT = Op.getValueType();
03465         SDValue ARMcc = Cond.getOperand(2);
03466         SDValue CCR = Cond.getOperand(3);
03467         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
03468         assert(True.getValueType() == VT);
03469         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
03470       }
03471     }
03472   }
03473 
03474   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
03475   // undefined bits before doing a full-word comparison with zero.
03476   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
03477                      DAG.getConstant(1, Cond.getValueType()));
03478 
03479   return DAG.getSelectCC(dl, Cond,
03480                          DAG.getConstant(0, Cond.getValueType()),
03481                          SelectTrue, SelectFalse, ISD::SETNE);
03482 }
03483 
03484 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
03485   if (CC == ISD::SETNE)
03486     return ISD::SETEQ;
03487   return ISD::getSetCCInverse(CC, true);
03488 }
03489 
03490 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
03491                                  bool &swpCmpOps, bool &swpVselOps) {
03492   // Start by selecting the GE condition code for opcodes that return true for
03493   // 'equality'
03494   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
03495       CC == ISD::SETULE)
03496     CondCode = ARMCC::GE;
03497 
03498   // and GT for opcodes that return false for 'equality'.
03499   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
03500            CC == ISD::SETULT)
03501     CondCode = ARMCC::GT;
03502 
03503   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
03504   // to swap the compare operands.
03505   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
03506       CC == ISD::SETULT)
03507     swpCmpOps = true;
03508 
03509   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
03510   // If we have an unordered opcode, we need to swap the operands to the VSEL
03511   // instruction (effectively negating the condition).
03512   //
03513   // This also has the effect of swapping which one of 'less' or 'greater'
03514   // returns true, so we also swap the compare operands. It also switches
03515   // whether we return true for 'equality', so we compensate by picking the
03516   // opposite condition code to our original choice.
03517   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
03518       CC == ISD::SETUGT) {
03519     swpCmpOps = !swpCmpOps;
03520     swpVselOps = !swpVselOps;
03521     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
03522   }
03523 
03524   // 'ordered' is 'anything but unordered', so use the VS condition code and
03525   // swap the VSEL operands.
03526   if (CC == ISD::SETO) {
03527     CondCode = ARMCC::VS;
03528     swpVselOps = true;
03529   }
03530 
03531   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
03532   // code and swap the VSEL operands.
03533   if (CC == ISD::SETUNE) {
03534     CondCode = ARMCC::EQ;
03535     swpVselOps = true;
03536   }
03537 }
03538 
03539 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
03540                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
03541                                    SDValue Cmp, SelectionDAG &DAG) const {
03542   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
03543     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
03544                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
03545     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
03546                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
03547 
03548     SDValue TrueLow = TrueVal.getValue(0);
03549     SDValue TrueHigh = TrueVal.getValue(1);
03550     SDValue FalseLow = FalseVal.getValue(0);
03551     SDValue FalseHigh = FalseVal.getValue(1);
03552 
03553     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
03554                               ARMcc, CCR, Cmp);
03555     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
03556                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
03557 
03558     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
03559   } else {
03560     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
03561                        Cmp);
03562   }
03563 }
03564 
03565 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
03566   EVT VT = Op.getValueType();
03567   SDValue LHS = Op.getOperand(0);
03568   SDValue RHS = Op.getOperand(1);
03569   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
03570   SDValue TrueVal = Op.getOperand(2);
03571   SDValue FalseVal = Op.getOperand(3);
03572   SDLoc dl(Op);
03573 
03574   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
03575     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
03576                                                     dl);
03577 
03578     // If softenSetCCOperands only returned one value, we should compare it to
03579     // zero.
03580     if (!RHS.getNode()) {
03581       RHS = DAG.getConstant(0, LHS.getValueType());
03582       CC = ISD::SETNE;
03583     }
03584   }
03585 
03586   if (LHS.getValueType() == MVT::i32) {
03587     // Try to generate VSEL on ARMv8.
03588     // The VSEL instruction can't use all the usual ARM condition
03589     // codes: it only has two bits to select the condition code, so it's
03590     // constrained to use only GE, GT, VS and EQ.
03591     //
03592     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
03593     // swap the operands of the previous compare instruction (effectively
03594     // inverting the compare condition, swapping 'less' and 'greater') and
03595     // sometimes need to swap the operands to the VSEL (which inverts the
03596     // condition in the sense of firing whenever the previous condition didn't)
03597     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
03598                                     TrueVal.getValueType() == MVT::f64)) {
03599       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03600       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
03601           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
03602         CC = getInverseCCForVSEL(CC);
03603         std::swap(TrueVal, FalseVal);
03604       }
03605     }
03606 
03607     SDValue ARMcc;
03608     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03609     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03610     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
03611   }
03612 
03613   ARMCC::CondCodes CondCode, CondCode2;
03614   FPCCToARMCC(CC, CondCode, CondCode2);
03615 
03616   // Try to generate VSEL on ARMv8.
03617   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
03618                                   TrueVal.getValueType() == MVT::f64)) {
03619     // We can select VMAXNM/VMINNM from a compare followed by a select with the
03620     // same operands, as follows:
03621     //   c = fcmp [ogt, olt, ugt, ult] a, b
03622     //   select c, a, b
03623     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
03624     // handled differently than the original code sequence.
03625     if (getTargetMachine().Options.UnsafeFPMath) {
03626       if (LHS == TrueVal && RHS == FalseVal) {
03627         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
03628           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
03629         if (CC == ISD::SETOLT || CC == ISD::SETULT)
03630           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
03631       } else if (LHS == FalseVal && RHS == TrueVal) {
03632         if (CC == ISD::SETOLT || CC == ISD::SETULT)
03633           return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
03634         if (CC == ISD::SETOGT || CC == ISD::SETUGT)
03635           return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
03636       }
03637     }
03638 
03639     bool swpCmpOps = false;
03640     bool swpVselOps = false;
03641     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
03642 
03643     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
03644         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
03645       if (swpCmpOps)
03646         std::swap(LHS, RHS);
03647       if (swpVselOps)
03648         std::swap(TrueVal, FalseVal);
03649     }
03650   }
03651 
03652   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
03653   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
03654   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03655   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
03656   if (CondCode2 != ARMCC::AL) {
03657     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
03658     // FIXME: Needs another CMP because flag can have but one use.
03659     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
03660     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
03661   }
03662   return Result;
03663 }
03664 
03665 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
03666 /// to morph to an integer compare sequence.
03667 static bool canChangeToInt(SDValue Op, bool &SeenZero,
03668                            const ARMSubtarget *Subtarget) {
03669   SDNode *N = Op.getNode();
03670   if (!N->hasOneUse())
03671     // Otherwise it requires moving the value from fp to integer registers.
03672     return false;
03673   if (!N->getNumValues())
03674     return false;
03675   EVT VT = Op.getValueType();
03676   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
03677     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
03678     // vmrs are very slow, e.g. cortex-a8.
03679     return false;
03680 
03681   if (isFloatingPointZero(Op)) {
03682     SeenZero = true;
03683     return true;
03684   }
03685   return ISD::isNormalLoad(N);
03686 }
03687 
03688 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
03689   if (isFloatingPointZero(Op))
03690     return DAG.getConstant(0, MVT::i32);
03691 
03692   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
03693     return DAG.getLoad(MVT::i32, SDLoc(Op),
03694                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
03695                        Ld->isVolatile(), Ld->isNonTemporal(),
03696                        Ld->isInvariant(), Ld->getAlignment());
03697 
03698   llvm_unreachable("Unknown VFP cmp argument!");
03699 }
03700 
03701 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
03702                            SDValue &RetVal1, SDValue &RetVal2) {
03703   if (isFloatingPointZero(Op)) {
03704     RetVal1 = DAG.getConstant(0, MVT::i32);
03705     RetVal2 = DAG.getConstant(0, MVT::i32);
03706     return;
03707   }
03708 
03709   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
03710     SDValue Ptr = Ld->getBasePtr();
03711     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
03712                           Ld->getChain(), Ptr,
03713                           Ld->getPointerInfo(),
03714                           Ld->isVolatile(), Ld->isNonTemporal(),
03715                           Ld->isInvariant(), Ld->getAlignment());
03716 
03717     EVT PtrType = Ptr.getValueType();
03718     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
03719     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
03720                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
03721     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
03722                           Ld->getChain(), NewPtr,
03723                           Ld->getPointerInfo().getWithOffset(4),
03724                           Ld->isVolatile(), Ld->isNonTemporal(),
03725                           Ld->isInvariant(), NewAlign);
03726     return;
03727   }
03728 
03729   llvm_unreachable("Unknown VFP cmp argument!");
03730 }
03731 
03732 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
03733 /// f32 and even f64 comparisons to integer ones.
03734 SDValue
03735 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
03736   SDValue Chain = Op.getOperand(0);
03737   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
03738   SDValue LHS = Op.getOperand(2);
03739   SDValue RHS = Op.getOperand(3);
03740   SDValue Dest = Op.getOperand(4);
03741   SDLoc dl(Op);
03742 
03743   bool LHSSeenZero = false;
03744   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
03745   bool RHSSeenZero = false;
03746   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
03747   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
03748     // If unsafe fp math optimization is enabled and there are no other uses of
03749     // the CMP operands, and the condition code is EQ or NE, we can optimize it
03750     // to an integer comparison.
03751     if (CC == ISD::SETOEQ)
03752       CC = ISD::SETEQ;
03753     else if (CC == ISD::SETUNE)
03754       CC = ISD::SETNE;
03755 
03756     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
03757     SDValue ARMcc;
03758     if (LHS.getValueType() == MVT::f32) {
03759       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
03760                         bitcastf32Toi32(LHS, DAG), Mask);
03761       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
03762                         bitcastf32Toi32(RHS, DAG), Mask);
03763       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03764       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03765       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
03766                          Chain, Dest, ARMcc, CCR, Cmp);
03767     }
03768 
03769     SDValue LHS1, LHS2;
03770     SDValue RHS1, RHS2;
03771     expandf64Toi32(LHS, DAG, LHS1, LHS2);
03772     expandf64Toi32(RHS, DAG, RHS1, RHS2);
03773     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
03774     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
03775     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
03776     ARMcc = DAG.getConstant(CondCode, MVT::i32);
03777     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
03778     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
03779     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
03780   }
03781 
03782   return SDValue();
03783 }
03784 
03785 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
03786   SDValue Chain = Op.getOperand(0);
03787   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
03788   SDValue LHS = Op.getOperand(2);
03789   SDValue RHS = Op.getOperand(3);
03790   SDValue Dest = Op.getOperand(4);
03791   SDLoc dl(Op);
03792 
03793   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
03794     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
03795                                                     dl);
03796 
03797     // If softenSetCCOperands only returned one value, we should compare it to
03798     // zero.
03799     if (!RHS.getNode()) {
03800       RHS = DAG.getConstant(0, LHS.getValueType());
03801       CC = ISD::SETNE;
03802     }
03803   }
03804 
03805   if (LHS.getValueType() == MVT::i32) {
03806     SDValue ARMcc;
03807     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
03808     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03809     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
03810                        Chain, Dest, ARMcc, CCR, Cmp);
03811   }
03812 
03813   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
03814 
03815   if (getTargetMachine().Options.UnsafeFPMath &&
03816       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
03817        CC == ISD::SETNE || CC == ISD::SETUNE)) {
03818     SDValue Result = OptimizeVFPBrcond(Op, DAG);
03819     if (Result.getNode())
03820       return Result;
03821   }
03822 
03823   ARMCC::CondCodes CondCode, CondCode2;
03824   FPCCToARMCC(CC, CondCode, CondCode2);
03825 
03826   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
03827   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
03828   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
03829   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
03830   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
03831   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
03832   if (CondCode2 != ARMCC::AL) {
03833     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
03834     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
03835     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
03836   }
03837   return Res;
03838 }
03839 
03840 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
03841   SDValue Chain = Op.getOperand(0);
03842   SDValue Table = Op.getOperand(1);
03843   SDValue Index = Op.getOperand(2);
03844   SDLoc dl(Op);
03845 
03846   EVT PTy = getPointerTy();
03847   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
03848   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
03849   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
03850   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
03851   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
03852   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
03853   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
03854   if (Subtarget->isThumb2()) {
03855     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
03856     // which does another jump to the destination. This also makes it easier
03857     // to translate it to TBB / TBH later.
03858     // FIXME: This might not work if the function is extremely large.
03859     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
03860                        Addr, Op.getOperand(2), JTI, UId);
03861   }
03862   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
03863     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
03864                        MachinePointerInfo::getJumpTable(),
03865                        false, false, false, 0);
03866     Chain = Addr.getValue(1);
03867     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
03868     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
03869   } else {
03870     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
03871                        MachinePointerInfo::getJumpTable(),
03872                        false, false, false, 0);
03873     Chain = Addr.getValue(1);
03874     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
03875   }
03876 }
03877 
03878 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
03879   EVT VT = Op.getValueType();
03880   SDLoc dl(Op);
03881 
03882   if (Op.getValueType().getVectorElementType() == MVT::i32) {
03883     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
03884       return Op;
03885     return DAG.UnrollVectorOp(Op.getNode());
03886   }
03887 
03888   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
03889          "Invalid type for custom lowering!");
03890   if (VT != MVT::v4i16)
03891     return DAG.UnrollVectorOp(Op.getNode());
03892 
03893   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
03894   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
03895 }
03896 
03897 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
03898   EVT VT = Op.getValueType();
03899   if (VT.isVector())
03900     return LowerVectorFP_TO_INT(Op, DAG);
03901 
03902   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
03903     RTLIB::Libcall LC;
03904     if (Op.getOpcode() == ISD::FP_TO_SINT)
03905       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
03906                               Op.getValueType());
03907     else
03908       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
03909                               Op.getValueType());
03910     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
03911                        /*isSigned*/ false, SDLoc(Op)).first;
03912   }
03913 
03914   SDLoc dl(Op);
03915   unsigned Opc;
03916 
03917   switch (Op.getOpcode()) {
03918   default: llvm_unreachable("Invalid opcode!");
03919   case ISD::FP_TO_SINT:
03920     Opc = ARMISD::FTOSI;
03921     break;
03922   case ISD::FP_TO_UINT:
03923     Opc = ARMISD::FTOUI;
03924     break;
03925   }
03926   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
03927   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
03928 }
03929 
03930 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
03931   EVT VT = Op.getValueType();
03932   SDLoc dl(Op);
03933 
03934   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
03935     if (VT.getVectorElementType() == MVT::f32)
03936       return Op;
03937     return DAG.UnrollVectorOp(Op.getNode());
03938   }
03939 
03940   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
03941          "Invalid type for custom lowering!");
03942   if (VT != MVT::v4f32)
03943     return DAG.UnrollVectorOp(Op.getNode());
03944 
03945   unsigned CastOpc;
03946   unsigned Opc;
03947   switch (Op.getOpcode()) {
03948   default: llvm_unreachable("Invalid opcode!");
03949   case ISD::SINT_TO_FP:
03950     CastOpc = ISD::SIGN_EXTEND;
03951     Opc = ISD::SINT_TO_FP;
03952     break;
03953   case ISD::UINT_TO_FP:
03954     CastOpc = ISD::ZERO_EXTEND;
03955     Opc = ISD::UINT_TO_FP;
03956     break;
03957   }
03958 
03959   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
03960   return DAG.getNode(Opc, dl, VT, Op);
03961 }
03962 
03963 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
03964   EVT VT = Op.getValueType();
03965   if (VT.isVector())
03966     return LowerVectorINT_TO_FP(Op, DAG);
03967 
03968   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
03969     RTLIB::Libcall LC;
03970     if (Op.getOpcode() == ISD::SINT_TO_FP)
03971       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
03972                               Op.getValueType());
03973     else
03974       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
03975                               Op.getValueType());
03976     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
03977                        /*isSigned*/ false, SDLoc(Op)).first;
03978   }
03979 
03980   SDLoc dl(Op);
03981   unsigned Opc;
03982 
03983   switch (Op.getOpcode()) {
03984   default: llvm_unreachable("Invalid opcode!");
03985   case ISD::SINT_TO_FP:
03986     Opc = ARMISD::SITOF;
03987     break;
03988   case ISD::UINT_TO_FP:
03989     Opc = ARMISD::UITOF;
03990     break;
03991   }
03992 
03993   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
03994   return DAG.getNode(Opc, dl, VT, Op);
03995 }
03996 
03997 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
03998   // Implement fcopysign with a fabs and a conditional fneg.
03999   SDValue Tmp0 = Op.getOperand(0);
04000   SDValue Tmp1 = Op.getOperand(1);
04001   SDLoc dl(Op);
04002   EVT VT = Op.getValueType();
04003   EVT SrcVT = Tmp1.getValueType();
04004   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
04005     Tmp0.getOpcode() == ARMISD::VMOVDRR;
04006   bool UseNEON = !InGPR && Subtarget->hasNEON();
04007 
04008   if (UseNEON) {
04009     // Use VBSL to copy the sign bit.
04010     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
04011     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
04012                                DAG.getTargetConstant(EncodedVal, MVT::i32));
04013     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
04014     if (VT == MVT::f64)
04015       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
04016                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
04017                          DAG.getConstant(32, MVT::i32));
04018     else /*if (VT == MVT::f32)*/
04019       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
04020     if (SrcVT == MVT::f32) {
04021       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
04022       if (VT == MVT::f64)
04023         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
04024                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
04025                            DAG.getConstant(32, MVT::i32));
04026     } else if (VT == MVT::f32)
04027       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
04028                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
04029                          DAG.getConstant(32, MVT::i32));
04030     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
04031     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
04032 
04033     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
04034                                             MVT::i32);
04035     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
04036     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
04037                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
04038 
04039     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
04040                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
04041                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
04042     if (VT == MVT::f32) {
04043       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
04044       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
04045                         DAG.getConstant(0, MVT::i32));
04046     } else {
04047       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
04048     }
04049 
04050     return Res;
04051   }
04052 
04053   // Bitcast operand 1 to i32.
04054   if (SrcVT == MVT::f64)
04055     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
04056                        Tmp1).getValue(1);
04057   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
04058 
04059   // Or in the signbit with integer operations.
04060   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
04061   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
04062   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
04063   if (VT == MVT::f32) {
04064     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
04065                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
04066     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
04067                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
04068   }
04069 
04070   // f64: Or the high part with signbit and then combine two parts.
04071   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
04072                      Tmp0);
04073   SDValue Lo = Tmp0.getValue(0);
04074   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
04075   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
04076   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
04077 }
04078 
04079 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
04080   MachineFunction &MF = DAG.getMachineFunction();
04081   MachineFrameInfo *MFI = MF.getFrameInfo();
04082   MFI->setReturnAddressIsTaken(true);
04083 
04084   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
04085     return SDValue();
04086 
04087   EVT VT = Op.getValueType();
04088   SDLoc dl(Op);
04089   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
04090   if (Depth) {
04091     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
04092     SDValue Offset = DAG.getConstant(4, MVT::i32);
04093     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
04094                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
04095                        MachinePointerInfo(), false, false, false, 0);
04096   }
04097 
04098   // Return LR, which contains the return address. Mark it an implicit live-in.
04099   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
04100   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
04101 }
04102 
04103 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
04104   const ARMBaseRegisterInfo &ARI =
04105     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
04106   MachineFunction &MF = DAG.getMachineFunction();
04107   MachineFrameInfo *MFI = MF.getFrameInfo();
04108   MFI->setFrameAddressIsTaken(true);
04109 
04110   EVT VT = Op.getValueType();
04111   SDLoc dl(Op);  // FIXME probably not meaningful
04112   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
04113   unsigned FrameReg = ARI.getFrameRegister(MF);
04114   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
04115   while (Depth--)
04116     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
04117                             MachinePointerInfo(),
04118                             false, false, false, 0);
04119   return FrameAddr;
04120 }
04121 
04122 // FIXME? Maybe this could be a TableGen attribute on some registers and
04123 // this table could be generated automatically from RegInfo.
04124 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
04125                                               EVT VT) const {
04126   unsigned Reg = StringSwitch<unsigned>(RegName)
04127                        .Case("sp", ARM::SP)
04128                        .Default(0);
04129   if (Reg)
04130     return Reg;
04131   report_fatal_error("Invalid register name global variable");
04132 }
04133 
04134 /// ExpandBITCAST - If the target supports VFP, this function is called to
04135 /// expand a bit convert where either the source or destination type is i64 to
04136 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
04137 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
04138 /// vectors), since the legalizer won't know what to do with that.
04139 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
04140   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
04141   SDLoc dl(N);
04142   SDValue Op = N->getOperand(0);
04143 
04144   // This function is only supposed to be called for i64 types, either as the
04145   // source or destination of the bit convert.
04146   EVT SrcVT = Op.getValueType();
04147   EVT DstVT = N->getValueType(0);
04148   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
04149          "ExpandBITCAST called for non-i64 type");
04150 
04151   // Turn i64->f64 into VMOVDRR.
04152   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
04153     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
04154                              DAG.getConstant(0, MVT::i32));
04155     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
04156                              DAG.getConstant(1, MVT::i32));
04157     return DAG.getNode(ISD::BITCAST, dl, DstVT,
04158                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
04159   }
04160 
04161   // Turn f64->i64 into VMOVRRD.
04162   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
04163     SDValue Cvt;
04164     if (TLI.isBigEndian() && SrcVT.isVector() &&
04165         SrcVT.getVectorNumElements() > 1)
04166       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
04167                         DAG.getVTList(MVT::i32, MVT::i32),
04168                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
04169     else
04170       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
04171                         DAG.getVTList(MVT::i32, MVT::i32), Op);
04172     // Merge the pieces into a single i64 value.
04173     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
04174   }
04175 
04176   return SDValue();
04177 }
04178 
04179 /// getZeroVector - Returns a vector of specified type with all zero elements.
04180 /// Zero vectors are used to represent vector negation and in those cases
04181 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
04182 /// not support i64 elements, so sometimes the zero vectors will need to be
04183 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
04184 /// zero vector.
04185 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
04186   assert(VT.isVector() && "Expected a vector type");
04187   // The canonical modified immediate encoding of a zero vector is....0!
04188   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
04189   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
04190   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
04191   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
04192 }
04193 
04194 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
04195 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
04196 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
04197                                                 SelectionDAG &DAG) const {
04198   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04199   EVT VT = Op.getValueType();
04200   unsigned VTBits = VT.getSizeInBits();
04201   SDLoc dl(Op);
04202   SDValue ShOpLo = Op.getOperand(0);
04203   SDValue ShOpHi = Op.getOperand(1);
04204   SDValue ShAmt  = Op.getOperand(2);
04205   SDValue ARMcc;
04206   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
04207 
04208   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
04209 
04210   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
04211                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
04212   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
04213   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
04214                                    DAG.getConstant(VTBits, MVT::i32));
04215   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
04216   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
04217   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
04218 
04219   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
04220   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
04221                           ARMcc, DAG, dl);
04222   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
04223   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
04224                            CCR, Cmp);
04225 
04226   SDValue Ops[2] = { Lo, Hi };
04227   return DAG.getMergeValues(Ops, dl);
04228 }
04229 
04230 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
04231 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
04232 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
04233                                                SelectionDAG &DAG) const {
04234   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
04235   EVT VT = Op.getValueType();
04236   unsigned VTBits = VT.getSizeInBits();
04237   SDLoc dl(Op);
04238   SDValue ShOpLo = Op.getOperand(0);
04239   SDValue ShOpHi = Op.getOperand(1);
04240   SDValue ShAmt  = Op.getOperand(2);
04241   SDValue ARMcc;
04242 
04243   assert(Op.getOpcode() == ISD::SHL_PARTS);
04244   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
04245                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
04246   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
04247   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
04248                                    DAG.getConstant(VTBits, MVT::i32));
04249   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
04250   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
04251 
04252   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
04253   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
04254   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
04255                           ARMcc, DAG, dl);
04256   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
04257   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
04258                            CCR, Cmp);
04259 
04260   SDValue Ops[2] = { Lo, Hi };
04261   return DAG.getMergeValues(Ops, dl);
04262 }
04263 
04264 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
04265                                             SelectionDAG &DAG) const {
04266   // The rounding mode is in bits 23:22 of the FPSCR.
04267   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
04268   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
04269   // so that the shift + and get folded into a bitfield extract.
04270   SDLoc dl(Op);
04271   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
04272                               DAG.getConstant(Intrinsic::arm_get_fpscr,
04273                                               MVT::i32));
04274   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
04275                                   DAG.getConstant(1U << 22, MVT::i32));
04276   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
04277                               DAG.getConstant(22, MVT::i32));
04278   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
04279                      DAG.getConstant(3, MVT::i32));
04280 }
04281 
04282 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
04283                          const ARMSubtarget *ST) {
04284   EVT VT = N->getValueType(0);
04285   SDLoc dl(N);
04286 
04287   if (!ST->hasV6T2Ops())
04288     return SDValue();
04289 
04290   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
04291   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
04292 }
04293 
04294 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
04295 /// for each 16-bit element from operand, repeated.  The basic idea is to
04296 /// leverage vcnt to get the 8-bit counts, gather and add the results.
04297 ///
04298 /// Trace for v4i16:
04299 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
04300 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
04301 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
04302 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
04303 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
04304 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
04305 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
04306 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
04307 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
04308   EVT VT = N->getValueType(0);
04309   SDLoc DL(N);
04310 
04311   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
04312   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
04313   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
04314   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
04315   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
04316   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
04317 }
04318 
04319 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
04320 /// bit-count for each 16-bit element from the operand.  We need slightly
04321 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
04322 /// 64/128-bit registers.
04323 ///
04324 /// Trace for v4i16:
04325 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
04326 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
04327 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
04328 /// v4i16:Extracted = [k0    k1    k2    k3    ]
04329 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
04330   EVT VT = N->getValueType(0);
04331   SDLoc DL(N);
04332 
04333   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
04334   if (VT.is64BitVector()) {
04335     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
04336     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
04337                        DAG.getIntPtrConstant(0));
04338   } else {
04339     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
04340                                     BitCounts, DAG.getIntPtrConstant(0));
04341     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
04342   }
04343 }
04344 
04345 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
04346 /// bit-count for each 32-bit element from the operand.  The idea here is
04347 /// to split the vector into 16-bit elements, leverage the 16-bit count
04348 /// routine, and then combine the results.
04349 ///
04350 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
04351 /// input    = [v0    v1    ] (vi: 32-bit elements)
04352 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
04353 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
04354 /// vrev: N0 = [k1 k0 k3 k2 ]
04355 ///            [k0 k1 k2 k3 ]
04356 ///       N1 =+[k1 k0 k3 k2 ]
04357 ///            [k0 k2 k1 k3 ]
04358 ///       N2 =+[k1 k3 k0 k2 ]
04359 ///            [k0    k2    k1    k3    ]
04360 /// Extended =+[k1    k3    k0    k2    ]
04361 ///            [k0    k2    ]
04362 /// Extracted=+[k1    k3    ]
04363 ///
04364 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
04365   EVT VT = N->getValueType(0);
04366   SDLoc DL(N);
04367 
04368   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
04369 
04370   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
04371   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
04372   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
04373   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
04374   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
04375 
04376   if (VT.is64BitVector()) {
04377     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
04378     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
04379                        DAG.getIntPtrConstant(0));
04380   } else {
04381     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
04382                                     DAG.getIntPtrConstant(0));
04383     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
04384   }
04385 }
04386 
04387 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
04388                           const ARMSubtarget *ST) {
04389   EVT VT = N->getValueType(0);
04390 
04391   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
04392   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
04393           VT == MVT::v4i16 || VT == MVT::v8i16) &&
04394          "Unexpected type for custom ctpop lowering");
04395 
04396   if (VT.getVectorElementType() == MVT::i32)
04397     return lowerCTPOP32BitElements(N, DAG);
04398   else
04399     return lowerCTPOP16BitElements(N, DAG);
04400 }
04401 
04402 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
04403                           const ARMSubtarget *ST) {
04404   EVT VT = N->getValueType(0);
04405   SDLoc dl(N);
04406 
04407   if (!VT.isVector())
04408     return SDValue();
04409 
04410   // Lower vector shifts on NEON to use VSHL.
04411   assert(ST->hasNEON() && "unexpected vector shift");
04412 
04413   // Left shifts translate directly to the vshiftu intrinsic.
04414   if (N->getOpcode() == ISD::SHL)
04415     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
04416                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
04417                        N->getOperand(0), N->getOperand(1));
04418 
04419   assert((N->getOpcode() == ISD::SRA ||
04420           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
04421 
04422   // NEON uses the same intrinsics for both left and right shifts.  For
04423   // right shifts, the shift amounts are negative, so negate the vector of
04424   // shift amounts.
04425   EVT ShiftVT = N->getOperand(1).getValueType();
04426   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
04427                                      getZeroVector(ShiftVT, DAG, dl),
04428                                      N->getOperand(1));
04429   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
04430                              Intrinsic::arm_neon_vshifts :
04431                              Intrinsic::arm_neon_vshiftu);
04432   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
04433                      DAG.getConstant(vshiftInt, MVT::i32),
04434                      N->getOperand(0), NegatedCount);
04435 }
04436 
04437 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
04438                                 const ARMSubtarget *ST) {
04439   EVT VT = N->getValueType(0);
04440   SDLoc dl(N);
04441 
04442   // We can get here for a node like i32 = ISD::SHL i32, i64
04443   if (VT != MVT::i64)
04444     return SDValue();
04445 
04446   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
04447          "Unknown shift to lower!");
04448 
04449   // We only lower SRA, SRL of 1 here, all others use generic lowering.
04450   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
04451       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
04452     return SDValue();
04453 
04454   // If we are in thumb mode, we don't have RRX.
04455   if (ST->isThumb1Only()) return SDValue();
04456 
04457   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
04458   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
04459                            DAG.getConstant(0, MVT::i32));
04460   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
04461                            DAG.getConstant(1, MVT::i32));
04462 
04463   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
04464   // captures the result into a carry flag.
04465   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
04466   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
04467 
04468   // The low part is an ARMISD::RRX operand, which shifts the carry in.
04469   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
04470 
04471   // Merge the pieces into a single i64 value.
04472  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
04473 }
04474 
04475 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
04476   SDValue TmpOp0, TmpOp1;
04477   bool Invert = false;
04478   bool Swap = false;
04479   unsigned Opc = 0;
04480 
04481   SDValue Op0 = Op.getOperand(0);
04482   SDValue Op1 = Op.getOperand(1);
04483   SDValue CC = Op.getOperand(2);
04484   EVT VT = Op.getValueType();
04485   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
04486   SDLoc dl(Op);
04487 
04488   if (Op1.getValueType().isFloatingPoint()) {
04489     switch (SetCCOpcode) {
04490     default: llvm_unreachable("Illegal FP comparison");
04491     case ISD::SETUNE:
04492     case ISD::SETNE:  Invert = true; // Fallthrough
04493     case ISD::SETOEQ:
04494     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
04495     case ISD::SETOLT:
04496     case ISD::SETLT: Swap = true; // Fallthrough
04497     case ISD::SETOGT:
04498     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
04499     case ISD::SETOLE:
04500     case ISD::SETLE:  Swap = true; // Fallthrough
04501     case ISD::SETOGE:
04502     case ISD::SETGE: Opc = ARMISD::VCGE; break;
04503     case ISD::SETUGE: Swap = true; // Fallthrough
04504     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
04505     case ISD::SETUGT: Swap = true; // Fallthrough
04506     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
04507     case ISD::SETUEQ: Invert = true; // Fallthrough
04508     case ISD::SETONE:
04509       // Expand this to (OLT | OGT).
04510       TmpOp0 = Op0;
04511       TmpOp1 = Op1;
04512       Opc = ISD::OR;
04513       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
04514       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
04515       break;
04516     case ISD::SETUO: Invert = true; // Fallthrough
04517     case ISD::SETO:
04518       // Expand this to (OLT | OGE).
04519       TmpOp0 = Op0;
04520       TmpOp1 = Op1;
04521       Opc = ISD::OR;
04522       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
04523       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
04524       break;
04525     }
04526   } else {
04527     // Integer comparisons.
04528     switch (SetCCOpcode) {
04529     default: llvm_unreachable("Illegal integer comparison");
04530     case ISD::SETNE:  Invert = true;
04531     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
04532     case ISD::SETLT:  Swap = true;
04533     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
04534     case ISD::SETLE:  Swap = true;
04535     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
04536     case ISD::SETULT: Swap = true;
04537     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
04538     case ISD::SETULE: Swap = true;
04539     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
04540     }
04541 
04542     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
04543     if (Opc == ARMISD::VCEQ) {
04544 
04545       SDValue AndOp;
04546       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
04547         AndOp = Op0;
04548       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
04549         AndOp = Op1;
04550 
04551       // Ignore bitconvert.
04552       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
04553         AndOp = AndOp.getOperand(0);
04554 
04555       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
04556         Opc = ARMISD::VTST;
04557         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
04558         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
04559         Invert = !Invert;
04560       }
04561     }
04562   }
04563 
04564   if (Swap)
04565     std::swap(Op0, Op1);
04566 
04567   // If one of the operands is a constant vector zero, attempt to fold the
04568   // comparison to a specialized compare-against-zero form.
04569   SDValue SingleOp;
04570   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
04571     SingleOp = Op0;
04572   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
04573     if (Opc == ARMISD::VCGE)
04574       Opc = ARMISD::VCLEZ;
04575     else if (Opc == ARMISD::VCGT)
04576       Opc = ARMISD::VCLTZ;
04577     SingleOp = Op1;
04578   }
04579 
04580   SDValue Result;
04581   if (SingleOp.getNode()) {
04582     switch (Opc) {
04583     case ARMISD::VCEQ:
04584       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
04585     case ARMISD::VCGE:
04586       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
04587     case ARMISD::VCLEZ:
04588       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
04589     case ARMISD::VCGT:
04590       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
04591     case ARMISD::VCLTZ:
04592       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
04593     default:
04594       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
04595     }
04596   } else {
04597      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
04598   }
04599 
04600   if (Invert)
04601     Result = DAG.getNOT(dl, Result, VT);
04602 
04603   return Result;
04604 }
04605 
04606 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
04607 /// valid vector constant for a NEON instruction with a "modified immediate"
04608 /// operand (e.g., VMOV).  If so, return the encoded value.
04609 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
04610                                  unsigned SplatBitSize, SelectionDAG &DAG,
04611                                  EVT &VT, bool is128Bits, NEONModImmType type) {
04612   unsigned OpCmode, Imm;
04613 
04614   // SplatBitSize is set to the smallest size that splats the vector, so a
04615   // zero vector will always have SplatBitSize == 8.  However, NEON modified
04616   // immediate instructions others than VMOV do not support the 8-bit encoding
04617   // of a zero vector, and the default encoding of zero is supposed to be the
04618   // 32-bit version.
04619   if (SplatBits == 0)
04620     SplatBitSize = 32;
04621 
04622   switch (SplatBitSize) {
04623   case 8:
04624     if (type != VMOVModImm)
04625       return SDValue();
04626     // Any 1-byte value is OK.  Op=0, Cmode=1110.
04627     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
04628     OpCmode = 0xe;
04629     Imm = SplatBits;
04630     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
04631     break;
04632 
04633   case 16:
04634     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
04635     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
04636     if ((SplatBits & ~0xff) == 0) {
04637       // Value = 0x00nn: Op=x, Cmode=100x.
04638       OpCmode = 0x8;
04639       Imm = SplatBits;
04640       break;
04641     }
04642     if ((SplatBits & ~0xff00) == 0) {
04643       // Value = 0xnn00: Op=x, Cmode=101x.
04644       OpCmode = 0xa;
04645       Imm = SplatBits >> 8;
04646       break;
04647     }
04648     return SDValue();
04649 
04650   case 32:
04651     // NEON's 32-bit VMOV supports splat values where:
04652     // * only one byte is nonzero, or
04653     // * the least significant byte is 0xff and the second byte is nonzero, or
04654     // * the least significant 2 bytes are 0xff and the third is nonzero.
04655     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
04656     if ((SplatBits & ~0xff) == 0) {
04657       // Value = 0x000000nn: Op=x, Cmode=000x.
04658       OpCmode = 0;
04659       Imm = SplatBits;
04660       break;
04661     }
04662     if ((SplatBits & ~0xff00) == 0) {
04663       // Value = 0x0000nn00: Op=x, Cmode=001x.
04664       OpCmode = 0x2;
04665       Imm = SplatBits >> 8;
04666       break;
04667     }
04668     if ((SplatBits & ~0xff0000) == 0) {
04669       // Value = 0x00nn0000: Op=x, Cmode=010x.
04670       OpCmode = 0x4;
04671       Imm = SplatBits >> 16;
04672       break;
04673     }
04674     if ((SplatBits & ~0xff000000) == 0) {
04675       // Value = 0xnn000000: Op=x, Cmode=011x.
04676       OpCmode = 0x6;
04677       Imm = SplatBits >> 24;
04678       break;
04679     }
04680 
04681     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
04682     if (type == OtherModImm) return SDValue();
04683 
04684     if ((SplatBits & ~0xffff) == 0 &&
04685         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
04686       // Value = 0x0000nnff: Op=x, Cmode=1100.
04687       OpCmode = 0xc;
04688       Imm = SplatBits >> 8;
04689       break;
04690     }
04691 
04692     if ((SplatBits & ~0xffffff) == 0 &&
04693         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
04694       // Value = 0x00nnffff: Op=x, Cmode=1101.
04695       OpCmode = 0xd;
04696       Imm = SplatBits >> 16;
04697       break;
04698     }
04699 
04700     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
04701     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
04702     // VMOV.I32.  A (very) minor optimization would be to replicate the value
04703     // and fall through here to test for a valid 64-bit splat.  But, then the
04704     // caller would also need to check and handle the change in size.
04705     return SDValue();
04706 
04707   case 64: {
04708     if (type != VMOVModImm)
04709       return SDValue();
04710     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
04711     uint64_t BitMask = 0xff;
04712     uint64_t Val = 0;
04713     unsigned ImmMask = 1;
04714     Imm = 0;
04715     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
04716       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
04717         Val |= BitMask;
04718         Imm |= ImmMask;
04719       } else if ((SplatBits & BitMask) != 0) {
04720         return SDValue();
04721       }
04722       BitMask <<= 8;
04723       ImmMask <<= 1;
04724     }
04725 
04726     if (DAG.getTargetLoweringInfo().isBigEndian())
04727       // swap higher and lower 32 bit word
04728       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
04729 
04730     // Op=1, Cmode=1110.
04731     OpCmode = 0x1e;
04732     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
04733     break;
04734   }
04735 
04736   default:
04737     llvm_unreachable("unexpected size for isNEONModifiedImm");
04738   }
04739 
04740   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
04741   return DAG.getTargetConstant(EncodedVal, MVT::i32);
04742 }
04743 
04744 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
04745                                            const ARMSubtarget *ST) const {
04746   if (!ST->hasVFP3())
04747     return SDValue();
04748 
04749   bool IsDouble = Op.getValueType() == MVT::f64;
04750   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
04751 
04752   // Use the default (constant pool) lowering for double constants when we have
04753   // an SP-only FPU
04754   if (IsDouble && Subtarget->isFPOnlySP())
04755     return SDValue();
04756 
04757   // Try splatting with a VMOV.f32...
04758   APFloat FPVal = CFP->getValueAPF();
04759   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
04760 
04761   if (ImmVal != -1) {
04762     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
04763       // We have code in place to select a valid ConstantFP already, no need to
04764       // do any mangling.
04765       return Op;
04766     }
04767 
04768     // It's a float and we are trying to use NEON operations where
04769     // possible. Lower it to a splat followed by an extract.
04770     SDLoc DL(Op);
04771     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
04772     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
04773                                       NewVal);
04774     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
04775                        DAG.getConstant(0, MVT::i32));
04776   }
04777 
04778   // The rest of our options are NEON only, make sure that's allowed before
04779   // proceeding..
04780   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
04781     return SDValue();
04782 
04783   EVT VMovVT;
04784   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
04785 
04786   // It wouldn't really be worth bothering for doubles except for one very
04787   // important value, which does happen to match: 0.0. So make sure we don't do
04788   // anything stupid.
04789   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
04790     return SDValue();
04791 
04792   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
04793   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
04794                                      false, VMOVModImm);
04795   if (NewVal != SDValue()) {
04796     SDLoc DL(Op);
04797     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
04798                                       NewVal);
04799     if (IsDouble)
04800       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
04801 
04802     // It's a float: cast and extract a vector element.
04803     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
04804                                        VecConstant);
04805     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
04806                        DAG.getConstant(0, MVT::i32));
04807   }
04808 
04809   // Finally, try a VMVN.i32
04810   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
04811                              false, VMVNModImm);
04812   if (NewVal != SDValue()) {
04813     SDLoc DL(Op);
04814     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
04815 
04816     if (IsDouble)
04817       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
04818 
04819     // It's a float: cast and extract a vector element.
04820     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
04821                                        VecConstant);
04822     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
04823                        DAG.getConstant(0, MVT::i32));
04824   }
04825 
04826   return SDValue();
04827 }
04828 
04829 // check if an VEXT instruction can handle the shuffle mask when the
04830 // vector sources of the shuffle are the same.
04831 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
04832   unsigned NumElts = VT.getVectorNumElements();
04833 
04834   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
04835   if (M[0] < 0)
04836     return false;
04837 
04838   Imm = M[0];
04839 
04840   // If this is a VEXT shuffle, the immediate value is the index of the first
04841   // element.  The other shuffle indices must be the successive elements after
04842   // the first one.
04843   unsigned ExpectedElt = Imm;
04844   for (unsigned i = 1; i < NumElts; ++i) {
04845     // Increment the expected index.  If it wraps around, just follow it
04846     // back to index zero and keep going.
04847     ++ExpectedElt;
04848     if (ExpectedElt == NumElts)
04849       ExpectedElt = 0;
04850 
04851     if (M[i] < 0) continue; // ignore UNDEF indices
04852     if (ExpectedElt != static_cast<unsigned>(M[i]))
04853       return false;
04854   }
04855 
04856   return true;
04857 }
04858 
04859 
04860 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
04861                        bool &ReverseVEXT, unsigned &Imm) {
04862   unsigned NumElts = VT.getVectorNumElements();
04863   ReverseVEXT = false;
04864 
04865   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
04866   if (M[0] < 0)
04867     return false;
04868 
04869   Imm = M[0];
04870 
04871   // If this is a VEXT shuffle, the immediate value is the index of the first
04872   // element.  The other shuffle indices must be the successive elements after
04873   // the first one.
04874   unsigned ExpectedElt = Imm;
04875   for (unsigned i = 1; i < NumElts; ++i) {
04876     // Increment the expected index.  If it wraps around, it may still be
04877     // a VEXT but the source vectors must be swapped.
04878     ExpectedElt += 1;
04879     if (ExpectedElt == NumElts * 2) {
04880       ExpectedElt = 0;
04881       ReverseVEXT = true;
04882     }
04883 
04884     if (M[i] < 0) continue; // ignore UNDEF indices
04885     if (ExpectedElt != static_cast<unsigned>(M[i]))
04886       return false;
04887   }
04888 
04889   // Adjust the index value if the source operands will be swapped.
04890   if (ReverseVEXT)
04891     Imm -= NumElts;
04892 
04893   return true;
04894 }
04895 
04896 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
04897 /// instruction with the specified blocksize.  (The order of the elements
04898 /// within each block of the vector is reversed.)
04899 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
04900   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
04901          "Only possible block sizes for VREV are: 16, 32, 64");
04902 
04903   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04904   if (EltSz == 64)
04905     return false;
04906 
04907   unsigned NumElts = VT.getVectorNumElements();
04908   unsigned BlockElts = M[0] + 1;
04909   // If the first shuffle index is UNDEF, be optimistic.
04910   if (M[0] < 0)
04911     BlockElts = BlockSize / EltSz;
04912 
04913   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
04914     return false;
04915 
04916   for (unsigned i = 0; i < NumElts; ++i) {
04917     if (M[i] < 0) continue; // ignore UNDEF indices
04918     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
04919       return false;
04920   }
04921 
04922   return true;
04923 }
04924 
04925 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
04926   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
04927   // range, then 0 is placed into the resulting vector. So pretty much any mask
04928   // of 8 elements can work here.
04929   return VT == MVT::v8i8 && M.size() == 8;
04930 }
04931 
04932 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
04933   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04934   if (EltSz == 64)
04935     return false;
04936 
04937   unsigned NumElts = VT.getVectorNumElements();
04938   WhichResult = (M[0] == 0 ? 0 : 1);
04939   for (unsigned i = 0; i < NumElts; i += 2) {
04940     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
04941         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
04942       return false;
04943   }
04944   return true;
04945 }
04946 
04947 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
04948 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
04949 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
04950 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
04951   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04952   if (EltSz == 64)
04953     return false;
04954 
04955   unsigned NumElts = VT.getVectorNumElements();
04956   WhichResult = (M[0] == 0 ? 0 : 1);
04957   for (unsigned i = 0; i < NumElts; i += 2) {
04958     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
04959         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
04960       return false;
04961   }
04962   return true;
04963 }
04964 
04965 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
04966   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04967   if (EltSz == 64)
04968     return false;
04969 
04970   unsigned NumElts = VT.getVectorNumElements();
04971   WhichResult = (M[0] == 0 ? 0 : 1);
04972   for (unsigned i = 0; i != NumElts; ++i) {
04973     if (M[i] < 0) continue; // ignore UNDEF indices
04974     if ((unsigned) M[i] != 2 * i + WhichResult)
04975       return false;
04976   }
04977 
04978   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
04979   if (VT.is64BitVector() && EltSz == 32)
04980     return false;
04981 
04982   return true;
04983 }
04984 
04985 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
04986 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
04987 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
04988 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
04989   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
04990   if (EltSz == 64)
04991     return false;
04992 
04993   unsigned Half = VT.getVectorNumElements() / 2;
04994   WhichResult = (M[0] == 0 ? 0 : 1);
04995   for (unsigned j = 0; j != 2; ++j) {
04996     unsigned Idx = WhichResult;
04997     for (unsigned i = 0; i != Half; ++i) {
04998       int MIdx = M[i + j * Half];
04999       if (MIdx >= 0 && (unsigned) MIdx != Idx)
05000         return false;
05001       Idx += 2;
05002     }
05003   }
05004 
05005   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
05006   if (VT.is64BitVector() && EltSz == 32)
05007     return false;
05008 
05009   return true;
05010 }
05011 
05012 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
05013   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
05014   if (EltSz == 64)
05015     return false;
05016 
05017   unsigned NumElts = VT.getVectorNumElements();
05018   WhichResult = (M[0] == 0 ? 0 : 1);
05019   unsigned Idx = WhichResult * NumElts / 2;
05020   for (unsigned i = 0; i != NumElts; i += 2) {
05021     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
05022         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
05023       return false;
05024     Idx += 1;
05025   }
05026 
05027   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
05028   if (VT.is64BitVector() && EltSz == 32)
05029     return false;
05030 
05031   return true;
05032 }
05033 
05034 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
05035 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
05036 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
05037 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
05038   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
05039   if (EltSz == 64)
05040     return false;
05041 
05042   unsigned NumElts = VT.getVectorNumElements();
05043   WhichResult = (M[0] == 0 ? 0 : 1);
05044   unsigned Idx = WhichResult * NumElts / 2;
05045   for (unsigned i = 0; i != NumElts; i += 2) {
05046     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
05047         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
05048       return false;
05049     Idx += 1;
05050   }
05051 
05052   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
05053   if (VT.is64BitVector() && EltSz == 32)
05054     return false;
05055 
05056   return true;
05057 }
05058 
05059 /// \return true if this is a reverse operation on an vector.
05060 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
05061   unsigned NumElts = VT.getVectorNumElements();
05062   // Make sure the mask has the right size.
05063   if (NumElts != M.size())
05064       return false;
05065 
05066   // Look for <15, ..., 3, -1, 1, 0>.
05067   for (unsigned i = 0; i != NumElts; ++i)
05068     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
05069       return false;
05070 
05071   return true;
05072 }
05073 
05074 // If N is an integer constant that can be moved into a register in one
05075 // instruction, return an SDValue of such a constant (will become a MOV
05076 // instruction).  Otherwise return null.
05077 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
05078                                      const ARMSubtarget *ST, SDLoc dl) {
05079   uint64_t Val;
05080   if (!isa<ConstantSDNode>(N))
05081     return SDValue();
05082   Val = cast<ConstantSDNode>(N)->getZExtValue();
05083 
05084   if (ST->isThumb1Only()) {
05085     if (Val <= 255 || ~Val <= 255)
05086       return DAG.getConstant(Val, MVT::i32);
05087   } else {
05088     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
05089       return DAG.getConstant(Val, MVT::i32);
05090   }
05091   return SDValue();
05092 }
05093 
05094 // If this is a case we can't handle, return null and let the default
05095 // expansion code take care of it.
05096 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
05097                                              const ARMSubtarget *ST) const {
05098   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
05099   SDLoc dl(Op);
05100   EVT VT = Op.getValueType();
05101 
05102   APInt SplatBits, SplatUndef;
05103   unsigned SplatBitSize;
05104   bool HasAnyUndefs;
05105   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
05106     if (SplatBitSize <= 64) {
05107       // Check if an immediate VMOV works.
05108       EVT VmovVT;
05109       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
05110                                       SplatUndef.getZExtValue(), SplatBitSize,
05111                                       DAG, VmovVT, VT.is128BitVector(),
05112                                       VMOVModImm);
05113       if (Val.getNode()) {
05114         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
05115         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
05116       }
05117 
05118       // Try an immediate VMVN.
05119       uint64_t NegatedImm = (~SplatBits).getZExtValue();
05120       Val = isNEONModifiedImm(NegatedImm,
05121                                       SplatUndef.getZExtValue(), SplatBitSize,
05122                                       DAG, VmovVT, VT.is128BitVector(),
05123                                       VMVNModImm);
05124       if (Val.getNode()) {
05125         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
05126         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
05127       }
05128 
05129       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
05130       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
05131         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
05132         if (ImmVal != -1) {
05133           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
05134           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
05135         }
05136       }
05137     }
05138   }
05139 
05140   // Scan through the operands to see if only one value is used.
05141   //
05142   // As an optimisation, even if more than one value is used it may be more
05143   // profitable to splat with one value then change some lanes.
05144   //
05145   // Heuristically we decide to do this if the vector has a "dominant" value,
05146   // defined as splatted to more than half of the lanes.
05147   unsigned NumElts = VT.getVectorNumElements();
05148   bool isOnlyLowElement = true;
05149   bool usesOnlyOneValue = true;
05150   bool hasDominantValue = false;
05151   bool isConstant = true;
05152 
05153   // Map of the number of times a particular SDValue appears in the
05154   // element list.
05155   DenseMap<SDValue, unsigned> ValueCounts;
05156   SDValue Value;
05157   for (unsigned i = 0; i < NumElts; ++i) {
05158     SDValue V = Op.getOperand(i);
05159     if (V.getOpcode() == ISD::UNDEF)
05160       continue;
05161     if (i > 0)
05162       isOnlyLowElement = false;
05163     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
05164       isConstant = false;
05165 
05166     ValueCounts.insert(std::make_pair(V, 0));
05167     unsigned &Count = ValueCounts[V];
05168 
05169     // Is this value dominant? (takes up more than half of the lanes)
05170     if (++Count > (NumElts / 2)) {
05171       hasDominantValue = true;
05172       Value = V;
05173     }
05174   }
05175   if (ValueCounts.size() != 1)
05176     usesOnlyOneValue = false;
05177   if (!Value.getNode() && ValueCounts.size() > 0)
05178     Value = ValueCounts.begin()->first;
05179 
05180   if (ValueCounts.size() == 0)
05181     return DAG.getUNDEF(VT);
05182 
05183   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
05184   // Keep going if we are hitting this case.
05185   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
05186     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
05187 
05188   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
05189 
05190   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
05191   // i32 and try again.
05192   if (hasDominantValue && EltSize <= 32) {
05193     if (!isConstant) {
05194       SDValue N;
05195 
05196       // If we are VDUPing a value that comes directly from a vector, that will
05197       // cause an unnecessary move to and from a GPR, where instead we could
05198       // just use VDUPLANE. We can only do this if the lane being extracted
05199       // is at a constant index, as the VDUP from lane instructions only have
05200       // constant-index forms.
05201       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
05202           isa<ConstantSDNode>(Value->getOperand(1))) {
05203         // We need to create a new undef vector to use for the VDUPLANE if the
05204         // size of the vector from which we get the value is different than the
05205         // size of the vector that we need to create. We will insert the element
05206         // such that the register coalescer will remove unnecessary copies.
05207         if (VT != Value->getOperand(0).getValueType()) {
05208           ConstantSDNode *constIndex;
05209           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
05210           assert(constIndex && "The index is not a constant!");
05211           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
05212                              VT.getVectorNumElements();
05213           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
05214                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
05215                         Value, DAG.getConstant(index, MVT::i32)),
05216                            DAG.getConstant(index, MVT::i32));
05217         } else
05218           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
05219                         Value->getOperand(0), Value->getOperand(1));
05220       } else
05221         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
05222 
05223       if (!usesOnlyOneValue) {
05224         // The dominant value was splatted as 'N', but we now have to insert
05225         // all differing elements.
05226         for (unsigned I = 0; I < NumElts; ++I) {
05227           if (Op.getOperand(I) == Value)
05228             continue;
05229           SmallVector<SDValue, 3> Ops;
05230           Ops.push_back(N);
05231           Ops.push_back(Op.getOperand(I));
05232           Ops.push_back(DAG.getConstant(I, MVT::i32));
05233           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
05234         }
05235       }
05236       return N;
05237     }
05238     if (VT.getVectorElementType().isFloatingPoint()) {
05239       SmallVector<SDValue, 8> Ops;
05240       for (unsigned i = 0; i < NumElts; ++i)
05241         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
05242                                   Op.getOperand(i)));
05243       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
05244       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
05245       Val = LowerBUILD_VECTOR(Val, DAG, ST);
05246       if (Val.getNode())
05247         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
05248     }
05249     if (usesOnlyOneValue) {
05250       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
05251       if (isConstant && Val.getNode())
05252         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
05253     }
05254   }
05255 
05256   // If all elements are constants and the case above didn't get hit, fall back
05257   // to the default expansion, which will generate a load from the constant
05258   // pool.
05259   if (isConstant)
05260     return SDValue();
05261 
05262   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
05263   if (NumElts >= 4) {
05264     SDValue shuffle = ReconstructShuffle(Op, DAG);
05265     if (shuffle != SDValue())
05266       return shuffle;
05267   }
05268 
05269   // Vectors with 32- or 64-bit elements can be built by directly assigning
05270   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
05271   // will be legalized.
05272   if (EltSize >= 32) {
05273     // Do the expansion with floating-point types, since that is what the VFP
05274     // registers are defined to use, and since i64 is not legal.
05275     EVT EltVT = EVT::getFloatingPointVT(EltSize);
05276     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
05277     SmallVector<SDValue, 8> Ops;
05278     for (unsigned i = 0; i < NumElts; ++i)
05279       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
05280     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
05281     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
05282   }
05283 
05284   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
05285   // know the default expansion would otherwise fall back on something even
05286   // worse. For a vector with one or two non-undef values, that's
05287   // scalar_to_vector for the elements followed by a shuffle (provided the
05288   // shuffle is valid for the target) and materialization element by element
05289   // on the stack followed by a load for everything else.
05290   if (!isConstant && !usesOnlyOneValue) {
05291     SDValue Vec = DAG.getUNDEF(VT);
05292     for (unsigned i = 0 ; i < NumElts; ++i) {
05293       SDValue V = Op.getOperand(i);
05294       if (V.getOpcode() == ISD::UNDEF)
05295         continue;
05296       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
05297       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
05298     }
05299     return Vec;
05300   }
05301 
05302   return SDValue();
05303 }
05304 
05305 // Gather data to see if the operation can be modelled as a
05306 // shuffle in combination with VEXTs.
05307 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
05308                                               SelectionDAG &DAG) const {
05309   SDLoc dl(Op);
05310   EVT VT = Op.getValueType();
05311   unsigned NumElts = VT.getVectorNumElements();
05312 
05313   SmallVector<SDValue, 2> SourceVecs;
05314   SmallVector<unsigned, 2> MinElts;
05315   SmallVector<unsigned, 2> MaxElts;
05316 
05317   for (unsigned i = 0; i < NumElts; ++i) {
05318     SDValue V = Op.getOperand(i);
05319     if (V.getOpcode() == ISD::UNDEF)
05320       continue;
05321     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
05322       // A shuffle can only come from building a vector from various
05323       // elements of other vectors.
05324       return SDValue();
05325     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
05326                VT.getVectorElementType()) {
05327       // This code doesn't know how to handle shuffles where the vector
05328       // element types do not match (this happens because type legalization
05329       // promotes the return type of EXTRACT_VECTOR_ELT).
05330       // FIXME: It might be appropriate to extend this code to handle
05331       // mismatched types.
05332       return SDValue();
05333     }
05334 
05335     // Record this extraction against the appropriate vector if possible...
05336     SDValue SourceVec = V.getOperand(0);
05337     // If the element number isn't a constant, we can't effectively
05338     // analyze what's going on.
05339     if (!isa<ConstantSDNode>(V.getOperand(1)))
05340       return SDValue();
05341     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
05342     bool FoundSource = false;
05343     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
05344       if (SourceVecs[j] == SourceVec) {
05345         if (MinElts[j] > EltNo)
05346           MinElts[j] = EltNo;
05347         if (MaxElts[j] < EltNo)
05348           MaxElts[j] = EltNo;
05349         FoundSource = true;
05350         break;
05351       }
05352     }
05353 
05354     // Or record a new source if not...
05355     if (!FoundSource) {
05356       SourceVecs.push_back(SourceVec);
05357       MinElts.push_back(EltNo);
05358       MaxElts.push_back(EltNo);
05359     }
05360   }
05361 
05362   // Currently only do something sane when at most two source vectors
05363   // involved.
05364   if (SourceVecs.size() > 2)
05365     return SDValue();
05366 
05367   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
05368   int VEXTOffsets[2] = {0, 0};
05369 
05370   // This loop extracts the usage patterns of the source vectors
05371   // and prepares appropriate SDValues for a shuffle if possible.
05372   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
05373     if (SourceVecs[i].getValueType() == VT) {
05374       // No VEXT necessary
05375       ShuffleSrcs[i] = SourceVecs[i];
05376       VEXTOffsets[i] = 0;
05377       continue;
05378     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
05379       // It probably isn't worth padding out a smaller vector just to
05380       // break it down again in a shuffle.
05381       return SDValue();
05382     }
05383 
05384     // Since only 64-bit and 128-bit vectors are legal on ARM and
05385     // we've eliminated the other cases...
05386     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
05387            "unexpected vector sizes in ReconstructShuffle");
05388 
05389     if (MaxElts[i] - MinElts[i] >= NumElts) {
05390       // Span too large for a VEXT to cope
05391       return SDValue();
05392     }
05393 
05394     if (MinElts[i] >= NumElts) {
05395       // The extraction can just take the second half
05396       VEXTOffsets[i] = NumElts;
05397       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05398                                    SourceVecs[i],
05399                                    DAG.getIntPtrConstant(NumElts));
05400     } else if (MaxElts[i] < NumElts) {
05401       // The extraction can just take the first half
05402       VEXTOffsets[i] = 0;
05403       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05404                                    SourceVecs[i],
05405                                    DAG.getIntPtrConstant(0));
05406     } else {
05407       // An actual VEXT is needed
05408       VEXTOffsets[i] = MinElts[i];
05409       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05410                                      SourceVecs[i],
05411                                      DAG.getIntPtrConstant(0));
05412       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
05413                                      SourceVecs[i],
05414                                      DAG.getIntPtrConstant(NumElts));
05415       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
05416                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
05417     }
05418   }
05419 
05420   SmallVector<int, 8> Mask;
05421 
05422   for (unsigned i = 0; i < NumElts; ++i) {
05423     SDValue Entry = Op.getOperand(i);
05424     if (Entry.getOpcode() == ISD::UNDEF) {
05425       Mask.push_back(-1);
05426       continue;
05427     }
05428 
05429     SDValue ExtractVec = Entry.getOperand(0);
05430     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
05431                                           .getOperand(1))->getSExtValue();
05432     if (ExtractVec == SourceVecs[0]) {
05433       Mask.push_back(ExtractElt - VEXTOffsets[0]);
05434     } else {
05435       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
05436     }
05437   }
05438 
05439   // Final check before we try to produce nonsense...
05440   if (isShuffleMaskLegal(Mask, VT))
05441     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
05442                                 &Mask[0]);
05443 
05444   return SDValue();
05445 }
05446 
05447 /// isShuffleMaskLegal - Targets can use this to indicate that they only
05448 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
05449 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values