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