1193323Sed//===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file defines the interfaces that ARM uses to lower LLVM code into a
11193323Sed// selection DAG.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15234353Sdim#include "ARMISelLowering.h"
16218893Sdim#include "ARMCallingConv.h"
17193323Sed#include "ARMConstantPoolValue.h"
18193323Sed#include "ARMMachineFunctionInfo.h"
19198090Srdivacky#include "ARMPerfectShuffle.h"
20193323Sed#include "ARMSubtarget.h"
21193323Sed#include "ARMTargetMachine.h"
22198090Srdivacky#include "ARMTargetObjectFile.h"
23226633Sdim#include "MCTargetDesc/ARMAddressingModes.h"
24249423Sdim#include "llvm/ADT/Statistic.h"
25249423Sdim#include "llvm/ADT/StringExtras.h"
26288943Sdim#include "llvm/ADT/StringSwitch.h"
27193323Sed#include "llvm/CodeGen/CallingConvLower.h"
28218893Sdim#include "llvm/CodeGen/IntrinsicLowering.h"
29193323Sed#include "llvm/CodeGen/MachineBasicBlock.h"
30193323Sed#include "llvm/CodeGen/MachineFrameInfo.h"
31193323Sed#include "llvm/CodeGen/MachineFunction.h"
32193323Sed#include "llvm/CodeGen/MachineInstrBuilder.h"
33280031Sdim#include "llvm/CodeGen/MachineJumpTableInfo.h"
34226633Sdim#include "llvm/CodeGen/MachineModuleInfo.h"
35193323Sed#include "llvm/CodeGen/MachineRegisterInfo.h"
36193323Sed#include "llvm/CodeGen/SelectionDAG.h"
37249423Sdim#include "llvm/IR/CallingConv.h"
38249423Sdim#include "llvm/IR/Constants.h"
39249423Sdim#include "llvm/IR/Function.h"
40249423Sdim#include "llvm/IR/GlobalValue.h"
41276479Sdim#include "llvm/IR/IRBuilder.h"
42249423Sdim#include "llvm/IR/Instruction.h"
43249423Sdim#include "llvm/IR/Instructions.h"
44288943Sdim#include "llvm/IR/IntrinsicInst.h"
45249423Sdim#include "llvm/IR/Intrinsics.h"
46249423Sdim#include "llvm/IR/Type.h"
47204961Srdivacky#include "llvm/MC/MCSectionMachO.h"
48207618Srdivacky#include "llvm/Support/CommandLine.h"
49276479Sdim#include "llvm/Support/Debug.h"
50198090Srdivacky#include "llvm/Support/ErrorHandling.h"
51193323Sed#include "llvm/Support/MathExtras.h"
52288943Sdim#include "llvm/Support/raw_ostream.h"
53249423Sdim#include "llvm/Target/TargetOptions.h"
54261991Sdim#include <utility>
55193323Sedusing namespace llvm;
56193323Sed
57276479Sdim#define DEBUG_TYPE "arm-isel"
58276479Sdim
59210299SedSTATISTIC(NumTailCalls, "Number of tail calls");
60218893SdimSTATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61239462SdimSTATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62210299Sed
63210299Sedstatic cl::opt<bool>
64210299SedARMInterworking("arm-interworking", cl::Hidden,
65210299Sed  cl::desc("Enable / disable ARM interworking (for debugging only)"),
66210299Sed  cl::init(true));
67210299Sed
68234353Sdimnamespace {
69223017Sdim  class ARMCCState : public CCState {
70223017Sdim  public:
71223017Sdim    ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72280031Sdim               SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73280031Sdim               ParmContext PC)
74280031Sdim        : CCState(CC, isVarArg, MF, locs, C) {
75223017Sdim      assert(((PC == Call) || (PC == Prologue)) &&
76223017Sdim             "ARMCCState users must specify whether their context is call"
77223017Sdim             "or prologue generation.");
78223017Sdim      CallOrPrologue = PC;
79223017Sdim    }
80223017Sdim  };
81223017Sdim}
82223017Sdim
83221345Sdim// The APCS parameter registers.
84276479Sdimstatic const MCPhysReg GPRArgRegs[] = {
85221345Sdim  ARM::R0, ARM::R1, ARM::R2, ARM::R3
86221345Sdim};
87221345Sdim
88239462Sdimvoid ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89239462Sdim                                       MVT PromotedBitwiseVT) {
90194710Sed  if (VT != PromotedLdStVT) {
91239462Sdim    setOperationAction(ISD::LOAD, VT, Promote);
92239462Sdim    AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93194710Sed
94239462Sdim    setOperationAction(ISD::STORE, VT, Promote);
95239462Sdim    AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96194710Sed  }
97194710Sed
98239462Sdim  MVT ElemTy = VT.getVectorElementType();
99194710Sed  if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100239462Sdim    setOperationAction(ISD::SETCC, VT, Custom);
101239462Sdim  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102239462Sdim  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103234353Sdim  if (ElemTy == MVT::i32) {
104239462Sdim    setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105239462Sdim    setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106239462Sdim    setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107239462Sdim    setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108234353Sdim  } else {
109239462Sdim    setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110239462Sdim    setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111239462Sdim    setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112239462Sdim    setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113198090Srdivacky  }
114239462Sdim  setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115239462Sdim  setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116239462Sdim  setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117239462Sdim  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118239462Sdim  setOperationAction(ISD::SELECT,            VT, Expand);
119239462Sdim  setOperationAction(ISD::SELECT_CC,         VT, Expand);
120243830Sdim  setOperationAction(ISD::VSELECT,           VT, Expand);
121239462Sdim  setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122194710Sed  if (VT.isInteger()) {
123239462Sdim    setOperationAction(ISD::SHL, VT, Custom);
124239462Sdim    setOperationAction(ISD::SRA, VT, Custom);
125239462Sdim    setOperationAction(ISD::SRL, VT, Custom);
126194710Sed  }
127194710Sed
128194710Sed  // Promote all bit-wise operations.
129194710Sed  if (VT.isInteger() && VT != PromotedBitwiseVT) {
130239462Sdim    setOperationAction(ISD::AND, VT, Promote);
131239462Sdim    AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132239462Sdim    setOperationAction(ISD::OR,  VT, Promote);
133239462Sdim    AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134239462Sdim    setOperationAction(ISD::XOR, VT, Promote);
135239462Sdim    AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136194710Sed  }
137198090Srdivacky
138198090Srdivacky  // Neon does not support vector divide/remainder operations.
139239462Sdim  setOperationAction(ISD::SDIV, VT, Expand);
140239462Sdim  setOperationAction(ISD::UDIV, VT, Expand);
141239462Sdim  setOperationAction(ISD::FDIV, VT, Expand);
142239462Sdim  setOperationAction(ISD::SREM, VT, Expand);
143239462Sdim  setOperationAction(ISD::UREM, VT, Expand);
144239462Sdim  setOperationAction(ISD::FREM, VT, Expand);
145296417Sdim
146296417Sdim  if (!VT.isFloatingPoint() &&
147296417Sdim      VT != MVT::v2i64 && VT != MVT::v1i64)
148296417Sdim    for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
149296417Sdim      setOperationAction(Opcode, VT, Legal);
150194710Sed}
151194710Sed
152239462Sdimvoid ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153239462Sdim  addRegisterClass(VT, &ARM::DPRRegClass);
154194710Sed  addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155194710Sed}
156194710Sed
157239462Sdimvoid ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158262613Sdim  addRegisterClass(VT, &ARM::DPairRegClass);
159194710Sed  addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160194710Sed}
161194710Sed
162288943SdimARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163288943Sdim                                     const ARMSubtarget &STI)
164288943Sdim    : TargetLowering(TM), Subtarget(&STI) {
165288943Sdim  RegInfo = Subtarget->getRegisterInfo();
166288943Sdim  Itins = Subtarget->getInstrItineraryData();
167193323Sed
168226633Sdim  setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169226633Sdim
170276479Sdim  if (Subtarget->isTargetMachO()) {
171193323Sed    // Uses VFP for Thumb libfuncs if available.
172261991Sdim    if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173288943Sdim        Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174296417Sdim      static const struct {
175296417Sdim        const RTLIB::Libcall Op;
176296417Sdim        const char * const Name;
177296417Sdim        const ISD::CondCode Cond;
178296417Sdim      } LibraryCalls[] = {
179296417Sdim        // Single-precision floating-point arithmetic.
180296417Sdim        { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181296417Sdim        { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182296417Sdim        { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183296417Sdim        { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184193323Sed
185296417Sdim        // Double-precision floating-point arithmetic.
186296417Sdim        { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187296417Sdim        { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188296417Sdim        { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189296417Sdim        { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190193323Sed
191296417Sdim        // Single-precision comparisons.
192296417Sdim        { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193296417Sdim        { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194296417Sdim        { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195296417Sdim        { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196296417Sdim        { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197296417Sdim        { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198296417Sdim        { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199296417Sdim        { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200193323Sed
201296417Sdim        // Double-precision comparisons.
202296417Sdim        { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203296417Sdim        { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204296417Sdim        { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205296417Sdim        { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206296417Sdim        { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207296417Sdim        { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208296417Sdim        { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209296417Sdim        { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210193323Sed
211296417Sdim        // Floating-point to integer conversions.
212296417Sdim        // i64 conversions are done via library routines even when generating VFP
213296417Sdim        // instructions, so use the same ones.
214296417Sdim        { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215296417Sdim        { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216296417Sdim        { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217296417Sdim        { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218193323Sed
219296417Sdim        // Conversions between floating types.
220296417Sdim        { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221296417Sdim        { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222193323Sed
223296417Sdim        // Integer to floating-point conversions.
224296417Sdim        // i64 conversions are done via library routines even when generating VFP
225296417Sdim        // instructions, so use the same ones.
226296417Sdim        // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227296417Sdim        // e.g., __floatunsidf vs. __floatunssidfvfp.
228296417Sdim        { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229296417Sdim        { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230296417Sdim        { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231296417Sdim        { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232296417Sdim      };
233193323Sed
234296417Sdim      for (const auto &LC : LibraryCalls) {
235296417Sdim        setLibcallName(LC.Op, LC.Name);
236296417Sdim        if (LC.Cond != ISD::SETCC_INVALID)
237296417Sdim          setCmpLibcallCC(LC.Op, LC.Cond);
238296417Sdim      }
239296417Sdim    }
240193323Sed
241296417Sdim    // Set the correct calling convention for ARMv7k WatchOS. It's just
242296417Sdim    // AAPCS_VFP for functions as simple as libcalls.
243296417Sdim    if (Subtarget->isTargetWatchOS()) {
244296417Sdim      for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
245296417Sdim        setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
246193323Sed    }
247193323Sed  }
248193323Sed
249193323Sed  // These libcalls are not available in 32-bit.
250276479Sdim  setLibcallName(RTLIB::SHL_I128, nullptr);
251276479Sdim  setLibcallName(RTLIB::SRL_I128, nullptr);
252276479Sdim  setLibcallName(RTLIB::SRA_I128, nullptr);
253193323Sed
254296417Sdim  // RTLIB
255296417Sdim  if (Subtarget->isAAPCS_ABI() &&
256296417Sdim      (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
257296417Sdim       Subtarget->isTargetAndroid())) {
258276479Sdim    static const struct {
259276479Sdim      const RTLIB::Libcall Op;
260276479Sdim      const char * const Name;
261276479Sdim      const CallingConv::ID CC;
262276479Sdim      const ISD::CondCode Cond;
263276479Sdim    } LibraryCalls[] = {
264276479Sdim      // Double-precision floating-point arithmetic helper functions
265276479Sdim      // RTABI chapter 4.1.2, Table 2
266276479Sdim      { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
267276479Sdim      { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268276479Sdim      { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269276479Sdim      { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270218893Sdim
271276479Sdim      // Double-precision floating-point comparison helper functions
272276479Sdim      // RTABI chapter 4.1.2, Table 3
273276479Sdim      { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
274276479Sdim      { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
275276479Sdim      { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
276276479Sdim      { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
277276479Sdim      { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
278276479Sdim      { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
279276479Sdim      { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
280276479Sdim      { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
281218893Sdim
282276479Sdim      // Single-precision floating-point arithmetic helper functions
283276479Sdim      // RTABI chapter 4.1.2, Table 4
284276479Sdim      { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
285276479Sdim      { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286276479Sdim      { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287276479Sdim      { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288218893Sdim
289276479Sdim      // Single-precision floating-point comparison helper functions
290276479Sdim      // RTABI chapter 4.1.2, Table 5
291276479Sdim      { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
292276479Sdim      { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
293276479Sdim      { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
294276479Sdim      { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
295276479Sdim      { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
296276479Sdim      { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
297276479Sdim      { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
298276479Sdim      { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
299218893Sdim
300276479Sdim      // Floating-point to integer conversions.
301276479Sdim      // RTABI chapter 4.1.2, Table 6
302276479Sdim      { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303276479Sdim      { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304276479Sdim      { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305276479Sdim      { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306276479Sdim      { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307276479Sdim      { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308276479Sdim      { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309276479Sdim      { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310218893Sdim
311276479Sdim      // Conversions between floating types.
312276479Sdim      // RTABI chapter 4.1.2, Table 7
313276479Sdim      { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314280031Sdim      { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315276479Sdim      { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316218893Sdim
317276479Sdim      // Integer to floating-point conversions.
318276479Sdim      // RTABI chapter 4.1.2, Table 8
319276479Sdim      { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320276479Sdim      { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321276479Sdim      { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322276479Sdim      { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323276479Sdim      { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324276479Sdim      { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325276479Sdim      { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326276479Sdim      { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327218893Sdim
328276479Sdim      // Long long helper functions
329276479Sdim      // RTABI chapter 4.2, Table 9
330276479Sdim      { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331276479Sdim      { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332276479Sdim      { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333276479Sdim      { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334218893Sdim
335276479Sdim      // Integer division functions
336276479Sdim      // RTABI chapter 4.3.1
337276479Sdim      { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338276479Sdim      { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339276479Sdim      { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340276479Sdim      { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341276479Sdim      { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342276479Sdim      { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343276479Sdim      { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344276479Sdim      { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345276479Sdim    };
346276479Sdim
347276479Sdim    for (const auto &LC : LibraryCalls) {
348276479Sdim      setLibcallName(LC.Op, LC.Name);
349276479Sdim      setLibcallCallingConv(LC.Op, LC.CC);
350276479Sdim      if (LC.Cond != ISD::SETCC_INVALID)
351276479Sdim        setCmpLibcallCC(LC.Op, LC.Cond);
352276479Sdim    }
353296417Sdim
354296417Sdim    // EABI dependent RTLIB
355296417Sdim    if (TM.Options.EABIVersion == EABI::EABI4 ||
356296417Sdim        TM.Options.EABIVersion == EABI::EABI5) {
357296417Sdim      static const struct {
358296417Sdim        const RTLIB::Libcall Op;
359296417Sdim        const char *const Name;
360296417Sdim        const CallingConv::ID CC;
361296417Sdim        const ISD::CondCode Cond;
362296417Sdim      } MemOpsLibraryCalls[] = {
363296417Sdim        // Memory operations
364296417Sdim        // RTABI chapter 4.3.4
365296417Sdim        { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366296417Sdim        { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367296417Sdim        { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368296417Sdim      };
369296417Sdim
370296417Sdim      for (const auto &LC : MemOpsLibraryCalls) {
371296417Sdim        setLibcallName(LC.Op, LC.Name);
372296417Sdim        setLibcallCallingConv(LC.Op, LC.CC);
373296417Sdim        if (LC.Cond != ISD::SETCC_INVALID)
374296417Sdim          setCmpLibcallCC(LC.Op, LC.Cond);
375296417Sdim      }
376296417Sdim    }
377221345Sdim  }
378221345Sdim
379276479Sdim  if (Subtarget->isTargetWindows()) {
380276479Sdim    static const struct {
381276479Sdim      const RTLIB::Libcall Op;
382276479Sdim      const char * const Name;
383276479Sdim      const CallingConv::ID CC;
384276479Sdim    } LibraryCalls[] = {
385276479Sdim      { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
386276479Sdim      { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
387276479Sdim      { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
388276479Sdim      { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
389276479Sdim      { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
390276479Sdim      { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
391276479Sdim      { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
392276479Sdim      { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
393296417Sdim      { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
394296417Sdim      { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
395296417Sdim      { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
396296417Sdim      { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
397276479Sdim    };
398276479Sdim
399276479Sdim    for (const auto &LC : LibraryCalls) {
400276479Sdim      setLibcallName(LC.Op, LC.Name);
401276479Sdim      setLibcallCallingConv(LC.Op, LC.CC);
402276479Sdim    }
403276479Sdim  }
404276479Sdim
405226633Sdim  // Use divmod compiler-rt calls for iOS 5.0 and later.
406296417Sdim  if (Subtarget->isTargetWatchOS() ||
407296417Sdim      (Subtarget->isTargetIOS() &&
408296417Sdim       !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
409226633Sdim    setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
410226633Sdim    setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
411226633Sdim  }
412226633Sdim
413280031Sdim  // The half <-> float conversion functions are always soft-float, but are
414280031Sdim  // needed for some targets which use a hard-float calling convention by
415280031Sdim  // default.
416280031Sdim  if (Subtarget->isAAPCS_ABI()) {
417280031Sdim    setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
418280031Sdim    setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
419280031Sdim    setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
420280031Sdim  } else {
421280031Sdim    setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
422280031Sdim    setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
423280031Sdim    setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
424280031Sdim  }
425280031Sdim
426296417Sdim  // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
427296417Sdim  // a __gnu_ prefix (which is the default).
428296417Sdim  if (Subtarget->isTargetAEABI()) {
429296417Sdim    setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
430296417Sdim    setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
431296417Sdim    setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
432296417Sdim  }
433296417Sdim
434198090Srdivacky  if (Subtarget->isThumb1Only())
435239462Sdim    addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
436193323Sed  else
437239462Sdim    addRegisterClass(MVT::i32, &ARM::GPRRegClass);
438288943Sdim  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
439234353Sdim      !Subtarget->isThumb1Only()) {
440239462Sdim    addRegisterClass(MVT::f32, &ARM::SPRRegClass);
441280031Sdim    addRegisterClass(MVT::f64, &ARM::DPRRegClass);
442193323Sed  }
443194710Sed
444280031Sdim  for (MVT VT : MVT::vector_valuetypes()) {
445280031Sdim    for (MVT InnerVT : MVT::vector_valuetypes()) {
446280031Sdim      setTruncStoreAction(VT, InnerVT, Expand);
447280031Sdim      setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
448280031Sdim      setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
449280031Sdim      setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
450280031Sdim    }
451276479Sdim
452280031Sdim    setOperationAction(ISD::MULHS, VT, Expand);
453280031Sdim    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454280031Sdim    setOperationAction(ISD::MULHU, VT, Expand);
455280031Sdim    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
456276479Sdim
457280031Sdim    setOperationAction(ISD::BSWAP, VT, Expand);
458234353Sdim  }
459234353Sdim
460234353Sdim  setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
461261991Sdim  setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
462234353Sdim
463288943Sdim  setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
464288943Sdim  setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
465288943Sdim
466194710Sed  if (Subtarget->hasNEON()) {
467194710Sed    addDRTypeForNEON(MVT::v2f32);
468194710Sed    addDRTypeForNEON(MVT::v8i8);
469194710Sed    addDRTypeForNEON(MVT::v4i16);
470194710Sed    addDRTypeForNEON(MVT::v2i32);
471194710Sed    addDRTypeForNEON(MVT::v1i64);
472194710Sed
473194710Sed    addQRTypeForNEON(MVT::v4f32);
474194710Sed    addQRTypeForNEON(MVT::v2f64);
475194710Sed    addQRTypeForNEON(MVT::v16i8);
476194710Sed    addQRTypeForNEON(MVT::v8i16);
477194710Sed    addQRTypeForNEON(MVT::v4i32);
478194710Sed    addQRTypeForNEON(MVT::v2i64);
479194710Sed
480198090Srdivacky    // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
481198090Srdivacky    // neither Neon nor VFP support any arithmetic operations on it.
482234353Sdim    // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
483234353Sdim    // supported for v4f32.
484198090Srdivacky    setOperationAction(ISD::FADD, MVT::v2f64, Expand);
485198090Srdivacky    setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
486198090Srdivacky    setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
487234353Sdim    // FIXME: Code duplication: FDIV and FREM are expanded always, see
488234353Sdim    // ARMTargetLowering::addTypeForNEON method for details.
489198090Srdivacky    setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
490198090Srdivacky    setOperationAction(ISD::FREM, MVT::v2f64, Expand);
491234353Sdim    // FIXME: Create unittest.
492234353Sdim    // In another words, find a way when "copysign" appears in DAG with vector
493234353Sdim    // operands.
494198090Srdivacky    setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
495234353Sdim    // FIXME: Code duplication: SETCC has custom operation action, see
496234353Sdim    // ARMTargetLowering::addTypeForNEON method for details.
497226633Sdim    setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
498234353Sdim    // FIXME: Create unittest for FNEG and for FABS.
499198090Srdivacky    setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
500198090Srdivacky    setOperationAction(ISD::FABS, MVT::v2f64, Expand);
501198090Srdivacky    setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
502198090Srdivacky    setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
503198090Srdivacky    setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
504198090Srdivacky    setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
505198090Srdivacky    setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
506198090Srdivacky    setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
507198090Srdivacky    setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
508198090Srdivacky    setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
509198090Srdivacky    setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
510198090Srdivacky    setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
511234353Sdim    // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
512198090Srdivacky    setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
513198090Srdivacky    setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
514198090Srdivacky    setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
515198090Srdivacky    setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
516198090Srdivacky    setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
517249423Sdim    setOperationAction(ISD::FMA, MVT::v2f64, Expand);
518198090Srdivacky
519234353Sdim    setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
520234353Sdim    setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
521234353Sdim    setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
522234353Sdim    setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
523234353Sdim    setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
524234353Sdim    setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
525234353Sdim    setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
526234353Sdim    setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
527234353Sdim    setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
528234353Sdim    setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
529249423Sdim    setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
530249423Sdim    setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
531249423Sdim    setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
532249423Sdim    setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
533243830Sdim    setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
534212904Sdim
535249423Sdim    // Mark v2f32 intrinsics.
536249423Sdim    setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
537249423Sdim    setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
538249423Sdim    setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
539249423Sdim    setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
540249423Sdim    setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
541249423Sdim    setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
542249423Sdim    setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
543249423Sdim    setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
544249423Sdim    setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
545249423Sdim    setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
546249423Sdim    setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
547249423Sdim    setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
548249423Sdim    setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
549249423Sdim    setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
550249423Sdim    setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
551249423Sdim
552198090Srdivacky    // Neon does not support some operations on v1i64 and v2i64 types.
553198090Srdivacky    setOperationAction(ISD::MUL, MVT::v1i64, Expand);
554212904Sdim    // Custom handling for some quad-vector types to detect VMULL.
555212904Sdim    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
556212904Sdim    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
557212904Sdim    setOperationAction(ISD::MUL, MVT::v2i64, Custom);
558218893Sdim    // Custom handling for some vector types to avoid expensive expansions
559218893Sdim    setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
560218893Sdim    setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
561218893Sdim    setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
562218893Sdim    setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
563226633Sdim    setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
564226633Sdim    setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
565221345Sdim    // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
566234353Sdim    // a destination type that is wider than the source, and nor does
567234353Sdim    // it have a FP_TO_[SU]INT instruction with a narrower destination than
568234353Sdim    // source.
569221345Sdim    setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
570221345Sdim    setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
571234353Sdim    setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
572234353Sdim    setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
573198090Srdivacky
574249423Sdim    setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
575249423Sdim    setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
576249423Sdim
577249423Sdim    // NEON does not have single instruction CTPOP for vectors with element
578249423Sdim    // types wider than 8-bits.  However, custom lowering can leverage the
579249423Sdim    // v8i8/v16i8 vcnt instruction.
580249423Sdim    setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581249423Sdim    setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582249423Sdim    setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583249423Sdim    setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584249423Sdim
585288943Sdim    // NEON does not have single instruction CTTZ for vectors.
586288943Sdim    setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
587288943Sdim    setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
588288943Sdim    setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
589288943Sdim    setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
590288943Sdim
591288943Sdim    setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
592288943Sdim    setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
593288943Sdim    setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
594288943Sdim    setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
595288943Sdim
596288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
597288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
598288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
599288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
600288943Sdim
601288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
602288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
603288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
604288943Sdim    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
605288943Sdim
606249423Sdim    // NEON only has FMA instructions as of VFP4.
607249423Sdim    if (!Subtarget->hasVFP4()) {
608249423Sdim      setOperationAction(ISD::FMA, MVT::v2f32, Expand);
609249423Sdim      setOperationAction(ISD::FMA, MVT::v4f32, Expand);
610249423Sdim    }
611249423Sdim
612218893Sdim    setTargetDAGCombine(ISD::INTRINSIC_VOID);
613218893Sdim    setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
614194710Sed    setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
615194710Sed    setTargetDAGCombine(ISD::SHL);
616194710Sed    setTargetDAGCombine(ISD::SRL);
617194710Sed    setTargetDAGCombine(ISD::SRA);
618194710Sed    setTargetDAGCombine(ISD::SIGN_EXTEND);
619194710Sed    setTargetDAGCombine(ISD::ZERO_EXTEND);
620194710Sed    setTargetDAGCombine(ISD::ANY_EXTEND);
621218893Sdim    setTargetDAGCombine(ISD::BUILD_VECTOR);
622218893Sdim    setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
623218893Sdim    setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
624218893Sdim    setTargetDAGCombine(ISD::STORE);
625224145Sdim    setTargetDAGCombine(ISD::FP_TO_SINT);
626224145Sdim    setTargetDAGCombine(ISD::FP_TO_UINT);
627224145Sdim    setTargetDAGCombine(ISD::FDIV);
628288943Sdim    setTargetDAGCombine(ISD::LOAD);
629234353Sdim
630234353Sdim    // It is legal to extload from v4i8 to v4i16 or v4i32.
631288943Sdim    for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
632288943Sdim                   MVT::v2i32}) {
633280031Sdim      for (MVT VT : MVT::integer_vector_valuetypes()) {
634288943Sdim        setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
635288943Sdim        setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
636288943Sdim        setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
637280031Sdim      }
638234353Sdim    }
639194710Sed  }
640194710Sed
641243830Sdim  // ARM and Thumb2 support UMLAL/SMLAL.
642243830Sdim  if (!Subtarget->isThumb1Only())
643243830Sdim    setTargetDAGCombine(ISD::ADDC);
644243830Sdim
645280031Sdim  if (Subtarget->isFPOnlySP()) {
646296417Sdim    // When targeting a floating-point unit with only single-precision
647280031Sdim    // operations, f64 is legal for the few double-precision instructions which
648280031Sdim    // are present However, no double-precision operations other than moves,
649280031Sdim    // loads and stores are provided by the hardware.
650280031Sdim    setOperationAction(ISD::FADD,       MVT::f64, Expand);
651280031Sdim    setOperationAction(ISD::FSUB,       MVT::f64, Expand);
652280031Sdim    setOperationAction(ISD::FMUL,       MVT::f64, Expand);
653280031Sdim    setOperationAction(ISD::FMA,        MVT::f64, Expand);
654280031Sdim    setOperationAction(ISD::FDIV,       MVT::f64, Expand);
655280031Sdim    setOperationAction(ISD::FREM,       MVT::f64, Expand);
656280031Sdim    setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
657280031Sdim    setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
658280031Sdim    setOperationAction(ISD::FNEG,       MVT::f64, Expand);
659280031Sdim    setOperationAction(ISD::FABS,       MVT::f64, Expand);
660280031Sdim    setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
661280031Sdim    setOperationAction(ISD::FSIN,       MVT::f64, Expand);
662280031Sdim    setOperationAction(ISD::FCOS,       MVT::f64, Expand);
663280031Sdim    setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
664280031Sdim    setOperationAction(ISD::FPOW,       MVT::f64, Expand);
665280031Sdim    setOperationAction(ISD::FLOG,       MVT::f64, Expand);
666280031Sdim    setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
667280031Sdim    setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
668280031Sdim    setOperationAction(ISD::FEXP,       MVT::f64, Expand);
669280031Sdim    setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
670280031Sdim    setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
671280031Sdim    setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
672280031Sdim    setOperationAction(ISD::FRINT,      MVT::f64, Expand);
673280031Sdim    setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
674280031Sdim    setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
675288943Sdim    setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
676288943Sdim    setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
677288943Sdim    setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
678288943Sdim    setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
679288943Sdim    setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
680288943Sdim    setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
681280031Sdim    setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
682280031Sdim    setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
683280031Sdim  }
684243830Sdim
685288943Sdim  computeRegisterProperties(Subtarget->getRegisterInfo());
686193323Sed
687276479Sdim  // ARM does not have floating-point extending loads.
688280031Sdim  for (MVT VT : MVT::fp_valuetypes()) {
689280031Sdim    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
690280031Sdim    setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
691280031Sdim  }
692193323Sed
693276479Sdim  // ... or truncating stores
694276479Sdim  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
695276479Sdim  setTruncStoreAction(MVT::f32, MVT::f16, Expand);
696276479Sdim  setTruncStoreAction(MVT::f64, MVT::f16, Expand);
697276479Sdim
698193323Sed  // ARM does not have i1 sign extending load.
699280031Sdim  for (MVT VT : MVT::integer_valuetypes())
700280031Sdim    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
701193323Sed
702193323Sed  // ARM supports all 4 flavors of integer indexed load / store.
703195340Sed  if (!Subtarget->isThumb1Only()) {
704195340Sed    for (unsigned im = (unsigned)ISD::PRE_INC;
705195340Sed         im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
706195340Sed      setIndexedLoadAction(im,  MVT::i1,  Legal);
707195340Sed      setIndexedLoadAction(im,  MVT::i8,  Legal);
708195340Sed      setIndexedLoadAction(im,  MVT::i16, Legal);
709195340Sed      setIndexedLoadAction(im,  MVT::i32, Legal);
710195340Sed      setIndexedStoreAction(im, MVT::i1,  Legal);
711195340Sed      setIndexedStoreAction(im, MVT::i8,  Legal);
712195340Sed      setIndexedStoreAction(im, MVT::i16, Legal);
713195340Sed      setIndexedStoreAction(im, MVT::i32, Legal);
714195340Sed    }
715193323Sed  }
716193323Sed
717276479Sdim  setOperationAction(ISD::SADDO, MVT::i32, Custom);
718276479Sdim  setOperationAction(ISD::UADDO, MVT::i32, Custom);
719276479Sdim  setOperationAction(ISD::SSUBO, MVT::i32, Custom);
720276479Sdim  setOperationAction(ISD::USUBO, MVT::i32, Custom);
721276479Sdim
722193323Sed  // i64 operation support.
723221345Sdim  setOperationAction(ISD::MUL,     MVT::i64, Expand);
724221345Sdim  setOperationAction(ISD::MULHU,   MVT::i32, Expand);
725198090Srdivacky  if (Subtarget->isThumb1Only()) {
726193323Sed    setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
727193323Sed    setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
728193323Sed  }
729224145Sdim  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
730296417Sdim      || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
731221345Sdim    setOperationAction(ISD::MULHS, MVT::i32, Expand);
732221345Sdim
733198892Srdivacky  setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
734198892Srdivacky  setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
735198892Srdivacky  setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
736193323Sed  setOperationAction(ISD::SRL,       MVT::i64, Custom);
737193323Sed  setOperationAction(ISD::SRA,       MVT::i64, Custom);
738193323Sed
739226633Sdim  if (!Subtarget->isThumb1Only()) {
740226633Sdim    // FIXME: We should do this for Thumb1 as well.
741226633Sdim    setOperationAction(ISD::ADDC,    MVT::i32, Custom);
742226633Sdim    setOperationAction(ISD::ADDE,    MVT::i32, Custom);
743226633Sdim    setOperationAction(ISD::SUBC,    MVT::i32, Custom);
744226633Sdim    setOperationAction(ISD::SUBE,    MVT::i32, Custom);
745226633Sdim  }
746226633Sdim
747296417Sdim  if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
748296417Sdim    setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
749296417Sdim
750193323Sed  // ARM does not have ROTL.
751296417Sdim  setOperationAction(ISD::ROTL, MVT::i32, Expand);
752296417Sdim  for (MVT VT : MVT::vector_valuetypes()) {
753296417Sdim    setOperationAction(ISD::ROTL, VT, Expand);
754296417Sdim    setOperationAction(ISD::ROTR, VT, Expand);
755296417Sdim  }
756202878Srdivacky  setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
757193323Sed  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
758195098Sed  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
759193323Sed    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
760193323Sed
761234353Sdim  // These just redirect to CTTZ and CTLZ on ARM.
762234353Sdim  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
763234353Sdim  setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
764234353Sdim
765296417Sdim  // @llvm.readcyclecounter requires the Performance Monitors extension.
766296417Sdim  // Default to the 0 expansion on unsupported platforms.
767296417Sdim  // FIXME: Technically there are older ARM CPUs that have
768296417Sdim  // implementation-specific ways of obtaining this information.
769296417Sdim  if (Subtarget->hasPerfMon())
770296417Sdim    setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
771261991Sdim
772193323Sed  // Only ARMv6 has BSWAP.
773193323Sed  if (!Subtarget->hasV6Ops())
774193323Sed    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
775193323Sed
776243830Sdim  if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
777243830Sdim      !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
778243830Sdim    // These are expanded into libcalls if the cpu doesn't have HW divider.
779296417Sdim    setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
780296417Sdim    setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
781208599Srdivacky  }
782261991Sdim
783193323Sed  setOperationAction(ISD::SREM,  MVT::i32, Expand);
784193323Sed  setOperationAction(ISD::UREM,  MVT::i32, Expand);
785261991Sdim  // Register based DivRem for AEABI (RTABI 4.2)
786296417Sdim  if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
787296417Sdim    setOperationAction(ISD::SREM, MVT::i64, Custom);
788296417Sdim    setOperationAction(ISD::UREM, MVT::i64, Custom);
789296417Sdim
790261991Sdim    setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
791261991Sdim    setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
792261991Sdim    setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
793261991Sdim    setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
794261991Sdim    setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
795261991Sdim    setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
796261991Sdim    setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
797261991Sdim    setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
798193323Sed
799261991Sdim    setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
800261991Sdim    setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
801261991Sdim    setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
802261991Sdim    setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
803261991Sdim    setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
804261991Sdim    setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
805261991Sdim    setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
806261991Sdim    setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
807261991Sdim
808261991Sdim    setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
809261991Sdim    setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
810261991Sdim  } else {
811261991Sdim    setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
812261991Sdim    setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
813261991Sdim  }
814261991Sdim
815193323Sed  setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
816193323Sed  setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
817193323Sed  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
818198892Srdivacky  setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
819193323Sed
820208599Srdivacky  setOperationAction(ISD::TRAP, MVT::Other, Legal);
821208599Srdivacky
822193323Sed  // Use the default implementation.
823193323Sed  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
824193323Sed  setOperationAction(ISD::VAARG,              MVT::Other, Expand);
825193323Sed  setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
826193323Sed  setOperationAction(ISD::VAEND,              MVT::Other, Expand);
827193323Sed  setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
828193323Sed  setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
829218893Sdim
830276479Sdim  if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
831276479Sdim    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
832276479Sdim  else
833276479Sdim    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
834276479Sdim
835212904Sdim  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
836280031Sdim  // the default expansion. If we are targeting a single threaded system,
837280031Sdim  // then set them all for expand so we can lower them later into their
838280031Sdim  // non-atomic form.
839280031Sdim  if (TM.Options.ThreadModel == ThreadModel::Single)
840280031Sdim    setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
841280031Sdim  else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
842276479Sdim    // ATOMIC_FENCE needs custom lowering; the others should have been expanded
843276479Sdim    // to ldrex/strex loops already.
844261991Sdim    setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
845276479Sdim
846261991Sdim    // On v8, we have particularly efficient implementations of atomic fences
847261991Sdim    // if they can be combined with nearby atomic loads and stores.
848261991Sdim    if (!Subtarget->hasV8Ops()) {
849280031Sdim      // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
850261991Sdim      setInsertFencesForAtomic(true);
851261991Sdim    }
852210299Sed  } else {
853261991Sdim    // If there's anything we can use as a barrier, go through custom lowering
854261991Sdim    // for ATOMIC_FENCE.
855261991Sdim    setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
856261991Sdim                       Subtarget->hasAnyDataBarrier() ? Custom : Expand);
857261991Sdim
858210299Sed    // Set them all for expansion, which will force libcalls.
859210299Sed    setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
860210299Sed    setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
861210299Sed    setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
862210299Sed    setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
863210299Sed    setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
864210299Sed    setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
865210299Sed    setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
866210299Sed    setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
867221345Sdim    setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
868221345Sdim    setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
869221345Sdim    setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
870221345Sdim    setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
871226633Sdim    // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
872226633Sdim    // Unordered/Monotonic case.
873226633Sdim    setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
874226633Sdim    setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
875210299Sed  }
876193323Sed
877218893Sdim  setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
878218893Sdim
879210299Sed  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
880210299Sed  if (!Subtarget->hasV6Ops()) {
881193323Sed    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
882193323Sed    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
883193323Sed  }
884193323Sed  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
885193323Sed
886288943Sdim  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
887234353Sdim      !Subtarget->isThumb1Only()) {
888202878Srdivacky    // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
889202878Srdivacky    // iff target supports vfp2.
890218893Sdim    setOperationAction(ISD::BITCAST, MVT::i64, Custom);
891212904Sdim    setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
892212904Sdim  }
893193323Sed
894193323Sed  // We want to custom lower some of our intrinsics.
895193323Sed  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
896296417Sdim  setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
897296417Sdim  setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
898296417Sdim  setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
899296417Sdim  if (Subtarget->useSjLjEH())
900223017Sdim    setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
901193323Sed
902193323Sed  setOperationAction(ISD::SETCC,     MVT::i32, Expand);
903193323Sed  setOperationAction(ISD::SETCC,     MVT::f32, Expand);
904193323Sed  setOperationAction(ISD::SETCC,     MVT::f64, Expand);
905212904Sdim  setOperationAction(ISD::SELECT,    MVT::i32, Custom);
906212904Sdim  setOperationAction(ISD::SELECT,    MVT::f32, Custom);
907212904Sdim  setOperationAction(ISD::SELECT,    MVT::f64, Custom);
908193323Sed  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
909193323Sed  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
910193323Sed  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
911193323Sed
912193323Sed  setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
913193323Sed  setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
914193323Sed  setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
915193323Sed  setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
916193323Sed  setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
917193323Sed
918193323Sed  // We don't support sin/cos/fmod/copysign/pow
919193323Sed  setOperationAction(ISD::FSIN,      MVT::f64, Expand);
920193323Sed  setOperationAction(ISD::FSIN,      MVT::f32, Expand);
921193323Sed  setOperationAction(ISD::FCOS,      MVT::f32, Expand);
922193323Sed  setOperationAction(ISD::FCOS,      MVT::f64, Expand);
923249423Sdim  setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
924249423Sdim  setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
925193323Sed  setOperationAction(ISD::FREM,      MVT::f64, Expand);
926193323Sed  setOperationAction(ISD::FREM,      MVT::f32, Expand);
927288943Sdim  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
928234353Sdim      !Subtarget->isThumb1Only()) {
929193323Sed    setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
930193323Sed    setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
931193323Sed  }
932193323Sed  setOperationAction(ISD::FPOW,      MVT::f64, Expand);
933193323Sed  setOperationAction(ISD::FPOW,      MVT::f32, Expand);
934193323Sed
935234353Sdim  if (!Subtarget->hasVFP4()) {
936234353Sdim    setOperationAction(ISD::FMA, MVT::f64, Expand);
937234353Sdim    setOperationAction(ISD::FMA, MVT::f32, Expand);
938234353Sdim  }
939224145Sdim
940205218Srdivacky  // Various VFP goodness
941288943Sdim  if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
942280031Sdim    // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
943280031Sdim    if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
944276479Sdim      setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
945276479Sdim      setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
946276479Sdim    }
947276479Sdim
948276479Sdim    // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
949205407Srdivacky    if (!Subtarget->hasFP16()) {
950276479Sdim      setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
951276479Sdim      setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
952205218Srdivacky    }
953193323Sed  }
954276479Sdim
955261991Sdim  // Combine sin / cos into one node or libcall if possible.
956261991Sdim  if (Subtarget->hasSinCos()) {
957261991Sdim    setLibcallName(RTLIB::SINCOS_F32, "sincosf");
958261991Sdim    setLibcallName(RTLIB::SINCOS_F64, "sincos");
959296417Sdim    if (Subtarget->isTargetWatchOS()) {
960296417Sdim      setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
961296417Sdim      setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
962296417Sdim    }
963296417Sdim    if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
964261991Sdim      // For iOS, we don't want to the normal expansion of a libcall to
965261991Sdim      // sincos. We want to issue a libcall to __sincos_stret.
966261991Sdim      setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
967261991Sdim      setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
968261991Sdim    }
969261991Sdim  }
970193323Sed
971280031Sdim  // FP-ARMv8 implements a lot of rounding-like FP operations.
972280031Sdim  if (Subtarget->hasFPARMv8()) {
973280031Sdim    setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
974280031Sdim    setOperationAction(ISD::FCEIL, MVT::f32, Legal);
975280031Sdim    setOperationAction(ISD::FROUND, MVT::f32, Legal);
976280031Sdim    setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
977280031Sdim    setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
978280031Sdim    setOperationAction(ISD::FRINT, MVT::f32, Legal);
979296417Sdim    setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
980296417Sdim    setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
981296417Sdim    setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
982296417Sdim    setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
983296417Sdim    setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
984296417Sdim    setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
985296417Sdim
986280031Sdim    if (!Subtarget->isFPOnlySP()) {
987280031Sdim      setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
988280031Sdim      setOperationAction(ISD::FCEIL, MVT::f64, Legal);
989280031Sdim      setOperationAction(ISD::FROUND, MVT::f64, Legal);
990280031Sdim      setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
991280031Sdim      setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
992280031Sdim      setOperationAction(ISD::FRINT, MVT::f64, Legal);
993296417Sdim      setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
994296417Sdim      setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
995280031Sdim    }
996280031Sdim  }
997296417Sdim
998296417Sdim  if (Subtarget->hasNEON()) {
999296417Sdim    // vmin and vmax aren't available in a scalar form, so we use
1000296417Sdim    // a NEON instruction with an undef lane instead.
1001296417Sdim    setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1002296417Sdim    setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1003296417Sdim    setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1004296417Sdim    setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1005296417Sdim    setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1006296417Sdim    setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1007296417Sdim  }
1008296417Sdim
1009193323Sed  // We have target-specific dag combine patterns for the following nodes:
1010199481Srdivacky  // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1011193323Sed  setTargetDAGCombine(ISD::ADD);
1012193323Sed  setTargetDAGCombine(ISD::SUB);
1013208599Srdivacky  setTargetDAGCombine(ISD::MUL);
1014243830Sdim  setTargetDAGCombine(ISD::AND);
1015243830Sdim  setTargetDAGCombine(ISD::OR);
1016243830Sdim  setTargetDAGCombine(ISD::XOR);
1017193323Sed
1018234353Sdim  if (Subtarget->hasV6Ops())
1019234353Sdim    setTargetDAGCombine(ISD::SRL);
1020234353Sdim
1021193323Sed  setStackPointerRegisterToSaveRestore(ARM::SP);
1022193323Sed
1023288943Sdim  if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1024234353Sdim      !Subtarget->hasVFP2())
1025208599Srdivacky    setSchedulingPreference(Sched::RegPressure);
1026208599Srdivacky  else
1027208599Srdivacky    setSchedulingPreference(Sched::Hybrid);
1028208599Srdivacky
1029218893Sdim  //// temporary - rewrite interface to use type
1030249423Sdim  MaxStoresPerMemset = 8;
1031296417Sdim  MaxStoresPerMemsetOptSize = 4;
1032249423Sdim  MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1033296417Sdim  MaxStoresPerMemcpyOptSize = 2;
1034249423Sdim  MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1035296417Sdim  MaxStoresPerMemmoveOptSize = 2;
1036194612Sed
1037210299Sed  // On ARM arguments smaller than 4 bytes are extended, so all arguments
1038210299Sed  // are at least 4 bytes aligned.
1039210299Sed  setMinStackArgumentAlignment(4);
1040210299Sed
1041239462Sdim  // Prefer likely predicted branches to selects on out-of-order cores.
1042249423Sdim  PredictableSelectIsExpensive = Subtarget->isLikeA9();
1043239462Sdim
1044223017Sdim  setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1045193323Sed}
1046193323Sed
1047288943Sdimbool ARMTargetLowering::useSoftFloat() const {
1048288943Sdim  return Subtarget->useSoftFloat();
1049288943Sdim}
1050288943Sdim
1051218893Sdim// FIXME: It might make sense to define the representative register class as the
1052218893Sdim// nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1053218893Sdim// a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1054218893Sdim// SPR's representative would be DPR_VFP2. This should work well if register
1055218893Sdim// pressure tracking were modified such that a register use would increment the
1056218893Sdim// pressure of the register class's representative and all of it's super
1057218893Sdim// classes' representatives transitively. We have not implemented this because
1058218893Sdim// of the difficulty prior to coalescing of modeling operand register classes
1059221345Sdim// due to the common occurrence of cross class copies and subregister insertions
1060218893Sdim// and extractions.
1061288943Sdimstd::pair<const TargetRegisterClass *, uint8_t>
1062288943SdimARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1063288943Sdim                                           MVT VT) const {
1064276479Sdim  const TargetRegisterClass *RRC = nullptr;
1065212904Sdim  uint8_t Cost = 1;
1066249423Sdim  switch (VT.SimpleTy) {
1067212904Sdim  default:
1068288943Sdim    return TargetLowering::findRepresentativeClass(TRI, VT);
1069212904Sdim  // Use DPR as representative register class for all floating point
1070212904Sdim  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1071212904Sdim  // the cost is 1 for both f32 and f64.
1072212904Sdim  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1073212904Sdim  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1074239462Sdim    RRC = &ARM::DPRRegClass;
1075218893Sdim    // When NEON is used for SP, only half of the register file is available
1076218893Sdim    // because operations that define both SP and DP results will be constrained
1077218893Sdim    // to the VFP2 class (D0-D15). We currently model this constraint prior to
1078218893Sdim    // coalescing by double-counting the SP regs. See the FIXME above.
1079218893Sdim    if (Subtarget->useNEONForSinglePrecisionFP())
1080218893Sdim      Cost = 2;
1081212904Sdim    break;
1082212904Sdim  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1083212904Sdim  case MVT::v4f32: case MVT::v2f64:
1084239462Sdim    RRC = &ARM::DPRRegClass;
1085212904Sdim    Cost = 2;
1086212904Sdim    break;
1087212904Sdim  case MVT::v4i64:
1088239462Sdim    RRC = &ARM::DPRRegClass;
1089212904Sdim    Cost = 4;
1090212904Sdim    break;
1091212904Sdim  case MVT::v8i64:
1092239462Sdim    RRC = &ARM::DPRRegClass;
1093212904Sdim    Cost = 8;
1094212904Sdim    break;
1095212904Sdim  }
1096212904Sdim  return std::make_pair(RRC, Cost);
1097212904Sdim}
1098212904Sdim
1099193323Sedconst char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1100288943Sdim  switch ((ARMISD::NodeType)Opcode) {
1101288943Sdim  case ARMISD::FIRST_NUMBER:  break;
1102193323Sed  case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1103218893Sdim  case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1104193323Sed  case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1105288943Sdim  case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1106193323Sed  case ARMISD::CALL:          return "ARMISD::CALL";
1107193323Sed  case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1108193323Sed  case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1109193323Sed  case ARMISD::tCALL:         return "ARMISD::tCALL";
1110193323Sed  case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1111193323Sed  case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1112198090Srdivacky  case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1113193323Sed  case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1114261991Sdim  case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1115193323Sed  case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1116193323Sed  case ARMISD::CMP:           return "ARMISD::CMP";
1117239462Sdim  case ARMISD::CMN:           return "ARMISD::CMN";
1118195340Sed  case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1119193323Sed  case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1120193323Sed  case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1121210299Sed  case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1122193323Sed  case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1123234353Sdim
1124193323Sed  case ARMISD::CMOV:          return "ARMISD::CMOV";
1125193323Sed
1126193323Sed  case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1127193323Sed  case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1128193323Sed  case ARMISD::RRX:           return "ARMISD::RRX";
1129193323Sed
1130226633Sdim  case ARMISD::ADDC:          return "ARMISD::ADDC";
1131226633Sdim  case ARMISD::ADDE:          return "ARMISD::ADDE";
1132226633Sdim  case ARMISD::SUBC:          return "ARMISD::SUBC";
1133226633Sdim  case ARMISD::SUBE:          return "ARMISD::SUBE";
1134226633Sdim
1135218893Sdim  case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1136218893Sdim  case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1137193323Sed
1138198892Srdivacky  case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1139296417Sdim  case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1140296417Sdim  case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1141198892Srdivacky
1142210299Sed  case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1143218893Sdim
1144193323Sed  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1145194710Sed
1146198090Srdivacky  case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1147198090Srdivacky
1148218893Sdim  case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1149200581Srdivacky
1150218893Sdim  case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1151218893Sdim
1152276479Sdim  case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1153296417Sdim  case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1154276479Sdim
1155194710Sed  case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1156218893Sdim  case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1157194710Sed  case ARMISD::VCGE:          return "ARMISD::VCGE";
1158218893Sdim  case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1159218893Sdim  case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1160194710Sed  case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1161194710Sed  case ARMISD::VCGT:          return "ARMISD::VCGT";
1162218893Sdim  case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1163218893Sdim  case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1164194710Sed  case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1165194710Sed  case ARMISD::VTST:          return "ARMISD::VTST";
1166194710Sed
1167194710Sed  case ARMISD::VSHL:          return "ARMISD::VSHL";
1168194710Sed  case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1169194710Sed  case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1170194710Sed  case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1171194710Sed  case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1172194710Sed  case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1173194710Sed  case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1174194710Sed  case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1175194710Sed  case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1176194710Sed  case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1177194710Sed  case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1178194710Sed  case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1179194710Sed  case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1180194710Sed  case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1181194710Sed  case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1182288943Sdim  case ARMISD::VSLI:          return "ARMISD::VSLI";
1183288943Sdim  case ARMISD::VSRI:          return "ARMISD::VSRI";
1184194710Sed  case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1185194710Sed  case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1186210299Sed  case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1187210299Sed  case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1188234353Sdim  case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1189198090Srdivacky  case ARMISD::VDUP:          return "ARMISD::VDUP";
1190198090Srdivacky  case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1191198090Srdivacky  case ARMISD::VEXT:          return "ARMISD::VEXT";
1192198090Srdivacky  case ARMISD::VREV64:        return "ARMISD::VREV64";
1193198090Srdivacky  case ARMISD::VREV32:        return "ARMISD::VREV32";
1194198090Srdivacky  case ARMISD::VREV16:        return "ARMISD::VREV16";
1195198090Srdivacky  case ARMISD::VZIP:          return "ARMISD::VZIP";
1196198090Srdivacky  case ARMISD::VUZP:          return "ARMISD::VUZP";
1197198090Srdivacky  case ARMISD::VTRN:          return "ARMISD::VTRN";
1198221345Sdim  case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1199221345Sdim  case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1200212904Sdim  case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1201212904Sdim  case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1202243830Sdim  case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1203243830Sdim  case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1204210299Sed  case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1205212904Sdim  case ARMISD::BFI:           return "ARMISD::BFI";
1206218893Sdim  case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1207218893Sdim  case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1208221345Sdim  case ARMISD::VBSL:          return "ARMISD::VBSL";
1209296417Sdim  case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1210218893Sdim  case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1211218893Sdim  case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1212218893Sdim  case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1213218893Sdim  case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1214218893Sdim  case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1215218893Sdim  case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1216218893Sdim  case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1217218893Sdim  case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1218218893Sdim  case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1219218893Sdim  case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1220218893Sdim  case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1221218893Sdim  case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1222218893Sdim  case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1223218893Sdim  case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1224218893Sdim  case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1225218893Sdim  case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1226218893Sdim  case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1227218893Sdim  case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1228218893Sdim  case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1229218893Sdim  case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1230193323Sed  }
1231288943Sdim  return nullptr;
1232193323Sed}
1233193323Sed
1234288943SdimEVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1235288943Sdim                                          EVT VT) const {
1236288943Sdim  if (!VT.isVector())
1237288943Sdim    return getPointerTy(DL);
1238226633Sdim  return VT.changeVectorElementTypeToInteger();
1239226633Sdim}
1240226633Sdim
1241208599Srdivacky/// getRegClassFor - Return the register class that should be used for the
1242208599Srdivacky/// specified value type.
1243249423Sdimconst TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1244208599Srdivacky  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1245208599Srdivacky  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1246208599Srdivacky  // load / store 4 to 8 consecutive D registers.
1247208599Srdivacky  if (Subtarget->hasNEON()) {
1248208599Srdivacky    if (VT == MVT::v4i64)
1249239462Sdim      return &ARM::QQPRRegClass;
1250239462Sdim    if (VT == MVT::v8i64)
1251239462Sdim      return &ARM::QQQQPRRegClass;
1252208599Srdivacky  }
1253208599Srdivacky  return TargetLowering::getRegClassFor(VT);
1254208599Srdivacky}
1255208599Srdivacky
1256288943Sdim// memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1257288943Sdim// source/dest is aligned and the copy size is large enough. We therefore want
1258288943Sdim// to align such objects passed to memory intrinsics.
1259288943Sdimbool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1260288943Sdim                                               unsigned &PrefAlign) const {
1261288943Sdim  if (!isa<MemIntrinsic>(CI))
1262288943Sdim    return false;
1263288943Sdim  MinSize = 8;
1264288943Sdim  // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1265288943Sdim  // cycle faster than 4-byte aligned LDM.
1266288943Sdim  PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1267288943Sdim  return true;
1268288943Sdim}
1269288943Sdim
1270212904Sdim// Create a fast isel object.
1271212904SdimFastISel *
1272239462SdimARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1273239462Sdim                                  const TargetLibraryInfo *libInfo) const {
1274239462Sdim  return ARM::createFastISel(funcInfo, libInfo);
1275212904Sdim}
1276212904Sdim
1277208599SrdivackySched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1278210299Sed  unsigned NumVals = N->getNumValues();
1279210299Sed  if (!NumVals)
1280210299Sed    return Sched::RegPressure;
1281210299Sed
1282210299Sed  for (unsigned i = 0; i != NumVals; ++i) {
1283208599Srdivacky    EVT VT = N->getValueType(i);
1284218893Sdim    if (VT == MVT::Glue || VT == MVT::Other)
1285218893Sdim      continue;
1286208599Srdivacky    if (VT.isFloatingPoint() || VT.isVector())
1287234353Sdim      return Sched::ILP;
1288208599Srdivacky  }
1289210299Sed
1290210299Sed  if (!N->isMachineOpcode())
1291210299Sed    return Sched::RegPressure;
1292210299Sed
1293210299Sed  // Load are scheduled for latency even if there instruction itinerary
1294210299Sed  // is not available.
1295288943Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1296224145Sdim  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1297218893Sdim
1298224145Sdim  if (MCID.getNumDefs() == 0)
1299218893Sdim    return Sched::RegPressure;
1300218893Sdim  if (!Itins->isEmpty() &&
1301224145Sdim      Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1302234353Sdim    return Sched::ILP;
1303210299Sed
1304208599Srdivacky  return Sched::RegPressure;
1305208599Srdivacky}
1306208599Srdivacky
1307193323Sed//===----------------------------------------------------------------------===//
1308193323Sed// Lowering Code
1309193323Sed//===----------------------------------------------------------------------===//
1310193323Sed
1311193323Sed/// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1312193323Sedstatic ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1313193323Sed  switch (CC) {
1314198090Srdivacky  default: llvm_unreachable("Unknown condition code!");
1315193323Sed  case ISD::SETNE:  return ARMCC::NE;
1316193323Sed  case ISD::SETEQ:  return ARMCC::EQ;
1317193323Sed  case ISD::SETGT:  return ARMCC::GT;
1318193323Sed  case ISD::SETGE:  return ARMCC::GE;
1319193323Sed  case ISD::SETLT:  return ARMCC::LT;
1320193323Sed  case ISD::SETLE:  return ARMCC::LE;
1321193323Sed  case ISD::SETUGT: return ARMCC::HI;
1322193323Sed  case ISD::SETUGE: return ARMCC::HS;
1323193323Sed  case ISD::SETULT: return ARMCC::LO;
1324193323Sed  case ISD::SETULE: return ARMCC::LS;
1325193323Sed  }
1326193323Sed}
1327193323Sed
1328198090Srdivacky/// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1329198090Srdivackystatic void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1330193323Sed                        ARMCC::CondCodes &CondCode2) {
1331193323Sed  CondCode2 = ARMCC::AL;
1332193323Sed  switch (CC) {
1333198090Srdivacky  default: llvm_unreachable("Unknown FP condition!");
1334193323Sed  case ISD::SETEQ:
1335193323Sed  case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1336193323Sed  case ISD::SETGT:
1337193323Sed  case ISD::SETOGT: CondCode = ARMCC::GT; break;
1338193323Sed  case ISD::SETGE:
1339193323Sed  case ISD::SETOGE: CondCode = ARMCC::GE; break;
1340193323Sed  case ISD::SETOLT: CondCode = ARMCC::MI; break;
1341198090Srdivacky  case ISD::SETOLE: CondCode = ARMCC::LS; break;
1342193323Sed  case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1343193323Sed  case ISD::SETO:   CondCode = ARMCC::VC; break;
1344193323Sed  case ISD::SETUO:  CondCode = ARMCC::VS; break;
1345193323Sed  case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1346193323Sed  case ISD::SETUGT: CondCode = ARMCC::HI; break;
1347193323Sed  case ISD::SETUGE: CondCode = ARMCC::PL; break;
1348193323Sed  case ISD::SETLT:
1349193323Sed  case ISD::SETULT: CondCode = ARMCC::LT; break;
1350193323Sed  case ISD::SETLE:
1351193323Sed  case ISD::SETULE: CondCode = ARMCC::LE; break;
1352193323Sed  case ISD::SETNE:
1353193323Sed  case ISD::SETUNE: CondCode = ARMCC::NE; break;
1354193323Sed  }
1355193323Sed}
1356193323Sed
1357193323Sed//===----------------------------------------------------------------------===//
1358193323Sed//                      Calling Convention Implementation
1359193323Sed//===----------------------------------------------------------------------===//
1360193323Sed
1361193323Sed#include "ARMGenCallingConv.inc"
1362193323Sed
1363276479Sdim/// getEffectiveCallingConv - Get the effective calling convention, taking into
1364276479Sdim/// account presence of floating point hardware and calling convention
1365276479Sdim/// limitations, such as support for variadic functions.
1366276479SdimCallingConv::ID
1367276479SdimARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1368276479Sdim                                           bool isVarArg) const {
1369194612Sed  switch (CC) {
1370194612Sed  default:
1371198090Srdivacky    llvm_unreachable("Unsupported calling convention");
1372276479Sdim  case CallingConv::ARM_AAPCS:
1373276479Sdim  case CallingConv::ARM_APCS:
1374276479Sdim  case CallingConv::GHC:
1375276479Sdim    return CC;
1376276479Sdim  case CallingConv::ARM_AAPCS_VFP:
1377276479Sdim    return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1378276479Sdim  case CallingConv::C:
1379218893Sdim    if (!Subtarget->isAAPCS_ABI())
1380276479Sdim      return CallingConv::ARM_APCS;
1381276479Sdim    else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1382234353Sdim             getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1383234353Sdim             !isVarArg)
1384276479Sdim      return CallingConv::ARM_AAPCS_VFP;
1385276479Sdim    else
1386276479Sdim      return CallingConv::ARM_AAPCS;
1387276479Sdim  case CallingConv::Fast:
1388296417Sdim  case CallingConv::CXX_FAST_TLS:
1389276479Sdim    if (!Subtarget->isAAPCS_ABI()) {
1390276479Sdim      if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1391276479Sdim        return CallingConv::Fast;
1392276479Sdim      return CallingConv::ARM_APCS;
1393276479Sdim    } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1394276479Sdim      return CallingConv::ARM_AAPCS_VFP;
1395276479Sdim    else
1396276479Sdim      return CallingConv::ARM_AAPCS;
1397218893Sdim  }
1398276479Sdim}
1399276479Sdim
1400276479Sdim/// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1401276479Sdim/// CallingConvention.
1402276479SdimCCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1403276479Sdim                                                 bool Return,
1404276479Sdim                                                 bool isVarArg) const {
1405276479Sdim  switch (getEffectiveCallingConv(CC, isVarArg)) {
1406276479Sdim  default:
1407276479Sdim    llvm_unreachable("Unsupported calling convention");
1408276479Sdim  case CallingConv::ARM_APCS:
1409276479Sdim    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1410194612Sed  case CallingConv::ARM_AAPCS:
1411218893Sdim    return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1412276479Sdim  case CallingConv::ARM_AAPCS_VFP:
1413276479Sdim    return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1414276479Sdim  case CallingConv::Fast:
1415276479Sdim    return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1416239462Sdim  case CallingConv::GHC:
1417239462Sdim    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1418194612Sed  }
1419194612Sed}
1420194612Sed
1421198090Srdivacky/// LowerCallResult - Lower the result values of a call into the
1422198090Srdivacky/// appropriate copies out of appropriate physical registers.
1423198090SrdivackySDValue
1424198090SrdivackyARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1425198090Srdivacky                                   CallingConv::ID CallConv, bool isVarArg,
1426198090Srdivacky                                   const SmallVectorImpl<ISD::InputArg> &Ins,
1427261991Sdim                                   SDLoc dl, SelectionDAG &DAG,
1428251662Sdim                                   SmallVectorImpl<SDValue> &InVals,
1429251662Sdim                                   bool isThisReturn, SDValue ThisVal) const {
1430193323Sed
1431193323Sed  // Assign locations to each value returned by this call.
1432193323Sed  SmallVector<CCValAssign, 16> RVLocs;
1433280031Sdim  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1434280031Sdim                    *DAG.getContext(), Call);
1435198090Srdivacky  CCInfo.AnalyzeCallResult(Ins,
1436198090Srdivacky                           CCAssignFnForNode(CallConv, /* Return*/ true,
1437198090Srdivacky                                             isVarArg));
1438193323Sed
1439193323Sed  // Copy all of the result registers out of their specified physreg.
1440193323Sed  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1441193323Sed    CCValAssign VA = RVLocs[i];
1442193323Sed
1443251662Sdim    // Pass 'this' value directly from the argument to return value, to avoid
1444251662Sdim    // reg unit interference
1445251662Sdim    if (i == 0 && isThisReturn) {
1446251662Sdim      assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1447251662Sdim             "unexpected return calling convention register assignment");
1448251662Sdim      InVals.push_back(ThisVal);
1449251662Sdim      continue;
1450251662Sdim    }
1451251662Sdim
1452193323Sed    SDValue Val;
1453193323Sed    if (VA.needsCustom()) {
1454194710Sed      // Handle f64 or half of a v2f64.
1455193323Sed      SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1456193323Sed                                      InFlag);
1457193323Sed      Chain = Lo.getValue(1);
1458193323Sed      InFlag = Lo.getValue(2);
1459193323Sed      VA = RVLocs[++i]; // skip ahead to next loc
1460193323Sed      SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1461193323Sed                                      InFlag);
1462193323Sed      Chain = Hi.getValue(1);
1463193323Sed      InFlag = Hi.getValue(2);
1464276479Sdim      if (!Subtarget->isLittle())
1465276479Sdim        std::swap (Lo, Hi);
1466199481Srdivacky      Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1467194710Sed
1468194710Sed      if (VA.getLocVT() == MVT::v2f64) {
1469194710Sed        SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1470194710Sed        Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1471288943Sdim                          DAG.getConstant(0, dl, MVT::i32));
1472194710Sed
1473194710Sed        VA = RVLocs[++i]; // skip ahead to next loc
1474194710Sed        Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1475194710Sed        Chain = Lo.getValue(1);
1476194710Sed        InFlag = Lo.getValue(2);
1477194710Sed        VA = RVLocs[++i]; // skip ahead to next loc
1478194710Sed        Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1479194710Sed        Chain = Hi.getValue(1);
1480194710Sed        InFlag = Hi.getValue(2);
1481276479Sdim        if (!Subtarget->isLittle())
1482276479Sdim          std::swap (Lo, Hi);
1483199481Srdivacky        Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1484194710Sed        Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1485288943Sdim                          DAG.getConstant(1, dl, MVT::i32));
1486194710Sed      }
1487193323Sed    } else {
1488193323Sed      Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1489193323Sed                               InFlag);
1490193323Sed      Chain = Val.getValue(1);
1491193323Sed      InFlag = Val.getValue(2);
1492193323Sed    }
1493193323Sed
1494193323Sed    switch (VA.getLocInfo()) {
1495198090Srdivacky    default: llvm_unreachable("Unknown loc info!");
1496193323Sed    case CCValAssign::Full: break;
1497193323Sed    case CCValAssign::BCvt:
1498218893Sdim      Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1499193323Sed      break;
1500193323Sed    }
1501193323Sed
1502198090Srdivacky    InVals.push_back(Val);
1503193323Sed  }
1504193323Sed
1505198090Srdivacky  return Chain;
1506193323Sed}
1507193323Sed
1508193323Sed/// LowerMemOpCallTo - Store the argument to the stack.
1509193323SedSDValue
1510198090SrdivackyARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1511198090Srdivacky                                    SDValue StackPtr, SDValue Arg,
1512261991Sdim                                    SDLoc dl, SelectionDAG &DAG,
1513198090Srdivacky                                    const CCValAssign &VA,
1514207618Srdivacky                                    ISD::ArgFlagsTy Flags) const {
1515193323Sed  unsigned LocMemOffset = VA.getLocMemOffset();
1516288943Sdim  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1517288943Sdim  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1518288943Sdim                       StackPtr, PtrOff);
1519296417Sdim  return DAG.getStore(
1520296417Sdim      Chain, dl, Arg, PtrOff,
1521296417Sdim      MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1522296417Sdim      false, false, 0);
1523193323Sed}
1524193323Sed
1525261991Sdimvoid ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1526194710Sed                                         SDValue Chain, SDValue &Arg,
1527194710Sed                                         RegsToPassVector &RegsToPass,
1528194710Sed                                         CCValAssign &VA, CCValAssign &NextVA,
1529194710Sed                                         SDValue &StackPtr,
1530261991Sdim                                         SmallVectorImpl<SDValue> &MemOpChains,
1531207618Srdivacky                                         ISD::ArgFlagsTy Flags) const {
1532194710Sed
1533199481Srdivacky  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1534194710Sed                              DAG.getVTList(MVT::i32, MVT::i32), Arg);
1535276479Sdim  unsigned id = Subtarget->isLittle() ? 0 : 1;
1536276479Sdim  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1537194710Sed
1538194710Sed  if (NextVA.isRegLoc())
1539276479Sdim    RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1540194710Sed  else {
1541194710Sed    assert(NextVA.isMemLoc());
1542276479Sdim    if (!StackPtr.getNode())
1543288943Sdim      StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1544288943Sdim                                    getPointerTy(DAG.getDataLayout()));
1545194710Sed
1546276479Sdim    MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1547198090Srdivacky                                           dl, DAG, NextVA,
1548198090Srdivacky                                           Flags));
1549194710Sed  }
1550194710Sed}
1551194710Sed
1552198090Srdivacky/// LowerCall - Lowering a call into a callseq_start <-
1553193323Sed/// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1554193323Sed/// nodes.
1555198090SrdivackySDValue
1556239462SdimARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1557207618Srdivacky                             SmallVectorImpl<SDValue> &InVals) const {
1558239462Sdim  SelectionDAG &DAG                     = CLI.DAG;
1559288943Sdim  SDLoc &dl                             = CLI.DL;
1560261991Sdim  SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1561261991Sdim  SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1562261991Sdim  SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1563239462Sdim  SDValue Chain                         = CLI.Chain;
1564239462Sdim  SDValue Callee                        = CLI.Callee;
1565239462Sdim  bool &isTailCall                      = CLI.IsTailCall;
1566239462Sdim  CallingConv::ID CallConv              = CLI.CallConv;
1567239462Sdim  bool doesNotRet                       = CLI.DoesNotReturn;
1568239462Sdim  bool isVarArg                         = CLI.IsVarArg;
1569239462Sdim
1570210299Sed  MachineFunction &MF = DAG.getMachineFunction();
1571251662Sdim  bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1572251662Sdim  bool isThisReturn   = false;
1573251662Sdim  bool isSibCall      = false;
1574288943Sdim  auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1575276479Sdim
1576226633Sdim  // Disable tail calls if they're not supported.
1577288943Sdim  if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1578210299Sed    isTailCall = false;
1579276479Sdim
1580210299Sed  if (isTailCall) {
1581210299Sed    // Check if it's really possible to do a tail call.
1582210299Sed    isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1583251662Sdim                    isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1584210299Sed                                                   Outs, OutVals, Ins, DAG);
1585276479Sdim    if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1586276479Sdim      report_fatal_error("failed to perform tail call elimination on a call "
1587276479Sdim                         "site marked musttail");
1588210299Sed    // We don't support GuaranteedTailCallOpt for ARM, only automatically
1589210299Sed    // detected sibcalls.
1590210299Sed    if (isTailCall) {
1591210299Sed      ++NumTailCalls;
1592251662Sdim      isSibCall = true;
1593210299Sed    }
1594210299Sed  }
1595193323Sed
1596193323Sed  // Analyze operands of the call, assigning locations to each operand.
1597193323Sed  SmallVector<CCValAssign, 16> ArgLocs;
1598280031Sdim  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1599280031Sdim                    *DAG.getContext(), Call);
1600198090Srdivacky  CCInfo.AnalyzeCallOperands(Outs,
1601198090Srdivacky                             CCAssignFnForNode(CallConv, /* Return*/ false,
1602198090Srdivacky                                               isVarArg));
1603193323Sed
1604193323Sed  // Get a count of how many bytes are to be pushed on the stack.
1605193323Sed  unsigned NumBytes = CCInfo.getNextStackOffset();
1606193323Sed
1607210299Sed  // For tail calls, memory operands are available in our caller's stack.
1608251662Sdim  if (isSibCall)
1609210299Sed    NumBytes = 0;
1610210299Sed
1611193323Sed  // Adjust the stack pointer for the new arguments...
1612193323Sed  // These operations are automatically eliminated by the prolog/epilog pass
1613251662Sdim  if (!isSibCall)
1614288943Sdim    Chain = DAG.getCALLSEQ_START(Chain,
1615288943Sdim                                 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1616193323Sed
1617288943Sdim  SDValue StackPtr =
1618288943Sdim      DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1619193323Sed
1620194710Sed  RegsToPassVector RegsToPass;
1621193323Sed  SmallVector<SDValue, 8> MemOpChains;
1622193323Sed
1623193323Sed  // Walk the register/memloc assignments, inserting copies/loads.  In the case
1624193323Sed  // of tail call optimization, arguments are handled later.
1625193323Sed  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1626193323Sed       i != e;
1627193323Sed       ++i, ++realArgIdx) {
1628193323Sed    CCValAssign &VA = ArgLocs[i];
1629210299Sed    SDValue Arg = OutVals[realArgIdx];
1630198090Srdivacky    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1631221345Sdim    bool isByVal = Flags.isByVal();
1632193323Sed
1633193323Sed    // Promote the value if needed.
1634193323Sed    switch (VA.getLocInfo()) {
1635198090Srdivacky    default: llvm_unreachable("Unknown loc info!");
1636193323Sed    case CCValAssign::Full: break;
1637193323Sed    case CCValAssign::SExt:
1638193323Sed      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1639193323Sed      break;
1640193323Sed    case CCValAssign::ZExt:
1641193323Sed      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1642193323Sed      break;
1643193323Sed    case CCValAssign::AExt:
1644193323Sed      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1645193323Sed      break;
1646193323Sed    case CCValAssign::BCvt:
1647218893Sdim      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1648193323Sed      break;
1649193323Sed    }
1650193323Sed
1651198090Srdivacky    // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1652193323Sed    if (VA.needsCustom()) {
1653194710Sed      if (VA.getLocVT() == MVT::v2f64) {
1654194710Sed        SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1655288943Sdim                                  DAG.getConstant(0, dl, MVT::i32));
1656194710Sed        SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1657288943Sdim                                  DAG.getConstant(1, dl, MVT::i32));
1658193323Sed
1659198090Srdivacky        PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1660194710Sed                         VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1661194710Sed
1662194710Sed        VA = ArgLocs[++i]; // skip ahead to next loc
1663194710Sed        if (VA.isRegLoc()) {
1664198090Srdivacky          PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1665194710Sed                           VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1666194710Sed        } else {
1667194710Sed          assert(VA.isMemLoc());
1668194710Sed
1669198090Srdivacky          MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1670198090Srdivacky                                                 dl, DAG, VA, Flags));
1671194710Sed        }
1672194710Sed      } else {
1673198090Srdivacky        PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1674194710Sed                         StackPtr, MemOpChains, Flags);
1675193323Sed      }
1676193323Sed    } else if (VA.isRegLoc()) {
1677251662Sdim      if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1678251662Sdim        assert(VA.getLocVT() == MVT::i32 &&
1679251662Sdim               "unexpected calling convention register assignment");
1680251662Sdim        assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1681251662Sdim               "unexpected use of 'returned'");
1682251662Sdim        isThisReturn = true;
1683251662Sdim      }
1684193323Sed      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1685221345Sdim    } else if (isByVal) {
1686221345Sdim      assert(VA.isMemLoc());
1687221345Sdim      unsigned offset = 0;
1688221345Sdim
1689221345Sdim      // True if this byval aggregate will be split between registers
1690221345Sdim      // and memory.
1691251662Sdim      unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1692277320Sdim      unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1693251662Sdim
1694251662Sdim      if (CurByValIdx < ByValArgsCount) {
1695251662Sdim
1696251662Sdim        unsigned RegBegin, RegEnd;
1697251662Sdim        CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1698251662Sdim
1699288943Sdim        EVT PtrVT =
1700288943Sdim            DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1701221345Sdim        unsigned int i, j;
1702251662Sdim        for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1703288943Sdim          SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1704221345Sdim          SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1705221345Sdim          SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1706221345Sdim                                     MachinePointerInfo(),
1707261991Sdim                                     false, false, false,
1708261991Sdim                                     DAG.InferPtrAlignment(AddArg));
1709221345Sdim          MemOpChains.push_back(Load.getValue(1));
1710221345Sdim          RegsToPass.push_back(std::make_pair(j, Load));
1711221345Sdim        }
1712251662Sdim
1713251662Sdim        // If parameter size outsides register area, "offset" value
1714251662Sdim        // helps us to calculate stack slot for remained part properly.
1715251662Sdim        offset = RegEnd - RegBegin;
1716251662Sdim
1717251662Sdim        CCInfo.nextInRegsParam();
1718221345Sdim      }
1719221345Sdim
1720251662Sdim      if (Flags.getByValSize() > 4*offset) {
1721288943Sdim        auto PtrVT = getPointerTy(DAG.getDataLayout());
1722239462Sdim        unsigned LocMemOffset = VA.getLocMemOffset();
1723288943Sdim        SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1724288943Sdim        SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1725288943Sdim        SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1726288943Sdim        SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1727288943Sdim        SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1728239462Sdim                                           MVT::i32);
1729288943Sdim        SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1730288943Sdim                                            MVT::i32);
1731221345Sdim
1732239462Sdim        SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1733239462Sdim        SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1734239462Sdim        MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1735276479Sdim                                          Ops));
1736239462Sdim      }
1737251662Sdim    } else if (!isSibCall) {
1738193323Sed      assert(VA.isMemLoc());
1739193323Sed
1740198090Srdivacky      MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1741198090Srdivacky                                             dl, DAG, VA, Flags));
1742193323Sed    }
1743193323Sed  }
1744193323Sed
1745193323Sed  if (!MemOpChains.empty())
1746276479Sdim    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1747193323Sed
1748193323Sed  // Build a sequence of copy-to-reg nodes chained together with token chain
1749193323Sed  // and flag operands which copy the outgoing args into the appropriate regs.
1750193323Sed  SDValue InFlag;
1751210299Sed  // Tail call byval lowering might overwrite argument registers so in case of
1752210299Sed  // tail call optimization the copies to registers are lowered later.
1753210299Sed  if (!isTailCall)
1754210299Sed    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1755210299Sed      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1756210299Sed                               RegsToPass[i].second, InFlag);
1757210299Sed      InFlag = Chain.getValue(1);
1758210299Sed    }
1759210299Sed
1760210299Sed  // For tail calls lower the arguments to the 'real' stack slot.
1761210299Sed  if (isTailCall) {
1762210299Sed    // Force all the incoming stack arguments to be loaded from the stack
1763210299Sed    // before any new outgoing arguments are stored to the stack, because the
1764210299Sed    // outgoing stack slots may alias the incoming argument stack slots, and
1765210299Sed    // the alias isn't otherwise explicit. This is slightly more conservative
1766210299Sed    // than necessary, because it means that each store effectively depends
1767210299Sed    // on every argument instead of just those arguments it would clobber.
1768210299Sed
1769221345Sdim    // Do not flag preceding copytoreg stuff together with the following stuff.
1770210299Sed    InFlag = SDValue();
1771210299Sed    for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1772210299Sed      Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1773210299Sed                               RegsToPass[i].second, InFlag);
1774210299Sed      InFlag = Chain.getValue(1);
1775210299Sed    }
1776251662Sdim    InFlag = SDValue();
1777193323Sed  }
1778193323Sed
1779193323Sed  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1780193323Sed  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1781193323Sed  // node so that legalize doesn't hack it.
1782193323Sed  bool isDirect = false;
1783193323Sed  bool isARMFunc = false;
1784193323Sed  bool isLocalARMFunc = false;
1785199481Srdivacky  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1786288943Sdim  auto PtrVt = getPointerTy(DAG.getDataLayout());
1787207618Srdivacky
1788288943Sdim  if (Subtarget->genLongCalls()) {
1789276479Sdim    assert((Subtarget->isTargetWindows() ||
1790276479Sdim            getTargetMachine().getRelocationModel() == Reloc::Static) &&
1791276479Sdim           "long-calls with non-static relocation model!");
1792207618Srdivacky    // Handle a global address or an external symbol. If it's not one of
1793207618Srdivacky    // those, the target's already in a register, so we don't need to do
1794207618Srdivacky    // anything extra.
1795207618Srdivacky    if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1796207618Srdivacky      const GlobalValue *GV = G->getGlobal();
1797207618Srdivacky      // Create a constant pool entry for the callee address
1798218893Sdim      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1799226633Sdim      ARMConstantPoolValue *CPV =
1800226633Sdim        ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1801226633Sdim
1802207618Srdivacky      // Get the address of the callee into a register
1803288943Sdim      SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1804207618Srdivacky      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1805296417Sdim      Callee = DAG.getLoad(
1806296417Sdim          PtrVt, dl, DAG.getEntryNode(), CPAddr,
1807296417Sdim          MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1808296417Sdim          false, false, 0);
1809207618Srdivacky    } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1810207618Srdivacky      const char *Sym = S->getSymbol();
1811207618Srdivacky
1812207618Srdivacky      // Create a constant pool entry for the callee address
1813218893Sdim      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1814226633Sdim      ARMConstantPoolValue *CPV =
1815226633Sdim        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1816226633Sdim                                      ARMPCLabelIndex, 0);
1817207618Srdivacky      // Get the address of the callee into a register
1818288943Sdim      SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1819207618Srdivacky      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1820296417Sdim      Callee = DAG.getLoad(
1821296417Sdim          PtrVt, dl, DAG.getEntryNode(), CPAddr,
1822296417Sdim          MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1823296417Sdim          false, false, 0);
1824207618Srdivacky    }
1825207618Srdivacky  } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1826207618Srdivacky    const GlobalValue *GV = G->getGlobal();
1827193323Sed    isDirect = true;
1828288943Sdim    bool isDef = GV->isStrongDefinitionForLinker();
1829288943Sdim    bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1830193323Sed                   getTargetMachine().getRelocationModel() != Reloc::Static;
1831280031Sdim    isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1832193323Sed    // ARM call to a local ARM function is predicable.
1833288943Sdim    isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1834193323Sed    // tBX takes a register source operand.
1835276479Sdim    if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1836276479Sdim      assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1837288943Sdim      Callee = DAG.getNode(
1838288943Sdim          ARMISD::WrapperPIC, dl, PtrVt,
1839288943Sdim          DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1840288943Sdim      Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1841296417Sdim                           MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1842296417Sdim                           false, false, true, 0);
1843276479Sdim    } else if (Subtarget->isTargetCOFF()) {
1844276479Sdim      assert(Subtarget->isTargetWindows() &&
1845276479Sdim             "Windows is the only supported COFF target");
1846276479Sdim      unsigned TargetFlags = GV->hasDLLImportStorageClass()
1847276479Sdim                                 ? ARMII::MO_DLLIMPORT
1848276479Sdim                                 : ARMII::MO_NO_FLAG;
1849288943Sdim      Callee =
1850288943Sdim          DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1851276479Sdim      if (GV->hasDLLImportStorageClass())
1852288943Sdim        Callee =
1853288943Sdim            DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1854288943Sdim                        DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1855296417Sdim                        MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1856296417Sdim                        false, false, false, 0);
1857218893Sdim    } else {
1858218893Sdim      // On ELF targets for PIC code, direct calls should go through the PLT
1859218893Sdim      unsigned OpFlags = 0;
1860218893Sdim      if (Subtarget->isTargetELF() &&
1861249423Sdim          getTargetMachine().getRelocationModel() == Reloc::PIC_)
1862218893Sdim        OpFlags = ARMII::MO_PLT;
1863288943Sdim      Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1864218893Sdim    }
1865193323Sed  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1866193323Sed    isDirect = true;
1867276479Sdim    bool isStub = Subtarget->isTargetMachO() &&
1868193323Sed                  getTargetMachine().getRelocationModel() != Reloc::Static;
1869280031Sdim    isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1870193323Sed    // tBX takes a register source operand.
1871193323Sed    const char *Sym = S->getSymbol();
1872198090Srdivacky    if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1873218893Sdim      unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1874226633Sdim      ARMConstantPoolValue *CPV =
1875226633Sdim        ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1876226633Sdim                                      ARMPCLabelIndex, 4);
1877288943Sdim      SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1878193323Sed      CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1879296417Sdim      Callee = DAG.getLoad(
1880296417Sdim          PtrVt, dl, DAG.getEntryNode(), CPAddr,
1881296417Sdim          MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1882296417Sdim          false, false, 0);
1883288943Sdim      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1884288943Sdim      Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1885218893Sdim    } else {
1886218893Sdim      unsigned OpFlags = 0;
1887218893Sdim      // On ELF targets for PIC code, direct calls should go through the PLT
1888218893Sdim      if (Subtarget->isTargetELF() &&
1889218893Sdim                  getTargetMachine().getRelocationModel() == Reloc::PIC_)
1890218893Sdim        OpFlags = ARMII::MO_PLT;
1891288943Sdim      Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1892218893Sdim    }
1893193323Sed  }
1894193323Sed
1895193323Sed  // FIXME: handle tail calls differently.
1896193323Sed  unsigned CallOpc;
1897193323Sed  if (Subtarget->isThumb()) {
1898198090Srdivacky    if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1899193323Sed      CallOpc = ARMISD::CALL_NOLINK;
1900193323Sed    else
1901193323Sed      CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1902193323Sed  } else {
1903243830Sdim    if (!isDirect && !Subtarget->hasV5TOps())
1904234353Sdim      CallOpc = ARMISD::CALL_NOLINK;
1905243830Sdim    else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1906296417Sdim             // Emit regular call when code size is the priority
1907296417Sdim             !MF.getFunction()->optForMinSize())
1908234353Sdim      // "mov lr, pc; b _foo" to avoid confusing the RSP
1909234353Sdim      CallOpc = ARMISD::CALL_NOLINK;
1910234353Sdim    else
1911234353Sdim      CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1912193323Sed  }
1913193323Sed
1914193323Sed  std::vector<SDValue> Ops;
1915193323Sed  Ops.push_back(Chain);
1916193323Sed  Ops.push_back(Callee);
1917193323Sed
1918193323Sed  // Add argument registers to the end of the list so that they are known live
1919193323Sed  // into the call.
1920193323Sed  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1921193323Sed    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1922193323Sed                                  RegsToPass[i].second.getValueType()));
1923193323Sed
1924234353Sdim  // Add a register mask operand representing the call-preserved registers.
1925261991Sdim  if (!isTailCall) {
1926261991Sdim    const uint32_t *Mask;
1927288943Sdim    const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1928261991Sdim    if (isThisReturn) {
1929261991Sdim      // For 'this' returns, use the R0-preserving mask if applicable
1930288943Sdim      Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1931261991Sdim      if (!Mask) {
1932261991Sdim        // Set isThisReturn to false if the calling convention is not one that
1933261991Sdim        // allows 'returned' to be modeled in this way, so LowerCallResult does
1934261991Sdim        // not try to pass 'this' straight through
1935261991Sdim        isThisReturn = false;
1936288943Sdim        Mask = ARI->getCallPreservedMask(MF, CallConv);
1937261991Sdim      }
1938261991Sdim    } else
1939288943Sdim      Mask = ARI->getCallPreservedMask(MF, CallConv);
1940251662Sdim
1941261991Sdim    assert(Mask && "Missing call preserved mask for calling convention");
1942261991Sdim    Ops.push_back(DAG.getRegisterMask(Mask));
1943261991Sdim  }
1944234353Sdim
1945193323Sed  if (InFlag.getNode())
1946193323Sed    Ops.push_back(InFlag);
1947210299Sed
1948218893Sdim  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1949288943Sdim  if (isTailCall) {
1950288943Sdim    MF.getFrameInfo()->setHasTailCall();
1951276479Sdim    return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1952288943Sdim  }
1953210299Sed
1954193323Sed  // Returns a chain and a flag for retval copy to use.
1955276479Sdim  Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1956193323Sed  InFlag = Chain.getValue(1);
1957193323Sed
1958288943Sdim  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1959288943Sdim                             DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1960198090Srdivacky  if (!Ins.empty())
1961193323Sed    InFlag = Chain.getValue(1);
1962193323Sed
1963193323Sed  // Handle result values, copying them out of physregs into vregs that we
1964193323Sed  // return.
1965251662Sdim  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1966251662Sdim                         InVals, isThisReturn,
1967251662Sdim                         isThisReturn ? OutVals[0] : SDValue());
1968193323Sed}
1969193323Sed
1970221345Sdim/// HandleByVal - Every parameter *after* a byval parameter is passed
1971221345Sdim/// on the stack.  Remember the next parameter register to allocate,
1972221345Sdim/// and then confiscate the rest of the parameter registers to insure
1973221345Sdim/// this.
1974288943Sdimvoid ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1975288943Sdim                                    unsigned Align) const {
1976221345Sdim  assert((State->getCallOrPrologue() == Prologue ||
1977221345Sdim          State->getCallOrPrologue() == Call) &&
1978221345Sdim         "unhandled ParmContext");
1979251662Sdim
1980288943Sdim  // Byval (as with any stack) slots are always at least 4 byte aligned.
1981288943Sdim  Align = std::max(Align, 4U);
1982251662Sdim
1983288943Sdim  unsigned Reg = State->AllocateReg(GPRArgRegs);
1984288943Sdim  if (!Reg)
1985288943Sdim    return;
1986251662Sdim
1987288943Sdim  unsigned AlignInRegs = Align / 4;
1988288943Sdim  unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1989288943Sdim  for (unsigned i = 0; i < Waste; ++i)
1990288943Sdim    Reg = State->AllocateReg(GPRArgRegs);
1991288943Sdim
1992288943Sdim  if (!Reg)
1993288943Sdim    return;
1994288943Sdim
1995288943Sdim  unsigned Excess = 4 * (ARM::R4 - Reg);
1996288943Sdim
1997288943Sdim  // Special case when NSAA != SP and parameter size greater than size of
1998288943Sdim  // all remained GPR regs. In that case we can't split parameter, we must
1999288943Sdim  // send it to stack. We also must set NCRN to R4, so waste all
2000288943Sdim  // remained registers.
2001288943Sdim  const unsigned NSAAOffset = State->getNextStackOffset();
2002288943Sdim  if (NSAAOffset != 0 && Size > Excess) {
2003288943Sdim    while (State->AllocateReg(GPRArgRegs))
2004288943Sdim      ;
2005288943Sdim    return;
2006221345Sdim  }
2007288943Sdim
2008288943Sdim  // First register for byval parameter is the first register that wasn't
2009288943Sdim  // allocated before this method call, so it would be "reg".
2010288943Sdim  // If parameter is small enough to be saved in range [reg, r4), then
2011288943Sdim  // the end (first after last) register would be reg + param-size-in-regs,
2012288943Sdim  // else parameter would be splitted between registers and stack,
2013288943Sdim  // end register would be r4 in this case.
2014288943Sdim  unsigned ByValRegBegin = Reg;
2015288943Sdim  unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2016288943Sdim  State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2017288943Sdim  // Note, first register is allocated in the beginning of function already,
2018288943Sdim  // allocate remained amount of registers we need.
2019288943Sdim  for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2020288943Sdim    State->AllocateReg(GPRArgRegs);
2021288943Sdim  // A byval parameter that is split between registers and memory needs its
2022288943Sdim  // size truncated here.
2023288943Sdim  // In the case where the entire structure fits in registers, we set the
2024288943Sdim  // size in memory to zero.
2025288943Sdim  Size = std::max<int>(Size - Excess, 0);
2026221345Sdim}
2027221345Sdim
2028210299Sed/// MatchingStackOffset - Return true if the given stack call argument is
2029210299Sed/// already available in the same position (relatively) of the caller's
2030210299Sed/// incoming argument stack.
2031210299Sedstatic
2032210299Sedbool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2033210299Sed                         MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2034234353Sdim                         const TargetInstrInfo *TII) {
2035210299Sed  unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2036210299Sed  int FI = INT_MAX;
2037210299Sed  if (Arg.getOpcode() == ISD::CopyFromReg) {
2038210299Sed    unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2039218893Sdim    if (!TargetRegisterInfo::isVirtualRegister(VR))
2040210299Sed      return false;
2041210299Sed    MachineInstr *Def = MRI->getVRegDef(VR);
2042210299Sed    if (!Def)
2043210299Sed      return false;
2044210299Sed    if (!Flags.isByVal()) {
2045210299Sed      if (!TII->isLoadFromStackSlot(Def, FI))
2046210299Sed        return false;
2047210299Sed    } else {
2048210299Sed      return false;
2049210299Sed    }
2050210299Sed  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2051210299Sed    if (Flags.isByVal())
2052210299Sed      // ByVal argument is passed in as a pointer but it's now being
2053210299Sed      // dereferenced. e.g.
2054210299Sed      // define @foo(%struct.X* %A) {
2055210299Sed      //   tail call @bar(%struct.X* byval %A)
2056210299Sed      // }
2057210299Sed      return false;
2058210299Sed    SDValue Ptr = Ld->getBasePtr();
2059210299Sed    FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2060210299Sed    if (!FINode)
2061210299Sed      return false;
2062210299Sed    FI = FINode->getIndex();
2063210299Sed  } else
2064210299Sed    return false;
2065210299Sed
2066210299Sed  assert(FI != INT_MAX);
2067210299Sed  if (!MFI->isFixedObjectIndex(FI))
2068210299Sed    return false;
2069210299Sed  return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2070210299Sed}
2071210299Sed
2072210299Sed/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2073210299Sed/// for tail call optimization. Targets which want to do tail call
2074210299Sed/// optimization should implement this function.
2075210299Sedbool
2076210299SedARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2077210299Sed                                                     CallingConv::ID CalleeCC,
2078210299Sed                                                     bool isVarArg,
2079210299Sed                                                     bool isCalleeStructRet,
2080210299Sed                                                     bool isCallerStructRet,
2081210299Sed                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2082210299Sed                                    const SmallVectorImpl<SDValue> &OutVals,
2083210299Sed                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2084210299Sed                                                     SelectionDAG& DAG) const {
2085210299Sed  const Function *CallerF = DAG.getMachineFunction().getFunction();
2086210299Sed  CallingConv::ID CallerCC = CallerF->getCallingConv();
2087210299Sed  bool CCMatch = CallerCC == CalleeCC;
2088210299Sed
2089296417Sdim  assert(Subtarget->supportsTailCall());
2090296417Sdim
2091210299Sed  // Look for obvious safe cases to perform tail call optimization that do not
2092210299Sed  // require ABI changes. This is what gcc calls sibcall.
2093210299Sed
2094210299Sed  // Do not sibcall optimize vararg calls unless the call site is not passing
2095210299Sed  // any arguments.
2096210299Sed  if (isVarArg && !Outs.empty())
2097210299Sed    return false;
2098210299Sed
2099261991Sdim  // Exception-handling functions need a special set of instructions to indicate
2100261991Sdim  // a return to the hardware. Tail-calling another function would probably
2101261991Sdim  // break this.
2102261991Sdim  if (CallerF->hasFnAttribute("interrupt"))
2103261991Sdim    return false;
2104261991Sdim
2105210299Sed  // Also avoid sibcall optimization if either caller or callee uses struct
2106210299Sed  // return semantics.
2107210299Sed  if (isCalleeStructRet || isCallerStructRet)
2108210299Sed    return false;
2109210299Sed
2110280031Sdim  // Externally-defined functions with weak linkage should not be
2111280031Sdim  // tail-called on ARM when the OS does not support dynamic
2112280031Sdim  // pre-emption of symbols, as the AAELF spec requires normal calls
2113280031Sdim  // to undefined weak functions to be replaced with a NOP or jump to the
2114280031Sdim  // next instruction. The behaviour of branch instructions in this
2115280031Sdim  // situation (as used for tail calls) is implementation-defined, so we
2116280031Sdim  // cannot rely on the linker replacing the tail call with a return.
2117280031Sdim  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2118280031Sdim    const GlobalValue *GV = G->getGlobal();
2119288943Sdim    const Triple &TT = getTargetMachine().getTargetTriple();
2120280031Sdim    if (GV->hasExternalWeakLinkage() &&
2121280031Sdim        (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2122280031Sdim      return false;
2123280031Sdim  }
2124280031Sdim
2125210299Sed  // If the calling conventions do not match, then we'd better make sure the
2126210299Sed  // results are returned in the same way as what the caller expects.
2127210299Sed  if (!CCMatch) {
2128210299Sed    SmallVector<CCValAssign, 16> RVLocs1;
2129280031Sdim    ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2130280031Sdim                       *DAG.getContext(), Call);
2131210299Sed    CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2132210299Sed
2133210299Sed    SmallVector<CCValAssign, 16> RVLocs2;
2134280031Sdim    ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2135280031Sdim                       *DAG.getContext(), Call);
2136210299Sed    CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2137210299Sed
2138210299Sed    if (RVLocs1.size() != RVLocs2.size())
2139210299Sed      return false;
2140210299Sed    for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2141210299Sed      if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2142210299Sed        return false;
2143210299Sed      if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2144210299Sed        return false;
2145210299Sed      if (RVLocs1[i].isRegLoc()) {
2146210299Sed        if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2147210299Sed          return false;
2148210299Sed      } else {
2149210299Sed        if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2150210299Sed          return false;
2151210299Sed      }
2152210299Sed    }
2153210299Sed  }
2154210299Sed
2155243830Sdim  // If Caller's vararg or byval argument has been split between registers and
2156243830Sdim  // stack, do not perform tail call, since part of the argument is in caller's
2157243830Sdim  // local frame.
2158243830Sdim  const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2159243830Sdim                                      getInfo<ARMFunctionInfo>();
2160251662Sdim  if (AFI_Caller->getArgRegsSaveSize())
2161243830Sdim    return false;
2162243830Sdim
2163210299Sed  // If the callee takes no arguments then go on to check the results of the
2164210299Sed  // call.
2165210299Sed  if (!Outs.empty()) {
2166210299Sed    // Check if stack adjustment is needed. For now, do not do this if any
2167210299Sed    // argument is passed on the stack.
2168210299Sed    SmallVector<CCValAssign, 16> ArgLocs;
2169280031Sdim    ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2170280031Sdim                      *DAG.getContext(), Call);
2171210299Sed    CCInfo.AnalyzeCallOperands(Outs,
2172210299Sed                               CCAssignFnForNode(CalleeCC, false, isVarArg));
2173210299Sed    if (CCInfo.getNextStackOffset()) {
2174210299Sed      MachineFunction &MF = DAG.getMachineFunction();
2175210299Sed
2176210299Sed      // Check if the arguments are already laid out in the right way as
2177210299Sed      // the caller's fixed stack objects.
2178210299Sed      MachineFrameInfo *MFI = MF.getFrameInfo();
2179210299Sed      const MachineRegisterInfo *MRI = &MF.getRegInfo();
2180288943Sdim      const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2181210299Sed      for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2182210299Sed           i != e;
2183210299Sed           ++i, ++realArgIdx) {
2184210299Sed        CCValAssign &VA = ArgLocs[i];
2185210299Sed        EVT RegVT = VA.getLocVT();
2186210299Sed        SDValue Arg = OutVals[realArgIdx];
2187210299Sed        ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2188210299Sed        if (VA.getLocInfo() == CCValAssign::Indirect)
2189210299Sed          return false;
2190210299Sed        if (VA.needsCustom()) {
2191210299Sed          // f64 and vector types are split into multiple registers or
2192210299Sed          // register/stack-slot combinations.  The types will not match
2193210299Sed          // the registers; give up on memory f64 refs until we figure
2194210299Sed          // out what to do about this.
2195210299Sed          if (!VA.isRegLoc())
2196210299Sed            return false;
2197210299Sed          if (!ArgLocs[++i].isRegLoc())
2198218893Sdim            return false;
2199210299Sed          if (RegVT == MVT::v2f64) {
2200210299Sed            if (!ArgLocs[++i].isRegLoc())
2201210299Sed              return false;
2202210299Sed            if (!ArgLocs[++i].isRegLoc())
2203210299Sed              return false;
2204210299Sed          }
2205210299Sed        } else if (!VA.isRegLoc()) {
2206210299Sed          if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2207210299Sed                                   MFI, MRI, TII))
2208210299Sed            return false;
2209210299Sed        }
2210210299Sed      }
2211210299Sed    }
2212210299Sed  }
2213210299Sed
2214210299Sed  return true;
2215210299Sed}
2216210299Sed
2217249423Sdimbool
2218249423SdimARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2219249423Sdim                                  MachineFunction &MF, bool isVarArg,
2220249423Sdim                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
2221249423Sdim                                  LLVMContext &Context) const {
2222249423Sdim  SmallVector<CCValAssign, 16> RVLocs;
2223280031Sdim  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2224249423Sdim  return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2225249423Sdim                                                    isVarArg));
2226249423Sdim}
2227249423Sdim
2228261991Sdimstatic SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2229261991Sdim                                    SDLoc DL, SelectionDAG &DAG) {
2230261991Sdim  const MachineFunction &MF = DAG.getMachineFunction();
2231261991Sdim  const Function *F = MF.getFunction();
2232261991Sdim
2233261991Sdim  StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2234261991Sdim
2235261991Sdim  // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2236261991Sdim  // version of the "preferred return address". These offsets affect the return
2237261991Sdim  // instruction if this is a return from PL1 without hypervisor extensions.
2238261991Sdim  //    IRQ/FIQ: +4     "subs pc, lr, #4"
2239261991Sdim  //    SWI:     0      "subs pc, lr, #0"
2240261991Sdim  //    ABORT:   +4     "subs pc, lr, #4"
2241261991Sdim  //    UNDEF:   +4/+2  "subs pc, lr, #0"
2242261991Sdim  // UNDEF varies depending on where the exception came from ARM or Thumb
2243261991Sdim  // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2244261991Sdim
2245261991Sdim  int64_t LROffset;
2246261991Sdim  if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2247261991Sdim      IntKind == "ABORT")
2248261991Sdim    LROffset = 4;
2249261991Sdim  else if (IntKind == "SWI" || IntKind == "UNDEF")
2250261991Sdim    LROffset = 0;
2251261991Sdim  else
2252261991Sdim    report_fatal_error("Unsupported interrupt attribute. If present, value "
2253261991Sdim                       "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2254261991Sdim
2255288943Sdim  RetOps.insert(RetOps.begin() + 1,
2256288943Sdim                DAG.getConstant(LROffset, DL, MVT::i32, false));
2257261991Sdim
2258276479Sdim  return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2259261991Sdim}
2260261991Sdim
2261198090SrdivackySDValue
2262198090SrdivackyARMTargetLowering::LowerReturn(SDValue Chain,
2263198090Srdivacky                               CallingConv::ID CallConv, bool isVarArg,
2264198090Srdivacky                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2265210299Sed                               const SmallVectorImpl<SDValue> &OutVals,
2266261991Sdim                               SDLoc dl, SelectionDAG &DAG) const {
2267193323Sed
2268193323Sed  // CCValAssign - represent the assignment of the return value to a location.
2269193323Sed  SmallVector<CCValAssign, 16> RVLocs;
2270193323Sed
2271193323Sed  // CCState - Info about the registers and stack slots.
2272280031Sdim  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2273280031Sdim                    *DAG.getContext(), Call);
2274193323Sed
2275198090Srdivacky  // Analyze outgoing return values.
2276198090Srdivacky  CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2277198090Srdivacky                                               isVarArg));
2278193323Sed
2279193323Sed  SDValue Flag;
2280249423Sdim  SmallVector<SDValue, 4> RetOps;
2281249423Sdim  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2282276479Sdim  bool isLittleEndian = Subtarget->isLittle();
2283193323Sed
2284280031Sdim  MachineFunction &MF = DAG.getMachineFunction();
2285280031Sdim  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2286280031Sdim  AFI->setReturnRegsCount(RVLocs.size());
2287280031Sdim
2288193323Sed  // Copy the result values into the output registers.
2289193323Sed  for (unsigned i = 0, realRVLocIdx = 0;
2290193323Sed       i != RVLocs.size();
2291193323Sed       ++i, ++realRVLocIdx) {
2292193323Sed    CCValAssign &VA = RVLocs[i];
2293193323Sed    assert(VA.isRegLoc() && "Can only return in registers!");
2294193323Sed
2295210299Sed    SDValue Arg = OutVals[realRVLocIdx];
2296193323Sed
2297193323Sed    switch (VA.getLocInfo()) {
2298198090Srdivacky    default: llvm_unreachable("Unknown loc info!");
2299193323Sed    case CCValAssign::Full: break;
2300193323Sed    case CCValAssign::BCvt:
2301218893Sdim      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2302193323Sed      break;
2303193323Sed    }
2304193323Sed
2305193323Sed    if (VA.needsCustom()) {
2306194710Sed      if (VA.getLocVT() == MVT::v2f64) {
2307194710Sed        // Extract the first half and return it in two registers.
2308194710Sed        SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2309288943Sdim                                   DAG.getConstant(0, dl, MVT::i32));
2310199481Srdivacky        SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2311194710Sed                                       DAG.getVTList(MVT::i32, MVT::i32), Half);
2312194710Sed
2313276479Sdim        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2314276479Sdim                                 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2315276479Sdim                                 Flag);
2316194710Sed        Flag = Chain.getValue(1);
2317249423Sdim        RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2318194710Sed        VA = RVLocs[++i]; // skip ahead to next loc
2319194710Sed        Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2320276479Sdim                                 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2321276479Sdim                                 Flag);
2322194710Sed        Flag = Chain.getValue(1);
2323249423Sdim        RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2324194710Sed        VA = RVLocs[++i]; // skip ahead to next loc
2325194710Sed
2326194710Sed        // Extract the 2nd half and fall through to handle it as an f64 value.
2327194710Sed        Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2328288943Sdim                          DAG.getConstant(1, dl, MVT::i32));
2329194710Sed      }
2330194710Sed      // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2331194710Sed      // available.
2332199481Srdivacky      SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2333276479Sdim                                  DAG.getVTList(MVT::i32, MVT::i32), Arg);
2334276479Sdim      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2335276479Sdim                               fmrrd.getValue(isLittleEndian ? 0 : 1),
2336276479Sdim                               Flag);
2337193323Sed      Flag = Chain.getValue(1);
2338249423Sdim      RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2339193323Sed      VA = RVLocs[++i]; // skip ahead to next loc
2340276479Sdim      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2341276479Sdim                               fmrrd.getValue(isLittleEndian ? 1 : 0),
2342193323Sed                               Flag);
2343193323Sed    } else
2344193323Sed      Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2345193323Sed
2346193323Sed    // Guarantee that all emitted copies are
2347193323Sed    // stuck together, avoiding something bad.
2348193323Sed    Flag = Chain.getValue(1);
2349249423Sdim    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2350193323Sed  }
2351296417Sdim  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2352296417Sdim  const MCPhysReg *I =
2353296417Sdim      TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2354296417Sdim  if (I) {
2355296417Sdim    for (; *I; ++I) {
2356296417Sdim      if (ARM::GPRRegClass.contains(*I))
2357296417Sdim        RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2358296417Sdim      else if (ARM::DPRRegClass.contains(*I))
2359296417Sdim        RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2360296417Sdim      else
2361296417Sdim        llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2362296417Sdim    }
2363296417Sdim  }
2364193323Sed
2365249423Sdim  // Update chain and glue.
2366249423Sdim  RetOps[0] = Chain;
2367193323Sed  if (Flag.getNode())
2368249423Sdim    RetOps.push_back(Flag);
2369193323Sed
2370261991Sdim  // CPUs which aren't M-class use a special sequence to return from
2371261991Sdim  // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2372261991Sdim  // though we use "subs pc, lr, #N").
2373261991Sdim  //
2374261991Sdim  // M-class CPUs actually use a normal return sequence with a special
2375261991Sdim  // (hardware-provided) value in LR, so the normal code path works.
2376261991Sdim  if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2377261991Sdim      !Subtarget->isMClass()) {
2378261991Sdim    if (Subtarget->isThumb1Only())
2379261991Sdim      report_fatal_error("interrupt attribute is not supported in Thumb1");
2380261991Sdim    return LowerInterruptReturn(RetOps, dl, DAG);
2381261991Sdim  }
2382261991Sdim
2383276479Sdim  return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2384193323Sed}
2385193323Sed
2386234353Sdimbool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2387218893Sdim  if (N->getNumValues() != 1)
2388218893Sdim    return false;
2389218893Sdim  if (!N->hasNUsesOfValue(1, 0))
2390218893Sdim    return false;
2391218893Sdim
2392234353Sdim  SDValue TCChain = Chain;
2393234353Sdim  SDNode *Copy = *N->use_begin();
2394234353Sdim  if (Copy->getOpcode() == ISD::CopyToReg) {
2395234353Sdim    // If the copy has a glue operand, we conservatively assume it isn't safe to
2396234353Sdim    // perform a tail call.
2397234353Sdim    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2398234353Sdim      return false;
2399234353Sdim    TCChain = Copy->getOperand(0);
2400234353Sdim  } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2401234353Sdim    SDNode *VMov = Copy;
2402218893Sdim    // f64 returned in a pair of GPRs.
2403234353Sdim    SmallPtrSet<SDNode*, 2> Copies;
2404234353Sdim    for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2405218893Sdim         UI != UE; ++UI) {
2406218893Sdim      if (UI->getOpcode() != ISD::CopyToReg)
2407218893Sdim        return false;
2408234353Sdim      Copies.insert(*UI);
2409218893Sdim    }
2410234353Sdim    if (Copies.size() > 2)
2411234353Sdim      return false;
2412234353Sdim
2413234353Sdim    for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2414234353Sdim         UI != UE; ++UI) {
2415234353Sdim      SDValue UseChain = UI->getOperand(0);
2416234353Sdim      if (Copies.count(UseChain.getNode()))
2417234353Sdim        // Second CopyToReg
2418234353Sdim        Copy = *UI;
2419280031Sdim      else {
2420280031Sdim        // We are at the top of this chain.
2421280031Sdim        // If the copy has a glue operand, we conservatively assume it
2422280031Sdim        // isn't safe to perform a tail call.
2423280031Sdim        if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2424280031Sdim          return false;
2425234353Sdim        // First CopyToReg
2426234353Sdim        TCChain = UseChain;
2427280031Sdim      }
2428234353Sdim    }
2429234353Sdim  } else if (Copy->getOpcode() == ISD::BITCAST) {
2430218893Sdim    // f32 returned in a single GPR.
2431234353Sdim    if (!Copy->hasOneUse())
2432218893Sdim      return false;
2433234353Sdim    Copy = *Copy->use_begin();
2434234353Sdim    if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2435218893Sdim      return false;
2436280031Sdim    // If the copy has a glue operand, we conservatively assume it isn't safe to
2437280031Sdim    // perform a tail call.
2438280031Sdim    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2439280031Sdim      return false;
2440261991Sdim    TCChain = Copy->getOperand(0);
2441218893Sdim  } else {
2442218893Sdim    return false;
2443218893Sdim  }
2444218893Sdim
2445218893Sdim  bool HasRet = false;
2446234353Sdim  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2447234353Sdim       UI != UE; ++UI) {
2448261991Sdim    if (UI->getOpcode() != ARMISD::RET_FLAG &&
2449261991Sdim        UI->getOpcode() != ARMISD::INTRET_FLAG)
2450234353Sdim      return false;
2451234353Sdim    HasRet = true;
2452218893Sdim  }
2453218893Sdim
2454234353Sdim  if (!HasRet)
2455234353Sdim    return false;
2456234353Sdim
2457234353Sdim  Chain = TCChain;
2458234353Sdim  return true;
2459218893Sdim}
2460218893Sdim
2461221345Sdimbool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2462276479Sdim  if (!Subtarget->supportsTailCall())
2463221345Sdim    return false;
2464221345Sdim
2465288943Sdim  auto Attr =
2466288943Sdim      CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2467288943Sdim  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2468221345Sdim    return false;
2469221345Sdim
2470296417Sdim  return true;
2471221345Sdim}
2472221345Sdim
2473288943Sdim// Trying to write a 64 bit value so need to split into two 32 bit values first,
2474288943Sdim// and pass the lower and high parts through.
2475288943Sdimstatic SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2476288943Sdim  SDLoc DL(Op);
2477288943Sdim  SDValue WriteValue = Op->getOperand(2);
2478288943Sdim
2479288943Sdim  // This function is only supposed to be called for i64 type argument.
2480288943Sdim  assert(WriteValue.getValueType() == MVT::i64
2481288943Sdim          && "LowerWRITE_REGISTER called for non-i64 type argument.");
2482288943Sdim
2483288943Sdim  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2484288943Sdim                           DAG.getConstant(0, DL, MVT::i32));
2485288943Sdim  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2486288943Sdim                           DAG.getConstant(1, DL, MVT::i32));
2487288943Sdim  SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2488288943Sdim  return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2489288943Sdim}
2490288943Sdim
2491193323Sed// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2492198090Srdivacky// their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2493193323Sed// one of the above mentioned nodes. It has to be wrapped because otherwise
2494193323Sed// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2495193323Sed// be used to form addressing mode. These wrapped nodes will be selected
2496193323Sed// into MOVi.
2497193323Sedstatic SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2498198090Srdivacky  EVT PtrVT = Op.getValueType();
2499193323Sed  // FIXME there is no actual debug info here
2500261991Sdim  SDLoc dl(Op);
2501193323Sed  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2502193323Sed  SDValue Res;
2503193323Sed  if (CP->isMachineConstantPoolEntry())
2504193323Sed    Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2505193323Sed                                    CP->getAlignment());
2506193323Sed  else
2507193323Sed    Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2508193323Sed                                    CP->getAlignment());
2509193323Sed  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2510193323Sed}
2511193323Sed
2512212904Sdimunsigned ARMTargetLowering::getJumpTableEncoding() const {
2513212904Sdim  return MachineJumpTableInfo::EK_Inline;
2514212904Sdim}
2515212904Sdim
2516207618SrdivackySDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2517207618Srdivacky                                             SelectionDAG &DAG) const {
2518199481Srdivacky  MachineFunction &MF = DAG.getMachineFunction();
2519199481Srdivacky  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2520199481Srdivacky  unsigned ARMPCLabelIndex = 0;
2521261991Sdim  SDLoc DL(Op);
2522288943Sdim  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2523207618Srdivacky  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2524198892Srdivacky  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2525198892Srdivacky  SDValue CPAddr;
2526198892Srdivacky  if (RelocM == Reloc::Static) {
2527198892Srdivacky    CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2528198892Srdivacky  } else {
2529198892Srdivacky    unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2530218893Sdim    ARMPCLabelIndex = AFI->createPICLabelUId();
2531226633Sdim    ARMConstantPoolValue *CPV =
2532226633Sdim      ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2533226633Sdim                                      ARMCP::CPBlockAddress, PCAdj);
2534198892Srdivacky    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2535198892Srdivacky  }
2536198892Srdivacky  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2537296417Sdim  SDValue Result =
2538296417Sdim      DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2539296417Sdim                  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2540296417Sdim                  false, false, false, 0);
2541198892Srdivacky  if (RelocM == Reloc::Static)
2542198892Srdivacky    return Result;
2543288943Sdim  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2544198892Srdivacky  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2545198892Srdivacky}
2546198892Srdivacky
2547296417Sdim/// \brief Convert a TLS address reference into the correct sequence of loads
2548296417Sdim/// and calls to compute the variable's address for Darwin, and return an
2549296417Sdim/// SDValue containing the final node.
2550296417Sdim
2551296417Sdim/// Darwin only has one TLS scheme which must be capable of dealing with the
2552296417Sdim/// fully general situation, in the worst case. This means:
2553296417Sdim///     + "extern __thread" declaration.
2554296417Sdim///     + Defined in a possibly unknown dynamic library.
2555296417Sdim///
2556296417Sdim/// The general system is that each __thread variable has a [3 x i32] descriptor
2557296417Sdim/// which contains information used by the runtime to calculate the address. The
2558296417Sdim/// only part of this the compiler needs to know about is the first word, which
2559296417Sdim/// contains a function pointer that must be called with the address of the
2560296417Sdim/// entire descriptor in "r0".
2561296417Sdim///
2562296417Sdim/// Since this descriptor may be in a different unit, in general access must
2563296417Sdim/// proceed along the usual ARM rules. A common sequence to produce is:
2564296417Sdim///
2565296417Sdim///     movw rT1, :lower16:_var$non_lazy_ptr
2566296417Sdim///     movt rT1, :upper16:_var$non_lazy_ptr
2567296417Sdim///     ldr r0, [rT1]
2568296417Sdim///     ldr rT2, [r0]
2569296417Sdim///     blx rT2
2570296417Sdim///     [...address now in r0...]
2571296417SdimSDValue
2572296417SdimARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2573296417Sdim                                               SelectionDAG &DAG) const {
2574296417Sdim  assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2575296417Sdim  SDLoc DL(Op);
2576296417Sdim
2577296417Sdim  // First step is to get the address of the actua global symbol. This is where
2578296417Sdim  // the TLS descriptor lives.
2579296417Sdim  SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2580296417Sdim
2581296417Sdim  // The first entry in the descriptor is a function pointer that we must call
2582296417Sdim  // to obtain the address of the variable.
2583296417Sdim  SDValue Chain = DAG.getEntryNode();
2584296417Sdim  SDValue FuncTLVGet =
2585296417Sdim      DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2586296417Sdim                  MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2587296417Sdim                  false, true, true, 4);
2588296417Sdim  Chain = FuncTLVGet.getValue(1);
2589296417Sdim
2590296417Sdim  MachineFunction &F = DAG.getMachineFunction();
2591296417Sdim  MachineFrameInfo *MFI = F.getFrameInfo();
2592296417Sdim  MFI->setAdjustsStack(true);
2593296417Sdim
2594296417Sdim  // TLS calls preserve all registers except those that absolutely must be
2595296417Sdim  // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2596296417Sdim  // silly).
2597296417Sdim  auto TRI =
2598296417Sdim      getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2599296417Sdim  auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2600296417Sdim  const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2601296417Sdim
2602296417Sdim  // Finally, we can make the call. This is just a degenerate version of a
2603296417Sdim  // normal AArch64 call node: r0 takes the address of the descriptor, and
2604296417Sdim  // returns the address of the variable in this thread.
2605296417Sdim  Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2606296417Sdim  Chain =
2607296417Sdim      DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2608296417Sdim                  Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2609296417Sdim                  DAG.getRegisterMask(Mask), Chain.getValue(1));
2610296417Sdim  return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2611296417Sdim}
2612296417Sdim
2613193323Sed// Lower ISD::GlobalTLSAddress using the "general dynamic" model
2614193323SedSDValue
2615193323SedARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2616207618Srdivacky                                                 SelectionDAG &DAG) const {
2617261991Sdim  SDLoc dl(GA);
2618288943Sdim  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2619193323Sed  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2620199481Srdivacky  MachineFunction &MF = DAG.getMachineFunction();
2621199481Srdivacky  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2622218893Sdim  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2623193323Sed  ARMConstantPoolValue *CPV =
2624226633Sdim    ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2625226633Sdim                                    ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2626193323Sed  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2627193323Sed  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2628296417Sdim  Argument =
2629296417Sdim      DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2630296417Sdim                  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2631296417Sdim                  false, false, false, 0);
2632193323Sed  SDValue Chain = Argument.getValue(1);
2633193323Sed
2634288943Sdim  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2635193323Sed  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2636193323Sed
2637193323Sed  // call __tls_get_addr.
2638193323Sed  ArgListTy Args;
2639193323Sed  ArgListEntry Entry;
2640193323Sed  Entry.Node = Argument;
2641226633Sdim  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2642193323Sed  Args.push_back(Entry);
2643276479Sdim
2644193323Sed  // FIXME: is there useful debug info available here?
2645276479Sdim  TargetLowering::CallLoweringInfo CLI(DAG);
2646276479Sdim  CLI.setDebugLoc(dl).setChain(Chain)
2647276479Sdim    .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2648276479Sdim               DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2649276479Sdim               0);
2650276479Sdim
2651239462Sdim  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2652193323Sed  return CallResult.first;
2653193323Sed}
2654193323Sed
2655193323Sed// Lower ISD::GlobalTLSAddress using the "initial exec" or
2656193323Sed// "local exec" model.
2657193323SedSDValue
2658193323SedARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2659239462Sdim                                        SelectionDAG &DAG,
2660239462Sdim                                        TLSModel::Model model) const {
2661207618Srdivacky  const GlobalValue *GV = GA->getGlobal();
2662261991Sdim  SDLoc dl(GA);
2663193323Sed  SDValue Offset;
2664193323Sed  SDValue Chain = DAG.getEntryNode();
2665288943Sdim  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2666193323Sed  // Get the Thread Pointer
2667193323Sed  SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2668193323Sed
2669239462Sdim  if (model == TLSModel::InitialExec) {
2670199481Srdivacky    MachineFunction &MF = DAG.getMachineFunction();
2671199481Srdivacky    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2672218893Sdim    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2673199481Srdivacky    // Initial exec model.
2674193323Sed    unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2675193323Sed    ARMConstantPoolValue *CPV =
2676226633Sdim      ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2677226633Sdim                                      ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2678226633Sdim                                      true);
2679193323Sed    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2680193323Sed    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2681296417Sdim    Offset = DAG.getLoad(
2682296417Sdim        PtrVT, dl, Chain, Offset,
2683296417Sdim        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2684296417Sdim        false, false, 0);
2685193323Sed    Chain = Offset.getValue(1);
2686193323Sed
2687288943Sdim    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2688193323Sed    Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2689193323Sed
2690296417Sdim    Offset = DAG.getLoad(
2691296417Sdim        PtrVT, dl, Chain, Offset,
2692296417Sdim        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2693296417Sdim        false, false, 0);
2694193323Sed  } else {
2695193323Sed    // local exec model
2696239462Sdim    assert(model == TLSModel::LocalExec);
2697226633Sdim    ARMConstantPoolValue *CPV =
2698226633Sdim      ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2699193323Sed    Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700193323Sed    Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2701296417Sdim    Offset = DAG.getLoad(
2702296417Sdim        PtrVT, dl, Chain, Offset,
2703296417Sdim        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2704296417Sdim        false, false, 0);
2705193323Sed  }
2706193323Sed
2707193323Sed  // The address of the thread local variable is the add of the thread
2708193323Sed  // pointer with the offset of the variable.
2709193323Sed  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2710193323Sed}
2711193323Sed
2712193323SedSDValue
2713207618SrdivackyARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2714296417Sdim  if (Subtarget->isTargetDarwin())
2715296417Sdim    return LowerGlobalTLSAddressDarwin(Op, DAG);
2716296417Sdim
2717193323Sed  // TODO: implement the "local dynamic" model
2718296417Sdim  assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2719193323Sed  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2720296417Sdim  if (DAG.getTarget().Options.EmulatedTLS)
2721296417Sdim    return LowerToTLSEmulatedModel(GA, DAG);
2722239462Sdim
2723239462Sdim  TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2724239462Sdim
2725239462Sdim  switch (model) {
2726239462Sdim    case TLSModel::GeneralDynamic:
2727239462Sdim    case TLSModel::LocalDynamic:
2728239462Sdim      return LowerToTLSGeneralDynamicModel(GA, DAG);
2729239462Sdim    case TLSModel::InitialExec:
2730239462Sdim    case TLSModel::LocalExec:
2731239462Sdim      return LowerToTLSExecModels(GA, DAG, model);
2732239462Sdim  }
2733239462Sdim  llvm_unreachable("bogus TLS model");
2734193323Sed}
2735193323Sed
2736193323SedSDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2737207618Srdivacky                                                 SelectionDAG &DAG) const {
2738288943Sdim  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2739261991Sdim  SDLoc dl(Op);
2740207618Srdivacky  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2741249423Sdim  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2742296417Sdim    bool UseGOT_PREL =
2743296417Sdim        !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2744296417Sdim
2745296417Sdim    MachineFunction &MF = DAG.getMachineFunction();
2746296417Sdim    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2747296417Sdim    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2748296417Sdim    EVT PtrVT = getPointerTy(DAG.getDataLayout());
2749296417Sdim    SDLoc dl(Op);
2750296417Sdim    unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2751296417Sdim    ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2752296417Sdim        GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2753296417Sdim        UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2754296417Sdim        /*AddCurrentAddress=*/UseGOT_PREL);
2755193323Sed    SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2756193323Sed    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2757296417Sdim    SDValue Result = DAG.getLoad(
2758296417Sdim        PtrVT, dl, DAG.getEntryNode(), CPAddr,
2759296417Sdim        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2760296417Sdim        false, false, 0);
2761193323Sed    SDValue Chain = Result.getValue(1);
2762296417Sdim    SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2763296417Sdim    Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2764296417Sdim    if (UseGOT_PREL)
2765198090Srdivacky      Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2766296417Sdim                           MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2767234353Sdim                           false, false, false, 0);
2768193323Sed    return Result;
2769218893Sdim  }
2770218893Sdim
2771218893Sdim  // If we have T2 ops, we can materialize the address directly via movt/movw
2772218893Sdim  // pair. This is always cheaper.
2773276479Sdim  if (Subtarget->useMovt(DAG.getMachineFunction())) {
2774218893Sdim    ++NumMovwMovt;
2775218893Sdim    // FIXME: Once remat is capable of dealing with instructions with register
2776218893Sdim    // operands, expand this into two nodes.
2777218893Sdim    return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2778218893Sdim                       DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2779193323Sed  } else {
2780218893Sdim    SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2781218893Sdim    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2782296417Sdim    return DAG.getLoad(
2783296417Sdim        PtrVT, dl, DAG.getEntryNode(), CPAddr,
2784296417Sdim        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2785296417Sdim        false, false, 0);
2786193323Sed  }
2787193323Sed}
2788193323Sed
2789193323SedSDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2790207618Srdivacky                                                    SelectionDAG &DAG) const {
2791288943Sdim  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2792261991Sdim  SDLoc dl(Op);
2793207618Srdivacky  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2794193323Sed  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2795218893Sdim
2796276479Sdim  if (Subtarget->useMovt(DAG.getMachineFunction()))
2797218893Sdim    ++NumMovwMovt;
2798218893Sdim
2799276479Sdim  // FIXME: Once remat is capable of dealing with instructions with register
2800276479Sdim  // operands, expand this into multiple nodes
2801276479Sdim  unsigned Wrapper =
2802276479Sdim      RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2803218893Sdim
2804276479Sdim  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2805276479Sdim  SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2806193323Sed
2807276479Sdim  if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2808276479Sdim    Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2809296417Sdim                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2810296417Sdim                         false, false, false, 0);
2811276479Sdim  return Result;
2812276479Sdim}
2813193323Sed
2814276479SdimSDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2815276479Sdim                                                     SelectionDAG &DAG) const {
2816276479Sdim  assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2817276479Sdim  assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2818276479Sdim         "Windows on ARM expects to use movw/movt");
2819198090Srdivacky
2820276479Sdim  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2821276479Sdim  const ARMII::TOF TargetFlags =
2822276479Sdim    (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2823288943Sdim  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2824276479Sdim  SDValue Result;
2825276479Sdim  SDLoc DL(Op);
2826193323Sed
2827276479Sdim  ++NumMovwMovt;
2828276479Sdim
2829276479Sdim  // FIXME: Once remat is capable of dealing with instructions with register
2830276479Sdim  // operands, expand this into two nodes.
2831276479Sdim  Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2832276479Sdim                       DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2833276479Sdim                                                  TargetFlags));
2834276479Sdim  if (GV->hasDLLImportStorageClass())
2835276479Sdim    Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2836296417Sdim                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2837296417Sdim                         false, false, false, 0);
2838193323Sed  return Result;
2839193323Sed}
2840193323Sed
2841193323SedSDValue
2842208599SrdivackyARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2843261991Sdim  SDLoc dl(Op);
2844288943Sdim  SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2845226633Sdim  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2846226633Sdim                     DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2847208599Srdivacky                     Op.getOperand(1), Val);
2848208599Srdivacky}
2849208599Srdivacky
2850208599SrdivackySDValue
2851208599SrdivackyARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2852261991Sdim  SDLoc dl(Op);
2853208599Srdivacky  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2854288943Sdim                     Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2855208599Srdivacky}
2856208599Srdivacky
2857296417SdimSDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2858296417Sdim                                                      SelectionDAG &DAG) const {
2859296417Sdim  SDLoc dl(Op);
2860296417Sdim  return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2861296417Sdim                     Op.getOperand(0));
2862296417Sdim}
2863296417Sdim
2864208599SrdivackySDValue
2865203954SrdivackyARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2866210299Sed                                          const ARMSubtarget *Subtarget) const {
2867193323Sed  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2868261991Sdim  SDLoc dl(Op);
2869193323Sed  switch (IntNo) {
2870193323Sed  default: return SDValue();    // Don't custom lower most intrinsics.
2871276479Sdim  case Intrinsic::arm_rbit: {
2872276479Sdim    assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2873276479Sdim           "RBIT intrinsic must have i32 type!");
2874296417Sdim    return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2875276479Sdim  }
2876198090Srdivacky  case Intrinsic::arm_thread_pointer: {
2877288943Sdim    EVT PtrVT = getPointerTy(DAG.getDataLayout());
2878198090Srdivacky    return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2879198090Srdivacky  }
2880198090Srdivacky  case Intrinsic::eh_sjlj_lsda: {
2881198090Srdivacky    MachineFunction &MF = DAG.getMachineFunction();
2882199481Srdivacky    ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2883218893Sdim    unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2884288943Sdim    EVT PtrVT = getPointerTy(DAG.getDataLayout());
2885198090Srdivacky    Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2886198090Srdivacky    SDValue CPAddr;
2887198090Srdivacky    unsigned PCAdj = (RelocM != Reloc::PIC_)
2888198090Srdivacky      ? 0 : (Subtarget->isThumb() ? 4 : 8);
2889198090Srdivacky    ARMConstantPoolValue *CPV =
2890226633Sdim      ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2891226633Sdim                                      ARMCP::CPLSDA, PCAdj);
2892198090Srdivacky    CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2893198090Srdivacky    CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2894296417Sdim    SDValue Result = DAG.getLoad(
2895296417Sdim        PtrVT, dl, DAG.getEntryNode(), CPAddr,
2896296417Sdim        MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2897296417Sdim        false, false, 0);
2898198090Srdivacky
2899198090Srdivacky    if (RelocM == Reloc::PIC_) {
2900288943Sdim      SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2901198090Srdivacky      Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2902198090Srdivacky    }
2903198090Srdivacky    return Result;
2904198090Srdivacky  }
2905221345Sdim  case Intrinsic::arm_neon_vmulls:
2906221345Sdim  case Intrinsic::arm_neon_vmullu: {
2907221345Sdim    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2908221345Sdim      ? ARMISD::VMULLs : ARMISD::VMULLu;
2909261991Sdim    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2910221345Sdim                       Op.getOperand(1), Op.getOperand(2));
2911193323Sed  }
2912296417Sdim  case Intrinsic::arm_neon_vminnm:
2913296417Sdim  case Intrinsic::arm_neon_vmaxnm: {
2914296417Sdim    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2915296417Sdim      ? ISD::FMINNUM : ISD::FMAXNUM;
2916296417Sdim    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2917296417Sdim                       Op.getOperand(1), Op.getOperand(2));
2918221345Sdim  }
2919296417Sdim  case Intrinsic::arm_neon_vminu:
2920296417Sdim  case Intrinsic::arm_neon_vmaxu: {
2921296417Sdim    if (Op.getValueType().isFloatingPoint())
2922296417Sdim      return SDValue();
2923296417Sdim    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2924296417Sdim      ? ISD::UMIN : ISD::UMAX;
2925296417Sdim    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2926296417Sdim                         Op.getOperand(1), Op.getOperand(2));
2927296417Sdim  }
2928296417Sdim  case Intrinsic::arm_neon_vmins:
2929296417Sdim  case Intrinsic::arm_neon_vmaxs: {
2930296417Sdim    // v{min,max}s is overloaded between signed integers and floats.
2931296417Sdim    if (!Op.getValueType().isFloatingPoint()) {
2932296417Sdim      unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2933296417Sdim        ? ISD::SMIN : ISD::SMAX;
2934296417Sdim      return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2935296417Sdim                         Op.getOperand(1), Op.getOperand(2));
2936296417Sdim    }
2937296417Sdim    unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2938296417Sdim      ? ISD::FMINNAN : ISD::FMAXNAN;
2939296417Sdim    return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2940296417Sdim                       Op.getOperand(1), Op.getOperand(2));
2941296417Sdim  }
2942296417Sdim  }
2943193323Sed}
2944193323Sed
2945226633Sdimstatic SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2946226633Sdim                                 const ARMSubtarget *Subtarget) {
2947226633Sdim  // FIXME: handle "fence singlethread" more efficiently.
2948261991Sdim  SDLoc dl(Op);
2949226633Sdim  if (!Subtarget->hasDataBarrier()) {
2950226633Sdim    // Some ARMv6 cpus can support data barriers with an mcr instruction.
2951226633Sdim    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2952226633Sdim    // here.
2953226633Sdim    assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2954261991Sdim           "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2955226633Sdim    return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2956288943Sdim                       DAG.getConstant(0, dl, MVT::i32));
2957226633Sdim  }
2958226633Sdim
2959261991Sdim  ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2960261991Sdim  AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2961280031Sdim  ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2962261991Sdim  if (Subtarget->isMClass()) {
2963261991Sdim    // Only a full system barrier exists in the M-class architectures.
2964261991Sdim    Domain = ARM_MB::SY;
2965261991Sdim  } else if (Subtarget->isSwift() && Ord == Release) {
2966261991Sdim    // Swift happens to implement ISHST barriers in a way that's compatible with
2967261991Sdim    // Release semantics but weaker than ISH so we'd be fools not to use
2968261991Sdim    // it. Beware: other processors probably don't!
2969261991Sdim    Domain = ARM_MB::ISHST;
2970261991Sdim  }
2971261991Sdim
2972261991Sdim  return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2973288943Sdim                     DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2974288943Sdim                     DAG.getConstant(Domain, dl, MVT::i32));
2975226633Sdim}
2976226633Sdim
2977218893Sdimstatic SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2978218893Sdim                             const ARMSubtarget *Subtarget) {
2979218893Sdim  // ARM pre v5TE and Thumb1 does not have preload instructions.
2980218893Sdim  if (!(Subtarget->isThumb2() ||
2981218893Sdim        (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2982218893Sdim    // Just preserve the chain.
2983218893Sdim    return Op.getOperand(0);
2984218893Sdim
2985261991Sdim  SDLoc dl(Op);
2986218893Sdim  unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2987218893Sdim  if (!isRead &&
2988218893Sdim      (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2989218893Sdim    // ARMv7 with MP extension has PLDW.
2990218893Sdim    return Op.getOperand(0);
2991218893Sdim
2992224145Sdim  unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2993224145Sdim  if (Subtarget->isThumb()) {
2994218893Sdim    // Invert the bits.
2995218893Sdim    isRead = ~isRead & 1;
2996224145Sdim    isData = ~isData & 1;
2997224145Sdim  }
2998218893Sdim
2999218893Sdim  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3000288943Sdim                     Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3001288943Sdim                     DAG.getConstant(isData, dl, MVT::i32));
3002218893Sdim}
3003218893Sdim
3004207618Srdivackystatic SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3005207618Srdivacky  MachineFunction &MF = DAG.getMachineFunction();
3006207618Srdivacky  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3007207618Srdivacky
3008193323Sed  // vastart just stores the address of the VarArgsFrameIndex slot into the
3009193323Sed  // memory location argument.
3010261991Sdim  SDLoc dl(Op);
3011288943Sdim  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3012207618Srdivacky  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3013193323Sed  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3014218893Sdim  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3015218893Sdim                      MachinePointerInfo(SV), false, false, 0);
3016193323Sed}
3017193323Sed
3018193323SedSDValue
3019194710SedARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
3020194710Sed                                        SDValue &Root, SelectionDAG &DAG,
3021261991Sdim                                        SDLoc dl) const {
3022194710Sed  MachineFunction &MF = DAG.getMachineFunction();
3023194710Sed  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3024194710Sed
3025234353Sdim  const TargetRegisterClass *RC;
3026198090Srdivacky  if (AFI->isThumb1OnlyFunction())
3027239462Sdim    RC = &ARM::tGPRRegClass;
3028194710Sed  else
3029239462Sdim    RC = &ARM::GPRRegClass;
3030194710Sed
3031194710Sed  // Transform the arguments stored in physical registers into virtual ones.
3032219077Sdim  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3033194710Sed  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3034194710Sed
3035194710Sed  SDValue ArgValue2;
3036194710Sed  if (NextVA.isMemLoc()) {
3037194710Sed    MachineFrameInfo *MFI = MF.getFrameInfo();
3038210299Sed    int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3039194710Sed
3040194710Sed    // Create load node to retrieve arguments from the stack.
3041288943Sdim    SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3042296417Sdim    ArgValue2 = DAG.getLoad(
3043296417Sdim        MVT::i32, dl, Root, FIN,
3044296417Sdim        MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3045296417Sdim        false, false, 0);
3046194710Sed  } else {
3047219077Sdim    Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3048194710Sed    ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3049194710Sed  }
3050276479Sdim  if (!Subtarget->isLittle())
3051276479Sdim    std::swap (ArgValue, ArgValue2);
3052199481Srdivacky  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3053194710Sed}
3054194710Sed
3055221345Sdim// The remaining GPRs hold either the beginning of variable-argument
3056249423Sdim// data, or the beginning of an aggregate passed by value (usually
3057221345Sdim// byval).  Either way, we allocate stack slots adjacent to the data
3058221345Sdim// provided by our caller, and store the unallocated registers there.
3059221345Sdim// If this is a variadic function, the va_list pointer will begin with
3060221345Sdim// these values; otherwise, this reassembles a (byval) structure that
3061221345Sdim// was split between registers and memory.
3062251662Sdim// Return: The frame index registers were stored into.
3063251662Sdimint
3064251662SdimARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3065261991Sdim                                  SDLoc dl, SDValue &Chain,
3066251662Sdim                                  const Value *OrigArg,
3067251662Sdim                                  unsigned InRegsParamRecordIdx,
3068288943Sdim                                  int ArgOffset,
3069288943Sdim                                  unsigned ArgSize) const {
3070251662Sdim  // Currently, two use-cases possible:
3071276479Sdim  // Case #1. Non-var-args function, and we meet first byval parameter.
3072251662Sdim  //          Setup first unallocated register as first byval register;
3073251662Sdim  //          eat all remained registers
3074251662Sdim  //          (these two actions are performed by HandleByVal method).
3075251662Sdim  //          Then, here, we initialize stack frame with
3076251662Sdim  //          "store-reg" instructions.
3077251662Sdim  // Case #2. Var-args function, that doesn't contain byval parameters.
3078251662Sdim  //          The same: eat all remained unallocated registers,
3079251662Sdim  //          initialize stack frame.
3080251662Sdim
3081221345Sdim  MachineFunction &MF = DAG.getMachineFunction();
3082221345Sdim  MachineFrameInfo *MFI = MF.getFrameInfo();
3083221345Sdim  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3084251662Sdim  unsigned RBegin, REnd;
3085251662Sdim  if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3086251662Sdim    CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3087251662Sdim  } else {
3088288943Sdim    unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3089288943Sdim    RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3090288943Sdim    REnd = ARM::R4;
3091221345Sdim  }
3092221345Sdim
3093288943Sdim  if (REnd != RBegin)
3094288943Sdim    ArgOffset = -4 * (ARM::R4 - RBegin);
3095221345Sdim
3096288943Sdim  auto PtrVT = getPointerTy(DAG.getDataLayout());
3097288943Sdim  int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3098288943Sdim  SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3099261991Sdim
3100288943Sdim  SmallVector<SDValue, 4> MemOps;
3101288943Sdim  const TargetRegisterClass *RC =
3102288943Sdim      AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3103261991Sdim
3104288943Sdim  for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3105288943Sdim    unsigned VReg = MF.addLiveIn(Reg, RC);
3106288943Sdim    SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3107288943Sdim    SDValue Store =
3108221345Sdim        DAG.getStore(Val.getValue(1), dl, Val, FIN,
3109288943Sdim                     MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3110288943Sdim    MemOps.push_back(Store);
3111288943Sdim    FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3112288943Sdim  }
3113251662Sdim
3114288943Sdim  if (!MemOps.empty())
3115288943Sdim    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3116288943Sdim  return FrameIndex;
3117221345Sdim}
3118221345Sdim
3119251662Sdim// Setup stack frame, the va_list pointer will start from.
3120251662Sdimvoid
3121251662SdimARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3122261991Sdim                                        SDLoc dl, SDValue &Chain,
3123251662Sdim                                        unsigned ArgOffset,
3124276479Sdim                                        unsigned TotalArgRegsSaveSize,
3125251662Sdim                                        bool ForceMutable) const {
3126251662Sdim  MachineFunction &MF = DAG.getMachineFunction();
3127251662Sdim  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3128251662Sdim
3129251662Sdim  // Try to store any remaining integer argument regs
3130251662Sdim  // to their spots on the stack so that they may be loaded by deferencing
3131251662Sdim  // the result of va_next.
3132251662Sdim  // If there is no regs to be stored, just point address after last
3133251662Sdim  // argument passed via stack.
3134288943Sdim  int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3135288943Sdim                                  CCInfo.getInRegsParamsCount(),
3136288943Sdim                                  CCInfo.getNextStackOffset(), 4);
3137251662Sdim  AFI->setVarArgsFrameIndex(FrameIndex);
3138251662Sdim}
3139251662Sdim
3140194710SedSDValue
3141198090SrdivackyARMTargetLowering::LowerFormalArguments(SDValue Chain,
3142198090Srdivacky                                        CallingConv::ID CallConv, bool isVarArg,
3143198090Srdivacky                                        const SmallVectorImpl<ISD::InputArg>
3144198090Srdivacky                                          &Ins,
3145261991Sdim                                        SDLoc dl, SelectionDAG &DAG,
3146207618Srdivacky                                        SmallVectorImpl<SDValue> &InVals)
3147207618Srdivacky                                          const {
3148193323Sed  MachineFunction &MF = DAG.getMachineFunction();
3149193323Sed  MachineFrameInfo *MFI = MF.getFrameInfo();
3150193323Sed
3151193323Sed  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3152193323Sed
3153193323Sed  // Assign locations to all of the incoming arguments.
3154193323Sed  SmallVector<CCValAssign, 16> ArgLocs;
3155280031Sdim  ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3156280031Sdim                    *DAG.getContext(), Prologue);
3157198090Srdivacky  CCInfo.AnalyzeFormalArguments(Ins,
3158198090Srdivacky                                CCAssignFnForNode(CallConv, /* Return*/ false,
3159198090Srdivacky                                                  isVarArg));
3160249423Sdim
3161193323Sed  SmallVector<SDValue, 16> ArgValues;
3162221345Sdim  SDValue ArgValue;
3163243830Sdim  Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3164243830Sdim  unsigned CurArgIdx = 0;
3165251662Sdim
3166251662Sdim  // Initially ArgRegsSaveSize is zero.
3167251662Sdim  // Then we increase this value each time we meet byval parameter.
3168251662Sdim  // We also increase this value in case of varargs function.
3169251662Sdim  AFI->setArgRegsSaveSize(0);
3170251662Sdim
3171276479Sdim  // Calculate the amount of stack space that we need to allocate to store
3172276479Sdim  // byval and variadic arguments that are passed in registers.
3173276479Sdim  // We need to know this before we allocate the first byval or variadic
3174276479Sdim  // argument, as they will be allocated a stack slot below the CFA (Canonical
3175276479Sdim  // Frame Address, the stack pointer at entry to the function).
3176288943Sdim  unsigned ArgRegBegin = ARM::R4;
3177193323Sed  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3178288943Sdim    if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3179288943Sdim      break;
3180288943Sdim
3181193323Sed    CCValAssign &VA = ArgLocs[i];
3182288943Sdim    unsigned Index = VA.getValNo();
3183288943Sdim    ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3184288943Sdim    if (!Flags.isByVal())
3185288943Sdim      continue;
3186276479Sdim
3187288943Sdim    assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3188288943Sdim    unsigned RBegin, REnd;
3189288943Sdim    CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3190288943Sdim    ArgRegBegin = std::min(ArgRegBegin, RBegin);
3191288943Sdim
3192288943Sdim    CCInfo.nextInRegsParam();
3193276479Sdim  }
3194276479Sdim  CCInfo.rewindByValRegsInfo();
3195288943Sdim
3196288943Sdim  int lastInsIndex = -1;
3197280031Sdim  if (isVarArg && MFI->hasVAStart()) {
3198288943Sdim    unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3199288943Sdim    if (RegIdx != array_lengthof(GPRArgRegs))
3200288943Sdim      ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3201276479Sdim  }
3202276479Sdim
3203288943Sdim  unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3204288943Sdim  AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3205288943Sdim  auto PtrVT = getPointerTy(DAG.getDataLayout());
3206288943Sdim
3207276479Sdim  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3208276479Sdim    CCValAssign &VA = ArgLocs[i];
3209283526Sdim    if (Ins[VA.getValNo()].isOrigArg()) {
3210283526Sdim      std::advance(CurOrigArg,
3211283526Sdim                   Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3212283526Sdim      CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3213283526Sdim    }
3214193323Sed    // Arguments stored in registers.
3215193323Sed    if (VA.isRegLoc()) {
3216198090Srdivacky      EVT RegVT = VA.getLocVT();
3217193323Sed
3218194710Sed      if (VA.needsCustom()) {
3219194710Sed        // f64 and vector types are split up into multiple registers or
3220194710Sed        // combinations of registers and stack slots.
3221194710Sed        if (VA.getLocVT() == MVT::v2f64) {
3222194710Sed          SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3223198090Srdivacky                                                   Chain, DAG, dl);
3224194710Sed          VA = ArgLocs[++i]; // skip ahead to next loc
3225207618Srdivacky          SDValue ArgValue2;
3226207618Srdivacky          if (VA.isMemLoc()) {
3227210299Sed            int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3228288943Sdim            SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3229296417Sdim            ArgValue2 = DAG.getLoad(
3230296417Sdim                MVT::f64, dl, Chain, FIN,
3231296417Sdim                MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3232296417Sdim                false, false, false, 0);
3233207618Srdivacky          } else {
3234207618Srdivacky            ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3235207618Srdivacky                                             Chain, DAG, dl);
3236207618Srdivacky          }
3237194710Sed          ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3238194710Sed          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3239288943Sdim                                 ArgValue, ArgValue1,
3240288943Sdim                                 DAG.getIntPtrConstant(0, dl));
3241194710Sed          ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3242288943Sdim                                 ArgValue, ArgValue2,
3243288943Sdim                                 DAG.getIntPtrConstant(1, dl));
3244194710Sed        } else
3245198090Srdivacky          ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3246193323Sed
3247194710Sed      } else {
3248234353Sdim        const TargetRegisterClass *RC;
3249198090Srdivacky
3250198090Srdivacky        if (RegVT == MVT::f32)
3251239462Sdim          RC = &ARM::SPRRegClass;
3252198090Srdivacky        else if (RegVT == MVT::f64)
3253239462Sdim          RC = &ARM::DPRRegClass;
3254198090Srdivacky        else if (RegVT == MVT::v2f64)
3255239462Sdim          RC = &ARM::QPRRegClass;
3256198090Srdivacky        else if (RegVT == MVT::i32)
3257280031Sdim          RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3258280031Sdim                                           : &ARM::GPRRegClass;
3259194710Sed        else
3260198090Srdivacky          llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3261193323Sed
3262194710Sed        // Transform the arguments in physical registers into virtual ones.
3263219077Sdim        unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3264198090Srdivacky        ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3265193323Sed      }
3266193323Sed
3267193323Sed      // If this is an 8 or 16-bit value, it is really passed promoted
3268193323Sed      // to 32 bits.  Insert an assert[sz]ext to capture this, then
3269193323Sed      // truncate to the right size.
3270193323Sed      switch (VA.getLocInfo()) {
3271198090Srdivacky      default: llvm_unreachable("Unknown loc info!");
3272193323Sed      case CCValAssign::Full: break;
3273193323Sed      case CCValAssign::BCvt:
3274218893Sdim        ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3275193323Sed        break;
3276193323Sed      case CCValAssign::SExt:
3277193323Sed        ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3278193323Sed                               DAG.getValueType(VA.getValVT()));
3279193323Sed        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3280193323Sed        break;
3281193323Sed      case CCValAssign::ZExt:
3282193323Sed        ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3283193323Sed                               DAG.getValueType(VA.getValVT()));
3284193323Sed        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3285193323Sed        break;
3286193323Sed      }
3287193323Sed
3288198090Srdivacky      InVals.push_back(ArgValue);
3289193323Sed
3290193323Sed    } else { // VA.isRegLoc()
3291193323Sed
3292193323Sed      // sanity check
3293193323Sed      assert(VA.isMemLoc());
3294193323Sed      assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3295193323Sed
3296283526Sdim      int index = VA.getValNo();
3297193323Sed
3298221345Sdim      // Some Ins[] entries become multiple ArgLoc[] entries.
3299221345Sdim      // Process them only once.
3300221345Sdim      if (index != lastInsIndex)
3301221345Sdim        {
3302221345Sdim          ISD::ArgFlagsTy Flags = Ins[index].Flags;
3303223017Sdim          // FIXME: For now, all byval parameter objects are marked mutable.
3304221345Sdim          // This can be changed with more analysis.
3305221345Sdim          // In case of tail call optimization mark all arguments mutable.
3306221345Sdim          // Since they could be overwritten by lowering of arguments in case of
3307221345Sdim          // a tail call.
3308221345Sdim          if (Flags.isByVal()) {
3309283526Sdim            assert(Ins[index].isOrigArg() &&
3310283526Sdim                   "Byval arguments cannot be implicit");
3311277320Sdim            unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3312276479Sdim
3313296417Sdim            int FrameIndex = StoreByValRegs(
3314296417Sdim                CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3315296417Sdim                VA.getLocMemOffset(), Flags.getByValSize());
3316288943Sdim            InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3317251662Sdim            CCInfo.nextInRegsParam();
3318221345Sdim          } else {
3319276479Sdim            unsigned FIOffset = VA.getLocMemOffset();
3320221345Sdim            int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3321261991Sdim                                            FIOffset, true);
3322221345Sdim
3323221345Sdim            // Create load nodes to retrieve arguments from the stack.
3324288943Sdim            SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3325296417Sdim            InVals.push_back(DAG.getLoad(
3326296417Sdim                VA.getValVT(), dl, Chain, FIN,
3327296417Sdim                MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3328296417Sdim                false, false, false, 0));
3329221345Sdim          }
3330221345Sdim          lastInsIndex = index;
3331221345Sdim        }
3332193323Sed    }
3333193323Sed  }
3334193323Sed
3335193323Sed  // varargs
3336280031Sdim  if (isVarArg && MFI->hasVAStart())
3337251662Sdim    VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3338276479Sdim                         CCInfo.getNextStackOffset(),
3339276479Sdim                         TotalArgRegsSaveSize);
3340193323Sed
3341276479Sdim  AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3342276479Sdim
3343198090Srdivacky  return Chain;
3344193323Sed}
3345193323Sed
3346193323Sed/// isFloatingPointZero - Return true if this is +0.0.
3347193323Sedstatic bool isFloatingPointZero(SDValue Op) {
3348193323Sed  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3349193323Sed    return CFP->getValueAPF().isPosZero();
3350193323Sed  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3351193323Sed    // Maybe this has already been legalized into the constant pool?
3352193323Sed    if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3353193323Sed      SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3354193323Sed      if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3355207618Srdivacky        if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3356193323Sed          return CFP->getValueAPF().isPosZero();
3357193323Sed    }
3358280031Sdim  } else if (Op->getOpcode() == ISD::BITCAST &&
3359280031Sdim             Op->getValueType(0) == MVT::f64) {
3360280031Sdim    // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3361280031Sdim    // created by LowerConstantFP().
3362280031Sdim    SDValue BitcastOp = Op->getOperand(0);
3363296417Sdim    if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3364296417Sdim        isNullConstant(BitcastOp->getOperand(0)))
3365296417Sdim      return true;
3366193323Sed  }
3367193323Sed  return false;
3368193323Sed}
3369193323Sed
3370193323Sed/// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3371193323Sed/// the given operands.
3372199481SrdivackySDValue
3373199481SrdivackyARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3374210299Sed                             SDValue &ARMcc, SelectionDAG &DAG,
3375261991Sdim                             SDLoc dl) const {
3376193323Sed  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3377193323Sed    unsigned C = RHSC->getZExtValue();
3378199481Srdivacky    if (!isLegalICmpImmediate(C)) {
3379193323Sed      // Constant does not fit, try adjusting it by one?
3380193323Sed      switch (CC) {
3381193323Sed      default: break;
3382193323Sed      case ISD::SETLT:
3383193323Sed      case ISD::SETGE:
3384212904Sdim        if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3385193323Sed          CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3386288943Sdim          RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3387193323Sed        }
3388193323Sed        break;
3389193323Sed      case ISD::SETULT:
3390193323Sed      case ISD::SETUGE:
3391212904Sdim        if (C != 0 && isLegalICmpImmediate(C-1)) {
3392193323Sed          CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3393288943Sdim          RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3394193323Sed        }
3395193323Sed        break;
3396193323Sed      case ISD::SETLE:
3397193323Sed      case ISD::SETGT:
3398212904Sdim        if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3399193323Sed          CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3400288943Sdim          RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3401193323Sed        }
3402193323Sed        break;
3403193323Sed      case ISD::SETULE:
3404193323Sed      case ISD::SETUGT:
3405212904Sdim        if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3406193323Sed          CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3407288943Sdim          RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3408193323Sed        }
3409193323Sed        break;
3410193323Sed      }
3411193323Sed    }
3412193323Sed  }
3413193323Sed
3414193323Sed  ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3415193323Sed  ARMISD::NodeType CompareType;
3416193323Sed  switch (CondCode) {
3417193323Sed  default:
3418193323Sed    CompareType = ARMISD::CMP;
3419193323Sed    break;
3420193323Sed  case ARMCC::EQ:
3421193323Sed  case ARMCC::NE:
3422195340Sed    // Uses only Z Flag
3423195340Sed    CompareType = ARMISD::CMPZ;
3424193323Sed    break;
3425193323Sed  }
3426288943Sdim  ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3427218893Sdim  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3428193323Sed}
3429193323Sed
3430193323Sed/// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3431210299SedSDValue
3432210299SedARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3433261991Sdim                             SDLoc dl) const {
3434280031Sdim  assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3435193323Sed  SDValue Cmp;
3436193323Sed  if (!isFloatingPointZero(RHS))
3437218893Sdim    Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3438193323Sed  else
3439218893Sdim    Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3440218893Sdim  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3441193323Sed}
3442193323Sed
3443221345Sdim/// duplicateCmp - Glue values can have only one use, so this function
3444221345Sdim/// duplicates a comparison node.
3445221345SdimSDValue
3446221345SdimARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3447221345Sdim  unsigned Opc = Cmp.getOpcode();
3448261991Sdim  SDLoc DL(Cmp);
3449221345Sdim  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3450221345Sdim    return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3451221345Sdim
3452221345Sdim  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3453221345Sdim  Cmp = Cmp.getOperand(0);
3454221345Sdim  Opc = Cmp.getOpcode();
3455221345Sdim  if (Opc == ARMISD::CMPFP)
3456221345Sdim    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3457221345Sdim  else {
3458221345Sdim    assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3459221345Sdim    Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3460221345Sdim  }
3461221345Sdim  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3462221345Sdim}
3463221345Sdim
3464276479Sdimstd::pair<SDValue, SDValue>
3465276479SdimARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3466276479Sdim                                 SDValue &ARMcc) const {
3467276479Sdim  assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3468276479Sdim
3469276479Sdim  SDValue Value, OverflowCmp;
3470276479Sdim  SDValue LHS = Op.getOperand(0);
3471276479Sdim  SDValue RHS = Op.getOperand(1);
3472288943Sdim  SDLoc dl(Op);
3473276479Sdim
3474276479Sdim  // FIXME: We are currently always generating CMPs because we don't support
3475276479Sdim  // generating CMN through the backend. This is not as good as the natural
3476276479Sdim  // CMP case because it causes a register dependency and cannot be folded
3477276479Sdim  // later.
3478276479Sdim
3479276479Sdim  switch (Op.getOpcode()) {
3480276479Sdim  default:
3481276479Sdim    llvm_unreachable("Unknown overflow instruction!");
3482276479Sdim  case ISD::SADDO:
3483288943Sdim    ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3484288943Sdim    Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3485288943Sdim    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3486276479Sdim    break;
3487276479Sdim  case ISD::UADDO:
3488288943Sdim    ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3489288943Sdim    Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3490288943Sdim    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3491276479Sdim    break;
3492276479Sdim  case ISD::SSUBO:
3493288943Sdim    ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3494288943Sdim    Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3495288943Sdim    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3496276479Sdim    break;
3497276479Sdim  case ISD::USUBO:
3498288943Sdim    ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3499288943Sdim    Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3500288943Sdim    OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3501276479Sdim    break;
3502276479Sdim  } // switch (...)
3503276479Sdim
3504276479Sdim  return std::make_pair(Value, OverflowCmp);
3505276479Sdim}
3506276479Sdim
3507276479Sdim
3508276479SdimSDValue
3509276479SdimARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3510276479Sdim  // Let legalize expand this if it isn't a legal type yet.
3511276479Sdim  if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3512276479Sdim    return SDValue();
3513276479Sdim
3514276479Sdim  SDValue Value, OverflowCmp;
3515276479Sdim  SDValue ARMcc;
3516276479Sdim  std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3517276479Sdim  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3518288943Sdim  SDLoc dl(Op);
3519276479Sdim  // We use 0 and 1 as false and true values.
3520288943Sdim  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3521288943Sdim  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3522276479Sdim  EVT VT = Op.getValueType();
3523276479Sdim
3524288943Sdim  SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3525276479Sdim                                 ARMcc, CCR, OverflowCmp);
3526276479Sdim
3527276479Sdim  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3528288943Sdim  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3529276479Sdim}
3530276479Sdim
3531276479Sdim
3532212904SdimSDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3533212904Sdim  SDValue Cond = Op.getOperand(0);
3534212904Sdim  SDValue SelectTrue = Op.getOperand(1);
3535212904Sdim  SDValue SelectFalse = Op.getOperand(2);
3536261991Sdim  SDLoc dl(Op);
3537276479Sdim  unsigned Opc = Cond.getOpcode();
3538212904Sdim
3539276479Sdim  if (Cond.getResNo() == 1 &&
3540276479Sdim      (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3541276479Sdim       Opc == ISD::USUBO)) {
3542276479Sdim    if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3543276479Sdim      return SDValue();
3544276479Sdim
3545276479Sdim    SDValue Value, OverflowCmp;
3546276479Sdim    SDValue ARMcc;
3547276479Sdim    std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3548276479Sdim    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3549276479Sdim    EVT VT = Op.getValueType();
3550276479Sdim
3551288943Sdim    return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3552280031Sdim                   OverflowCmp, DAG);
3553276479Sdim  }
3554276479Sdim
3555212904Sdim  // Convert:
3556212904Sdim  //
3557212904Sdim  //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3558212904Sdim  //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3559212904Sdim  //
3560212904Sdim  if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3561212904Sdim    const ConstantSDNode *CMOVTrue =
3562212904Sdim      dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3563212904Sdim    const ConstantSDNode *CMOVFalse =
3564212904Sdim      dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3565212904Sdim
3566212904Sdim    if (CMOVTrue && CMOVFalse) {
3567212904Sdim      unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3568212904Sdim      unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3569212904Sdim
3570212904Sdim      SDValue True;
3571212904Sdim      SDValue False;
3572212904Sdim      if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3573212904Sdim        True = SelectTrue;
3574212904Sdim        False = SelectFalse;
3575212904Sdim      } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3576212904Sdim        True = SelectFalse;
3577212904Sdim        False = SelectTrue;
3578212904Sdim      }
3579212904Sdim
3580212904Sdim      if (True.getNode() && False.getNode()) {
3581223017Sdim        EVT VT = Op.getValueType();
3582212904Sdim        SDValue ARMcc = Cond.getOperand(2);
3583212904Sdim        SDValue CCR = Cond.getOperand(3);
3584221345Sdim        SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3585223017Sdim        assert(True.getValueType() == VT);
3586280031Sdim        return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3587212904Sdim      }
3588212904Sdim    }
3589212904Sdim  }
3590212904Sdim
3591234353Sdim  // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3592234353Sdim  // undefined bits before doing a full-word comparison with zero.
3593234353Sdim  Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3594288943Sdim                     DAG.getConstant(1, dl, Cond.getValueType()));
3595234353Sdim
3596212904Sdim  return DAG.getSelectCC(dl, Cond,
3597288943Sdim                         DAG.getConstant(0, dl, Cond.getValueType()),
3598212904Sdim                         SelectTrue, SelectFalse, ISD::SETNE);
3599212904Sdim}
3600212904Sdim
3601261991Sdimstatic void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3602261991Sdim                                 bool &swpCmpOps, bool &swpVselOps) {
3603261991Sdim  // Start by selecting the GE condition code for opcodes that return true for
3604261991Sdim  // 'equality'
3605261991Sdim  if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3606261991Sdim      CC == ISD::SETULE)
3607261991Sdim    CondCode = ARMCC::GE;
3608261991Sdim
3609261991Sdim  // and GT for opcodes that return false for 'equality'.
3610261991Sdim  else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3611261991Sdim           CC == ISD::SETULT)
3612261991Sdim    CondCode = ARMCC::GT;
3613261991Sdim
3614261991Sdim  // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3615261991Sdim  // to swap the compare operands.
3616261991Sdim  if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3617261991Sdim      CC == ISD::SETULT)
3618261991Sdim    swpCmpOps = true;
3619261991Sdim
3620261991Sdim  // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3621261991Sdim  // If we have an unordered opcode, we need to swap the operands to the VSEL
3622261991Sdim  // instruction (effectively negating the condition).
3623261991Sdim  //
3624261991Sdim  // This also has the effect of swapping which one of 'less' or 'greater'
3625261991Sdim  // returns true, so we also swap the compare operands. It also switches
3626261991Sdim  // whether we return true for 'equality', so we compensate by picking the
3627261991Sdim  // opposite condition code to our original choice.
3628261991Sdim  if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3629261991Sdim      CC == ISD::SETUGT) {
3630261991Sdim    swpCmpOps = !swpCmpOps;
3631261991Sdim    swpVselOps = !swpVselOps;
3632261991Sdim    CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3633261991Sdim  }
3634261991Sdim
3635261991Sdim  // 'ordered' is 'anything but unordered', so use the VS condition code and
3636261991Sdim  // swap the VSEL operands.
3637261991Sdim  if (CC == ISD::SETO) {
3638261991Sdim    CondCode = ARMCC::VS;
3639261991Sdim    swpVselOps = true;
3640261991Sdim  }
3641261991Sdim
3642261991Sdim  // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3643261991Sdim  // code and swap the VSEL operands.
3644261991Sdim  if (CC == ISD::SETUNE) {
3645261991Sdim    CondCode = ARMCC::EQ;
3646261991Sdim    swpVselOps = true;
3647261991Sdim  }
3648261991Sdim}
3649261991Sdim
3650280031SdimSDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3651280031Sdim                                   SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3652280031Sdim                                   SDValue Cmp, SelectionDAG &DAG) const {
3653280031Sdim  if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3654280031Sdim    FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3655280031Sdim                           DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3656280031Sdim    TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3657280031Sdim                          DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3658280031Sdim
3659280031Sdim    SDValue TrueLow = TrueVal.getValue(0);
3660280031Sdim    SDValue TrueHigh = TrueVal.getValue(1);
3661280031Sdim    SDValue FalseLow = FalseVal.getValue(0);
3662280031Sdim    SDValue FalseHigh = FalseVal.getValue(1);
3663280031Sdim
3664280031Sdim    SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3665280031Sdim                              ARMcc, CCR, Cmp);
3666280031Sdim    SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3667280031Sdim                               ARMcc, CCR, duplicateCmp(Cmp, DAG));
3668280031Sdim
3669280031Sdim    return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3670280031Sdim  } else {
3671280031Sdim    return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3672280031Sdim                       Cmp);
3673280031Sdim  }
3674280031Sdim}
3675280031Sdim
3676207618SrdivackySDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3677198090Srdivacky  EVT VT = Op.getValueType();
3678193323Sed  SDValue LHS = Op.getOperand(0);
3679193323Sed  SDValue RHS = Op.getOperand(1);
3680193323Sed  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3681193323Sed  SDValue TrueVal = Op.getOperand(2);
3682193323Sed  SDValue FalseVal = Op.getOperand(3);
3683261991Sdim  SDLoc dl(Op);
3684193323Sed
3685280031Sdim  if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3686280031Sdim    DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3687280031Sdim                                                    dl);
3688280031Sdim
3689280031Sdim    // If softenSetCCOperands only returned one value, we should compare it to
3690280031Sdim    // zero.
3691280031Sdim    if (!RHS.getNode()) {
3692288943Sdim      RHS = DAG.getConstant(0, dl, LHS.getValueType());
3693280031Sdim      CC = ISD::SETNE;
3694280031Sdim    }
3695280031Sdim  }
3696280031Sdim
3697193323Sed  if (LHS.getValueType() == MVT::i32) {
3698261991Sdim    // Try to generate VSEL on ARMv8.
3699261991Sdim    // The VSEL instruction can't use all the usual ARM condition
3700261991Sdim    // codes: it only has two bits to select the condition code, so it's
3701261991Sdim    // constrained to use only GE, GT, VS and EQ.
3702261991Sdim    //
3703261991Sdim    // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3704261991Sdim    // swap the operands of the previous compare instruction (effectively
3705261991Sdim    // inverting the compare condition, swapping 'less' and 'greater') and
3706261991Sdim    // sometimes need to swap the operands to the VSEL (which inverts the
3707261991Sdim    // condition in the sense of firing whenever the previous condition didn't)
3708288943Sdim    if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3709288943Sdim                                    TrueVal.getValueType() == MVT::f64)) {
3710261991Sdim      ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3711261991Sdim      if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3712261991Sdim          CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3713288943Sdim        CC = ISD::getSetCCInverse(CC, true);
3714261991Sdim        std::swap(TrueVal, FalseVal);
3715261991Sdim      }
3716261991Sdim    }
3717261991Sdim
3718210299Sed    SDValue ARMcc;
3719193323Sed    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3720210299Sed    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3721280031Sdim    return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3722193323Sed  }
3723193323Sed
3724193323Sed  ARMCC::CondCodes CondCode, CondCode2;
3725198090Srdivacky  FPCCToARMCC(CC, CondCode, CondCode2);
3726193323Sed
3727288943Sdim  // Try to generate VMAXNM/VMINNM on ARMv8.
3728288943Sdim  if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3729288943Sdim                                  TrueVal.getValueType() == MVT::f64)) {
3730261991Sdim    bool swpCmpOps = false;
3731261991Sdim    bool swpVselOps = false;
3732261991Sdim    checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3733261991Sdim
3734261991Sdim    if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3735261991Sdim        CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3736261991Sdim      if (swpCmpOps)
3737261991Sdim        std::swap(LHS, RHS);
3738261991Sdim      if (swpVselOps)
3739261991Sdim        std::swap(TrueVal, FalseVal);
3740261991Sdim    }
3741261991Sdim  }
3742261991Sdim
3743288943Sdim  SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3744210299Sed  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3745193323Sed  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3746280031Sdim  SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3747193323Sed  if (CondCode2 != ARMCC::AL) {
3748288943Sdim    SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3749193323Sed    // FIXME: Needs another CMP because flag can have but one use.
3750193323Sed    SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3751280031Sdim    Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3752193323Sed  }
3753193323Sed  return Result;
3754193323Sed}
3755193323Sed
3756210299Sed/// canChangeToInt - Given the fp compare operand, return true if it is suitable
3757210299Sed/// to morph to an integer compare sequence.
3758210299Sedstatic bool canChangeToInt(SDValue Op, bool &SeenZero,
3759210299Sed                           const ARMSubtarget *Subtarget) {
3760210299Sed  SDNode *N = Op.getNode();
3761210299Sed  if (!N->hasOneUse())
3762210299Sed    // Otherwise it requires moving the value from fp to integer registers.
3763210299Sed    return false;
3764210299Sed  if (!N->getNumValues())
3765210299Sed    return false;
3766210299Sed  EVT VT = Op.getValueType();
3767210299Sed  if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3768210299Sed    // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3769210299Sed    // vmrs are very slow, e.g. cortex-a8.
3770210299Sed    return false;
3771210299Sed
3772210299Sed  if (isFloatingPointZero(Op)) {
3773210299Sed    SeenZero = true;
3774210299Sed    return true;
3775210299Sed  }
3776210299Sed  return ISD::isNormalLoad(N);
3777210299Sed}
3778210299Sed
3779210299Sedstatic SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3780210299Sed  if (isFloatingPointZero(Op))
3781288943Sdim    return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3782210299Sed
3783210299Sed  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3784261991Sdim    return DAG.getLoad(MVT::i32, SDLoc(Op),
3785218893Sdim                       Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3786210299Sed                       Ld->isVolatile(), Ld->isNonTemporal(),
3787234353Sdim                       Ld->isInvariant(), Ld->getAlignment());
3788210299Sed
3789210299Sed  llvm_unreachable("Unknown VFP cmp argument!");
3790210299Sed}
3791210299Sed
3792210299Sedstatic void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3793210299Sed                           SDValue &RetVal1, SDValue &RetVal2) {
3794288943Sdim  SDLoc dl(Op);
3795288943Sdim
3796210299Sed  if (isFloatingPointZero(Op)) {
3797288943Sdim    RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3798288943Sdim    RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3799210299Sed    return;
3800210299Sed  }
3801210299Sed
3802210299Sed  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3803210299Sed    SDValue Ptr = Ld->getBasePtr();
3804288943Sdim    RetVal1 = DAG.getLoad(MVT::i32, dl,
3805210299Sed                          Ld->getChain(), Ptr,
3806218893Sdim                          Ld->getPointerInfo(),
3807210299Sed                          Ld->isVolatile(), Ld->isNonTemporal(),
3808234353Sdim                          Ld->isInvariant(), Ld->getAlignment());
3809210299Sed
3810210299Sed    EVT PtrType = Ptr.getValueType();
3811210299Sed    unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3812288943Sdim    SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3813288943Sdim                                 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3814288943Sdim    RetVal2 = DAG.getLoad(MVT::i32, dl,
3815210299Sed                          Ld->getChain(), NewPtr,
3816218893Sdim                          Ld->getPointerInfo().getWithOffset(4),
3817210299Sed                          Ld->isVolatile(), Ld->isNonTemporal(),
3818234353Sdim                          Ld->isInvariant(), NewAlign);
3819210299Sed    return;
3820210299Sed  }
3821210299Sed
3822210299Sed  llvm_unreachable("Unknown VFP cmp argument!");
3823210299Sed}
3824210299Sed
3825210299Sed/// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3826210299Sed/// f32 and even f64 comparisons to integer ones.
3827210299SedSDValue
3828210299SedARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3829210299Sed  SDValue Chain = Op.getOperand(0);
3830210299Sed  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3831210299Sed  SDValue LHS = Op.getOperand(2);
3832210299Sed  SDValue RHS = Op.getOperand(3);
3833210299Sed  SDValue Dest = Op.getOperand(4);
3834261991Sdim  SDLoc dl(Op);
3835210299Sed
3836234353Sdim  bool LHSSeenZero = false;
3837234353Sdim  bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3838234353Sdim  bool RHSSeenZero = false;
3839234353Sdim  bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3840234353Sdim  if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3841221345Sdim    // If unsafe fp math optimization is enabled and there are no other uses of
3842221345Sdim    // the CMP operands, and the condition code is EQ or NE, we can optimize it
3843210299Sed    // to an integer comparison.
3844210299Sed    if (CC == ISD::SETOEQ)
3845210299Sed      CC = ISD::SETEQ;
3846210299Sed    else if (CC == ISD::SETUNE)
3847210299Sed      CC = ISD::SETNE;
3848210299Sed
3849288943Sdim    SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3850210299Sed    SDValue ARMcc;
3851210299Sed    if (LHS.getValueType() == MVT::f32) {
3852234353Sdim      LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3853234353Sdim                        bitcastf32Toi32(LHS, DAG), Mask);
3854234353Sdim      RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3855234353Sdim                        bitcastf32Toi32(RHS, DAG), Mask);
3856210299Sed      SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3857210299Sed      SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3858210299Sed      return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3859210299Sed                         Chain, Dest, ARMcc, CCR, Cmp);
3860210299Sed    }
3861210299Sed
3862210299Sed    SDValue LHS1, LHS2;
3863210299Sed    SDValue RHS1, RHS2;
3864210299Sed    expandf64Toi32(LHS, DAG, LHS1, LHS2);
3865210299Sed    expandf64Toi32(RHS, DAG, RHS1, RHS2);
3866234353Sdim    LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3867234353Sdim    RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3868210299Sed    ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3869288943Sdim    ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3870218893Sdim    SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3871210299Sed    SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3872276479Sdim    return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3873210299Sed  }
3874210299Sed
3875210299Sed  return SDValue();
3876210299Sed}
3877210299Sed
3878207618SrdivackySDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3879210299Sed  SDValue Chain = Op.getOperand(0);
3880193323Sed  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3881210299Sed  SDValue LHS = Op.getOperand(2);
3882210299Sed  SDValue RHS = Op.getOperand(3);
3883210299Sed  SDValue Dest = Op.getOperand(4);
3884261991Sdim  SDLoc dl(Op);
3885193323Sed
3886280031Sdim  if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3887280031Sdim    DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3888280031Sdim                                                    dl);
3889280031Sdim
3890280031Sdim    // If softenSetCCOperands only returned one value, we should compare it to
3891280031Sdim    // zero.
3892280031Sdim    if (!RHS.getNode()) {
3893288943Sdim      RHS = DAG.getConstant(0, dl, LHS.getValueType());
3894280031Sdim      CC = ISD::SETNE;
3895280031Sdim    }
3896280031Sdim  }
3897280031Sdim
3898193323Sed  if (LHS.getValueType() == MVT::i32) {
3899210299Sed    SDValue ARMcc;
3900210299Sed    SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3901193323Sed    SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3902193323Sed    return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3903210299Sed                       Chain, Dest, ARMcc, CCR, Cmp);
3904193323Sed  }
3905193323Sed
3906193323Sed  assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3907210299Sed
3908234353Sdim  if (getTargetMachine().Options.UnsafeFPMath &&
3909210299Sed      (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3910210299Sed       CC == ISD::SETNE || CC == ISD::SETUNE)) {
3911210299Sed    SDValue Result = OptimizeVFPBrcond(Op, DAG);
3912210299Sed    if (Result.getNode())
3913210299Sed      return Result;
3914210299Sed  }
3915210299Sed
3916193323Sed  ARMCC::CondCodes CondCode, CondCode2;
3917198090Srdivacky  FPCCToARMCC(CC, CondCode, CondCode2);
3918193323Sed
3919288943Sdim  SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3920193323Sed  SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3921193323Sed  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3922218893Sdim  SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3923210299Sed  SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3924276479Sdim  SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3925193323Sed  if (CondCode2 != ARMCC::AL) {
3926288943Sdim    ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3927210299Sed    SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3928276479Sdim    Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3929193323Sed  }
3930193323Sed  return Res;
3931193323Sed}
3932193323Sed
3933207618SrdivackySDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3934193323Sed  SDValue Chain = Op.getOperand(0);
3935193323Sed  SDValue Table = Op.getOperand(1);
3936193323Sed  SDValue Index = Op.getOperand(2);
3937261991Sdim  SDLoc dl(Op);
3938193323Sed
3939288943Sdim  EVT PTy = getPointerTy(DAG.getDataLayout());
3940193323Sed  JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3941193323Sed  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3942288943Sdim  Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3943288943Sdim  Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3944193323Sed  SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3945198090Srdivacky  if (Subtarget->isThumb2()) {
3946198090Srdivacky    // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3947198090Srdivacky    // which does another jump to the destination. This also makes it easier
3948198090Srdivacky    // to translate it to TBB / TBH later.
3949198090Srdivacky    // FIXME: This might not work if the function is extremely large.
3950198090Srdivacky    return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3951288943Sdim                       Addr, Op.getOperand(2), JTI);
3952198090Srdivacky  }
3953198090Srdivacky  if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3954296417Sdim    Addr =
3955296417Sdim        DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3956296417Sdim                    MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3957296417Sdim                    false, false, false, 0);
3958198090Srdivacky    Chain = Addr.getValue(1);
3959193323Sed    Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3960288943Sdim    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3961198090Srdivacky  } else {
3962296417Sdim    Addr =
3963296417Sdim        DAG.getLoad(PTy, dl, Chain, Addr,
3964296417Sdim                    MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3965296417Sdim                    false, false, false, 0);
3966198090Srdivacky    Chain = Addr.getValue(1);
3967288943Sdim    return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3968198090Srdivacky  }
3969193323Sed}
3970193323Sed
3971234353Sdimstatic SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3972234353Sdim  EVT VT = Op.getValueType();
3973261991Sdim  SDLoc dl(Op);
3974234353Sdim
3975234353Sdim  if (Op.getValueType().getVectorElementType() == MVT::i32) {
3976234353Sdim    if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3977234353Sdim      return Op;
3978234353Sdim    return DAG.UnrollVectorOp(Op.getNode());
3979234353Sdim  }
3980234353Sdim
3981234353Sdim  assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3982234353Sdim         "Invalid type for custom lowering!");
3983234353Sdim  if (VT != MVT::v4i16)
3984234353Sdim    return DAG.UnrollVectorOp(Op.getNode());
3985234353Sdim
3986234353Sdim  Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3987234353Sdim  return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3988234353Sdim}
3989234353Sdim
3990280031SdimSDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3991234353Sdim  EVT VT = Op.getValueType();
3992234353Sdim  if (VT.isVector())
3993234353Sdim    return LowerVectorFP_TO_INT(Op, DAG);
3994280031Sdim  if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3995280031Sdim    RTLIB::Libcall LC;
3996280031Sdim    if (Op.getOpcode() == ISD::FP_TO_SINT)
3997280031Sdim      LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3998280031Sdim                              Op.getValueType());
3999280031Sdim    else
4000280031Sdim      LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4001280031Sdim                              Op.getValueType());
4002296417Sdim    return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4003280031Sdim                       /*isSigned*/ false, SDLoc(Op)).first;
4004280031Sdim  }
4005280031Sdim
4006288943Sdim  return Op;
4007193323Sed}
4008193323Sed
4009221345Sdimstatic SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4010221345Sdim  EVT VT = Op.getValueType();
4011261991Sdim  SDLoc dl(Op);
4012221345Sdim
4013234353Sdim  if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4014234353Sdim    if (VT.getVectorElementType() == MVT::f32)
4015234353Sdim      return Op;
4016234353Sdim    return DAG.UnrollVectorOp(Op.getNode());
4017234353Sdim  }
4018234353Sdim
4019226633Sdim  assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4020226633Sdim         "Invalid type for custom lowering!");
4021221345Sdim  if (VT != MVT::v4f32)
4022221345Sdim    return DAG.UnrollVectorOp(Op.getNode());
4023221345Sdim
4024221345Sdim  unsigned CastOpc;
4025221345Sdim  unsigned Opc;
4026221345Sdim  switch (Op.getOpcode()) {
4027234353Sdim  default: llvm_unreachable("Invalid opcode!");
4028221345Sdim  case ISD::SINT_TO_FP:
4029221345Sdim    CastOpc = ISD::SIGN_EXTEND;
4030221345Sdim    Opc = ISD::SINT_TO_FP;
4031221345Sdim    break;
4032221345Sdim  case ISD::UINT_TO_FP:
4033221345Sdim    CastOpc = ISD::ZERO_EXTEND;
4034221345Sdim    Opc = ISD::UINT_TO_FP;
4035221345Sdim    break;
4036221345Sdim  }
4037221345Sdim
4038221345Sdim  Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4039221345Sdim  return DAG.getNode(Opc, dl, VT, Op);
4040221345Sdim}
4041221345Sdim
4042280031SdimSDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4043198090Srdivacky  EVT VT = Op.getValueType();
4044221345Sdim  if (VT.isVector())
4045221345Sdim    return LowerVectorINT_TO_FP(Op, DAG);
4046280031Sdim  if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4047280031Sdim    RTLIB::Libcall LC;
4048280031Sdim    if (Op.getOpcode() == ISD::SINT_TO_FP)
4049280031Sdim      LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4050280031Sdim                              Op.getValueType());
4051280031Sdim    else
4052280031Sdim      LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4053280031Sdim                              Op.getValueType());
4054296417Sdim    return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4055280031Sdim                       /*isSigned*/ false, SDLoc(Op)).first;
4056280031Sdim  }
4057280031Sdim
4058288943Sdim  return Op;
4059193323Sed}
4060193323Sed
4061210299SedSDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4062193323Sed  // Implement fcopysign with a fabs and a conditional fneg.
4063193323Sed  SDValue Tmp0 = Op.getOperand(0);
4064193323Sed  SDValue Tmp1 = Op.getOperand(1);
4065261991Sdim  SDLoc dl(Op);
4066198090Srdivacky  EVT VT = Op.getValueType();
4067198090Srdivacky  EVT SrcVT = Tmp1.getValueType();
4068219077Sdim  bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4069219077Sdim    Tmp0.getOpcode() == ARMISD::VMOVDRR;
4070219077Sdim  bool UseNEON = !InGPR && Subtarget->hasNEON();
4071218893Sdim
4072219077Sdim  if (UseNEON) {
4073219077Sdim    // Use VBSL to copy the sign bit.
4074219077Sdim    unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4075219077Sdim    SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4076288943Sdim                               DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4077219077Sdim    EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4078219077Sdim    if (VT == MVT::f64)
4079219077Sdim      Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4080219077Sdim                         DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4081288943Sdim                         DAG.getConstant(32, dl, MVT::i32));
4082219077Sdim    else /*if (VT == MVT::f32)*/
4083219077Sdim      Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4084219077Sdim    if (SrcVT == MVT::f32) {
4085219077Sdim      Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4086219077Sdim      if (VT == MVT::f64)
4087219077Sdim        Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4088219077Sdim                           DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4089288943Sdim                           DAG.getConstant(32, dl, MVT::i32));
4090221345Sdim    } else if (VT == MVT::f32)
4091221345Sdim      Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4092221345Sdim                         DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4093288943Sdim                         DAG.getConstant(32, dl, MVT::i32));
4094219077Sdim    Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4095219077Sdim    Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4096219077Sdim
4097219077Sdim    SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4098288943Sdim                                            dl, MVT::i32);
4099219077Sdim    AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4100219077Sdim    SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4101219077Sdim                                  DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4102221345Sdim
4103219077Sdim    SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4104219077Sdim                              DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4105219077Sdim                              DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4106221345Sdim    if (VT == MVT::f32) {
4107219077Sdim      Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4108219077Sdim      Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4109288943Sdim                        DAG.getConstant(0, dl, MVT::i32));
4110219077Sdim    } else {
4111219077Sdim      Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4112219077Sdim    }
4113219077Sdim
4114219077Sdim    return Res;
4115219077Sdim  }
4116219077Sdim
4117218893Sdim  // Bitcast operand 1 to i32.
4118218893Sdim  if (SrcVT == MVT::f64)
4119218893Sdim    Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4120276479Sdim                       Tmp1).getValue(1);
4121218893Sdim  Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4122218893Sdim
4123219077Sdim  // Or in the signbit with integer operations.
4124288943Sdim  SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4125288943Sdim  SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4126219077Sdim  Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4127219077Sdim  if (VT == MVT::f32) {
4128219077Sdim    Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4129219077Sdim                       DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4130219077Sdim    return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4131219077Sdim                       DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4132218893Sdim  }
4133218893Sdim
4134219077Sdim  // f64: Or the high part with signbit and then combine two parts.
4135219077Sdim  Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4136276479Sdim                     Tmp0);
4137219077Sdim  SDValue Lo = Tmp0.getValue(0);
4138219077Sdim  SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4139219077Sdim  Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4140219077Sdim  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4141193323Sed}
4142193323Sed
4143208599SrdivackySDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4144208599Srdivacky  MachineFunction &MF = DAG.getMachineFunction();
4145208599Srdivacky  MachineFrameInfo *MFI = MF.getFrameInfo();
4146208599Srdivacky  MFI->setReturnAddressIsTaken(true);
4147208599Srdivacky
4148276479Sdim  if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4149276479Sdim    return SDValue();
4150276479Sdim
4151208599Srdivacky  EVT VT = Op.getValueType();
4152261991Sdim  SDLoc dl(Op);
4153208599Srdivacky  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4154208599Srdivacky  if (Depth) {
4155208599Srdivacky    SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4156288943Sdim    SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4157208599Srdivacky    return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4158208599Srdivacky                       DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4159234353Sdim                       MachinePointerInfo(), false, false, false, 0);
4160208599Srdivacky  }
4161208599Srdivacky
4162208599Srdivacky  // Return LR, which contains the return address. Mark it an implicit live-in.
4163219077Sdim  unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4164208599Srdivacky  return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4165208599Srdivacky}
4166208599Srdivacky
4167207618SrdivackySDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4168276479Sdim  const ARMBaseRegisterInfo &ARI =
4169276479Sdim    *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4170276479Sdim  MachineFunction &MF = DAG.getMachineFunction();
4171276479Sdim  MachineFrameInfo *MFI = MF.getFrameInfo();
4172193323Sed  MFI->setFrameAddressIsTaken(true);
4173208599Srdivacky
4174198090Srdivacky  EVT VT = Op.getValueType();
4175261991Sdim  SDLoc dl(Op);  // FIXME probably not meaningful
4176193323Sed  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4177276479Sdim  unsigned FrameReg = ARI.getFrameRegister(MF);
4178193323Sed  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4179193323Sed  while (Depth--)
4180218893Sdim    FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4181218893Sdim                            MachinePointerInfo(),
4182234353Sdim                            false, false, false, 0);
4183193323Sed  return FrameAddr;
4184193323Sed}
4185193323Sed
4186276479Sdim// FIXME? Maybe this could be a TableGen attribute on some registers and
4187276479Sdim// this table could be generated automatically from RegInfo.
4188288943Sdimunsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4189288943Sdim                                              SelectionDAG &DAG) const {
4190276479Sdim  unsigned Reg = StringSwitch<unsigned>(RegName)
4191276479Sdim                       .Case("sp", ARM::SP)
4192276479Sdim                       .Default(0);
4193276479Sdim  if (Reg)
4194276479Sdim    return Reg;
4195288943Sdim  report_fatal_error(Twine("Invalid register name \""
4196288943Sdim                              + StringRef(RegName)  + "\"."));
4197276479Sdim}
4198276479Sdim
4199288943Sdim// Result is 64 bit value so split into two 32 bit values and return as a
4200288943Sdim// pair of values.
4201288943Sdimstatic void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4202288943Sdim                                SelectionDAG &DAG) {
4203288943Sdim  SDLoc DL(N);
4204288943Sdim
4205288943Sdim  // This function is only supposed to be called for i64 type destination.
4206288943Sdim  assert(N->getValueType(0) == MVT::i64
4207288943Sdim          && "ExpandREAD_REGISTER called for non-i64 type result.");
4208288943Sdim
4209288943Sdim  SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4210288943Sdim                             DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4211288943Sdim                             N->getOperand(0),
4212288943Sdim                             N->getOperand(1));
4213288943Sdim
4214288943Sdim  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4215288943Sdim                    Read.getValue(1)));
4216288943Sdim  Results.push_back(Read.getOperand(0));
4217288943Sdim}
4218288943Sdim
4219296417Sdim/// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4220296417Sdim/// When \p DstVT, the destination type of \p BC, is on the vector
4221296417Sdim/// register bank and the source of bitcast, \p Op, operates on the same bank,
4222296417Sdim/// it might be possible to combine them, such that everything stays on the
4223296417Sdim/// vector register bank.
4224296417Sdim/// \p return The node that would replace \p BT, if the combine
4225296417Sdim/// is possible.
4226296417Sdimstatic SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4227296417Sdim                                                SelectionDAG &DAG) {
4228296417Sdim  SDValue Op = BC->getOperand(0);
4229296417Sdim  EVT DstVT = BC->getValueType(0);
4230296417Sdim
4231296417Sdim  // The only vector instruction that can produce a scalar (remember,
4232296417Sdim  // since the bitcast was about to be turned into VMOVDRR, the source
4233296417Sdim  // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4234296417Sdim  // Moreover, we can do this combine only if there is one use.
4235296417Sdim  // Finally, if the destination type is not a vector, there is not
4236296417Sdim  // much point on forcing everything on the vector bank.
4237296417Sdim  if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4238296417Sdim      !Op.hasOneUse())
4239296417Sdim    return SDValue();
4240296417Sdim
4241296417Sdim  // If the index is not constant, we will introduce an additional
4242296417Sdim  // multiply that will stick.
4243296417Sdim  // Give up in that case.
4244296417Sdim  ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4245296417Sdim  if (!Index)
4246296417Sdim    return SDValue();
4247296417Sdim  unsigned DstNumElt = DstVT.getVectorNumElements();
4248296417Sdim
4249296417Sdim  // Compute the new index.
4250296417Sdim  const APInt &APIntIndex = Index->getAPIntValue();
4251296417Sdim  APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4252296417Sdim  NewIndex *= APIntIndex;
4253296417Sdim  // Check if the new constant index fits into i32.
4254296417Sdim  if (NewIndex.getBitWidth() > 32)
4255296417Sdim    return SDValue();
4256296417Sdim
4257296417Sdim  // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4258296417Sdim  // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4259296417Sdim  SDLoc dl(Op);
4260296417Sdim  SDValue ExtractSrc = Op.getOperand(0);
4261296417Sdim  EVT VecVT = EVT::getVectorVT(
4262296417Sdim      *DAG.getContext(), DstVT.getScalarType(),
4263296417Sdim      ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4264296417Sdim  SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4265296417Sdim  return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4266296417Sdim                     DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4267296417Sdim}
4268296417Sdim
4269218893Sdim/// ExpandBITCAST - If the target supports VFP, this function is called to
4270207618Srdivacky/// expand a bit convert where either the source or destination type is i64 to
4271207618Srdivacky/// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4272207618Srdivacky/// operand type is illegal (e.g., v2f32 for a target that doesn't support
4273207618Srdivacky/// vectors), since the legalizer won't know what to do with that.
4274218893Sdimstatic SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4275207618Srdivacky  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4276261991Sdim  SDLoc dl(N);
4277193323Sed  SDValue Op = N->getOperand(0);
4278207618Srdivacky
4279207618Srdivacky  // This function is only supposed to be called for i64 types, either as the
4280207618Srdivacky  // source or destination of the bit convert.
4281207618Srdivacky  EVT SrcVT = Op.getValueType();
4282207618Srdivacky  EVT DstVT = N->getValueType(0);
4283207618Srdivacky  assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4284218893Sdim         "ExpandBITCAST called for non-i64 type");
4285207618Srdivacky
4286207618Srdivacky  // Turn i64->f64 into VMOVDRR.
4287207618Srdivacky  if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4288296417Sdim    // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4289296417Sdim    // if we can combine the bitcast with its source.
4290296417Sdim    if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4291296417Sdim      return Val;
4292296417Sdim
4293193323Sed    SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4294288943Sdim                             DAG.getConstant(0, dl, MVT::i32));
4295193323Sed    SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4296288943Sdim                             DAG.getConstant(1, dl, MVT::i32));
4297218893Sdim    return DAG.getNode(ISD::BITCAST, dl, DstVT,
4298210299Sed                       DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4299193323Sed  }
4300193323Sed
4301199481Srdivacky  // Turn f64->i64 into VMOVRRD.
4302207618Srdivacky  if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4303276479Sdim    SDValue Cvt;
4304288943Sdim    if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4305276479Sdim        SrcVT.getVectorNumElements() > 1)
4306276479Sdim      Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4307276479Sdim                        DAG.getVTList(MVT::i32, MVT::i32),
4308276479Sdim                        DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4309276479Sdim    else
4310276479Sdim      Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4311276479Sdim                        DAG.getVTList(MVT::i32, MVT::i32), Op);
4312207618Srdivacky    // Merge the pieces into a single i64 value.
4313207618Srdivacky    return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4314207618Srdivacky  }
4315193323Sed
4316207618Srdivacky  return SDValue();
4317193323Sed}
4318193323Sed
4319194710Sed/// getZeroVector - Returns a vector of specified type with all zero elements.
4320210299Sed/// Zero vectors are used to represent vector negation and in those cases
4321210299Sed/// will be implemented with the NEON VNEG instruction.  However, VNEG does
4322210299Sed/// not support i64 elements, so sometimes the zero vectors will need to be
4323210299Sed/// explicitly constructed.  Regardless, use a canonical VMOV to create the
4324210299Sed/// zero vector.
4325261991Sdimstatic SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4326194710Sed  assert(VT.isVector() && "Expected a vector type");
4327210299Sed  // The canonical modified immediate encoding of a zero vector is....0!
4328288943Sdim  SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4329210299Sed  EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4330210299Sed  SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4331218893Sdim  return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4332194710Sed}
4333194710Sed
4334198892Srdivacky/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4335198892Srdivacky/// i32 values and take a 2 x i32 value to shift plus a shift amount.
4336207618SrdivackySDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4337207618Srdivacky                                                SelectionDAG &DAG) const {
4338198892Srdivacky  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4339198892Srdivacky  EVT VT = Op.getValueType();
4340198892Srdivacky  unsigned VTBits = VT.getSizeInBits();
4341261991Sdim  SDLoc dl(Op);
4342198892Srdivacky  SDValue ShOpLo = Op.getOperand(0);
4343198892Srdivacky  SDValue ShOpHi = Op.getOperand(1);
4344198892Srdivacky  SDValue ShAmt  = Op.getOperand(2);
4345210299Sed  SDValue ARMcc;
4346198892Srdivacky  unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4347198892Srdivacky
4348198892Srdivacky  assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4349198892Srdivacky
4350198892Srdivacky  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4351288943Sdim                                 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4352198892Srdivacky  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4353198892Srdivacky  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4354288943Sdim                                   DAG.getConstant(VTBits, dl, MVT::i32));
4355198892Srdivacky  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4356198892Srdivacky  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4357198892Srdivacky  SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4358198892Srdivacky
4359198892Srdivacky  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4360288943Sdim  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4361288943Sdim                          ISD::SETGE, ARMcc, DAG, dl);
4362198892Srdivacky  SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4363210299Sed  SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4364198892Srdivacky                           CCR, Cmp);
4365198892Srdivacky
4366198892Srdivacky  SDValue Ops[2] = { Lo, Hi };
4367276479Sdim  return DAG.getMergeValues(Ops, dl);
4368198892Srdivacky}
4369198892Srdivacky
4370198892Srdivacky/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4371198892Srdivacky/// i32 values and take a 2 x i32 value to shift plus a shift amount.
4372207618SrdivackySDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4373207618Srdivacky                                               SelectionDAG &DAG) const {
4374198892Srdivacky  assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4375198892Srdivacky  EVT VT = Op.getValueType();
4376198892Srdivacky  unsigned VTBits = VT.getSizeInBits();
4377261991Sdim  SDLoc dl(Op);
4378198892Srdivacky  SDValue ShOpLo = Op.getOperand(0);
4379198892Srdivacky  SDValue ShOpHi = Op.getOperand(1);
4380198892Srdivacky  SDValue ShAmt  = Op.getOperand(2);
4381210299Sed  SDValue ARMcc;
4382198892Srdivacky
4383198892Srdivacky  assert(Op.getOpcode() == ISD::SHL_PARTS);
4384198892Srdivacky  SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4385288943Sdim                                 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4386198892Srdivacky  SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4387198892Srdivacky  SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4388288943Sdim                                   DAG.getConstant(VTBits, dl, MVT::i32));
4389198892Srdivacky  SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4390198892Srdivacky  SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4391198892Srdivacky
4392198892Srdivacky  SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4393198892Srdivacky  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4394288943Sdim  SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4395288943Sdim                          ISD::SETGE, ARMcc, DAG, dl);
4396198892Srdivacky  SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4397210299Sed  SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4398198892Srdivacky                           CCR, Cmp);
4399198892Srdivacky
4400198892Srdivacky  SDValue Ops[2] = { Lo, Hi };
4401276479Sdim  return DAG.getMergeValues(Ops, dl);
4402198892Srdivacky}
4403198892Srdivacky
4404218893SdimSDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4405212904Sdim                                            SelectionDAG &DAG) const {
4406212904Sdim  // The rounding mode is in bits 23:22 of the FPSCR.
4407212904Sdim  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4408212904Sdim  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4409212904Sdim  // so that the shift + and get folded into a bitfield extract.
4410261991Sdim  SDLoc dl(Op);
4411212904Sdim  SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4412288943Sdim                              DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4413212904Sdim                                              MVT::i32));
4414218893Sdim  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4415288943Sdim                                  DAG.getConstant(1U << 22, dl, MVT::i32));
4416212904Sdim  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4417288943Sdim                              DAG.getConstant(22, dl, MVT::i32));
4418218893Sdim  return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4419288943Sdim                     DAG.getConstant(3, dl, MVT::i32));
4420212904Sdim}
4421212904Sdim
4422202878Srdivackystatic SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4423202878Srdivacky                         const ARMSubtarget *ST) {
4424288943Sdim  SDLoc dl(N);
4425202878Srdivacky  EVT VT = N->getValueType(0);
4426288943Sdim  if (VT.isVector()) {
4427288943Sdim    assert(ST->hasNEON());
4428202878Srdivacky
4429288943Sdim    // Compute the least significant set bit: LSB = X & -X
4430288943Sdim    SDValue X = N->getOperand(0);
4431288943Sdim    SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4432288943Sdim    SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4433288943Sdim
4434288943Sdim    EVT ElemTy = VT.getVectorElementType();
4435288943Sdim
4436288943Sdim    if (ElemTy == MVT::i8) {
4437288943Sdim      // Compute with: cttz(x) = ctpop(lsb - 1)
4438288943Sdim      SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4439288943Sdim                                DAG.getTargetConstant(1, dl, ElemTy));
4440288943Sdim      SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4441288943Sdim      return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4442288943Sdim    }
4443288943Sdim
4444288943Sdim    if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4445288943Sdim        (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4446288943Sdim      // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4447288943Sdim      unsigned NumBits = ElemTy.getSizeInBits();
4448288943Sdim      SDValue WidthMinus1 =
4449288943Sdim          DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4450288943Sdim                      DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4451288943Sdim      SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4452288943Sdim      return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4453288943Sdim    }
4454288943Sdim
4455288943Sdim    // Compute with: cttz(x) = ctpop(lsb - 1)
4456288943Sdim
4457288943Sdim    // Since we can only compute the number of bits in a byte with vcnt.8, we
4458288943Sdim    // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4459288943Sdim    // and i64.
4460288943Sdim
4461288943Sdim    // Compute LSB - 1.
4462288943Sdim    SDValue Bits;
4463288943Sdim    if (ElemTy == MVT::i64) {
4464288943Sdim      // Load constant 0xffff'ffff'ffff'ffff to register.
4465288943Sdim      SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4466288943Sdim                               DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4467288943Sdim      Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4468288943Sdim    } else {
4469288943Sdim      SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4470288943Sdim                                DAG.getTargetConstant(1, dl, ElemTy));
4471288943Sdim      Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4472288943Sdim    }
4473288943Sdim
4474288943Sdim    // Count #bits with vcnt.8.
4475288943Sdim    EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4476288943Sdim    SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4477288943Sdim    SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4478288943Sdim
4479288943Sdim    // Gather the #bits with vpaddl (pairwise add.)
4480288943Sdim    EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4481288943Sdim    SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4482288943Sdim        DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4483288943Sdim        Cnt8);
4484288943Sdim    if (ElemTy == MVT::i16)
4485288943Sdim      return Cnt16;
4486288943Sdim
4487288943Sdim    EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4488288943Sdim    SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4489288943Sdim        DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4490288943Sdim        Cnt16);
4491288943Sdim    if (ElemTy == MVT::i32)
4492288943Sdim      return Cnt32;
4493288943Sdim
4494288943Sdim    assert(ElemTy == MVT::i64);
4495288943Sdim    SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4496288943Sdim        DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4497288943Sdim        Cnt32);
4498288943Sdim    return Cnt64;
4499288943Sdim  }
4500288943Sdim
4501202878Srdivacky  if (!ST->hasV6T2Ops())
4502202878Srdivacky    return SDValue();
4503202878Srdivacky
4504296417Sdim  SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4505202878Srdivacky  return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4506202878Srdivacky}
4507202878Srdivacky
4508249423Sdim/// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4509249423Sdim/// for each 16-bit element from operand, repeated.  The basic idea is to
4510249423Sdim/// leverage vcnt to get the 8-bit counts, gather and add the results.
4511249423Sdim///
4512249423Sdim/// Trace for v4i16:
4513249423Sdim/// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4514249423Sdim/// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4515249423Sdim/// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4516249423Sdim/// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4517249423Sdim///            [b0 b1 b2 b3 b4 b5 b6 b7]
4518249423Sdim///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4519249423Sdim/// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4520249423Sdim/// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4521249423Sdimstatic SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4522249423Sdim  EVT VT = N->getValueType(0);
4523261991Sdim  SDLoc DL(N);
4524249423Sdim
4525249423Sdim  EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4526249423Sdim  SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4527249423Sdim  SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4528249423Sdim  SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4529249423Sdim  SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4530249423Sdim  return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4531249423Sdim}
4532249423Sdim
4533249423Sdim/// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4534249423Sdim/// bit-count for each 16-bit element from the operand.  We need slightly
4535249423Sdim/// different sequencing for v4i16 and v8i16 to stay within NEON's available
4536249423Sdim/// 64/128-bit registers.
4537249423Sdim///
4538249423Sdim/// Trace for v4i16:
4539249423Sdim/// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4540249423Sdim/// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4541249423Sdim/// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4542249423Sdim/// v4i16:Extracted = [k0    k1    k2    k3    ]
4543249423Sdimstatic SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4544249423Sdim  EVT VT = N->getValueType(0);
4545261991Sdim  SDLoc DL(N);
4546249423Sdim
4547249423Sdim  SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4548249423Sdim  if (VT.is64BitVector()) {
4549249423Sdim    SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4550249423Sdim    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4551288943Sdim                       DAG.getIntPtrConstant(0, DL));
4552249423Sdim  } else {
4553249423Sdim    SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4554288943Sdim                                    BitCounts, DAG.getIntPtrConstant(0, DL));
4555249423Sdim    return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4556249423Sdim  }
4557249423Sdim}
4558249423Sdim
4559249423Sdim/// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4560249423Sdim/// bit-count for each 32-bit element from the operand.  The idea here is
4561249423Sdim/// to split the vector into 16-bit elements, leverage the 16-bit count
4562249423Sdim/// routine, and then combine the results.
4563249423Sdim///
4564249423Sdim/// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4565249423Sdim/// input    = [v0    v1    ] (vi: 32-bit elements)
4566249423Sdim/// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4567249423Sdim/// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4568249423Sdim/// vrev: N0 = [k1 k0 k3 k2 ]
4569249423Sdim///            [k0 k1 k2 k3 ]
4570249423Sdim///       N1 =+[k1 k0 k3 k2 ]
4571249423Sdim///            [k0 k2 k1 k3 ]
4572249423Sdim///       N2 =+[k1 k3 k0 k2 ]
4573249423Sdim///            [k0    k2    k1    k3    ]
4574249423Sdim/// Extended =+[k1    k3    k0    k2    ]
4575249423Sdim///            [k0    k2    ]
4576249423Sdim/// Extracted=+[k1    k3    ]
4577249423Sdim///
4578249423Sdimstatic SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4579249423Sdim  EVT VT = N->getValueType(0);
4580261991Sdim  SDLoc DL(N);
4581249423Sdim
4582249423Sdim  EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4583249423Sdim
4584249423Sdim  SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4585249423Sdim  SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4586249423Sdim  SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4587249423Sdim  SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4588249423Sdim  SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4589249423Sdim
4590249423Sdim  if (VT.is64BitVector()) {
4591249423Sdim    SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4592249423Sdim    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4593288943Sdim                       DAG.getIntPtrConstant(0, DL));
4594249423Sdim  } else {
4595249423Sdim    SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4596288943Sdim                                    DAG.getIntPtrConstant(0, DL));
4597249423Sdim    return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4598249423Sdim  }
4599249423Sdim}
4600249423Sdim
4601249423Sdimstatic SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4602249423Sdim                          const ARMSubtarget *ST) {
4603249423Sdim  EVT VT = N->getValueType(0);
4604249423Sdim
4605249423Sdim  assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4606249423Sdim  assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4607249423Sdim          VT == MVT::v4i16 || VT == MVT::v8i16) &&
4608249423Sdim         "Unexpected type for custom ctpop lowering");
4609249423Sdim
4610249423Sdim  if (VT.getVectorElementType() == MVT::i32)
4611249423Sdim    return lowerCTPOP32BitElements(N, DAG);
4612249423Sdim  else
4613249423Sdim    return lowerCTPOP16BitElements(N, DAG);
4614249423Sdim}
4615249423Sdim
4616194710Sedstatic SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4617194710Sed                          const ARMSubtarget *ST) {
4618198090Srdivacky  EVT VT = N->getValueType(0);
4619261991Sdim  SDLoc dl(N);
4620194710Sed
4621218893Sdim  if (!VT.isVector())
4622218893Sdim    return SDValue();
4623218893Sdim
4624194710Sed  // Lower vector shifts on NEON to use VSHL.
4625218893Sdim  assert(ST->hasNEON() && "unexpected vector shift");
4626194710Sed
4627218893Sdim  // Left shifts translate directly to the vshiftu intrinsic.
4628218893Sdim  if (N->getOpcode() == ISD::SHL)
4629218893Sdim    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4630288943Sdim                       DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4631288943Sdim                                       MVT::i32),
4632218893Sdim                       N->getOperand(0), N->getOperand(1));
4633194710Sed
4634218893Sdim  assert((N->getOpcode() == ISD::SRA ||
4635218893Sdim          N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4636194710Sed
4637218893Sdim  // NEON uses the same intrinsics for both left and right shifts.  For
4638218893Sdim  // right shifts, the shift amounts are negative, so negate the vector of
4639218893Sdim  // shift amounts.
4640218893Sdim  EVT ShiftVT = N->getOperand(1).getValueType();
4641218893Sdim  SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4642218893Sdim                                     getZeroVector(ShiftVT, DAG, dl),
4643218893Sdim                                     N->getOperand(1));
4644218893Sdim  Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4645218893Sdim                             Intrinsic::arm_neon_vshifts :
4646218893Sdim                             Intrinsic::arm_neon_vshiftu);
4647218893Sdim  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4648288943Sdim                     DAG.getConstant(vshiftInt, dl, MVT::i32),
4649218893Sdim                     N->getOperand(0), NegatedCount);
4650218893Sdim}
4651194710Sed
4652218893Sdimstatic SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4653218893Sdim                                const ARMSubtarget *ST) {
4654218893Sdim  EVT VT = N->getValueType(0);
4655261991Sdim  SDLoc dl(N);
4656218893Sdim
4657198090Srdivacky  // We can get here for a node like i32 = ISD::SHL i32, i64
4658198090Srdivacky  if (VT != MVT::i64)
4659198090Srdivacky    return SDValue();
4660198090Srdivacky
4661198090Srdivacky  assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4662193323Sed         "Unknown shift to lower!");
4663193323Sed
4664193323Sed  // We only lower SRA, SRL of 1 here, all others use generic lowering.
4665296417Sdim  if (!isOneConstant(N->getOperand(1)))
4666193323Sed    return SDValue();
4667193323Sed
4668193323Sed  // If we are in thumb mode, we don't have RRX.
4669198090Srdivacky  if (ST->isThumb1Only()) return SDValue();
4670193323Sed
4671193323Sed  // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4672193323Sed  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4673288943Sdim                           DAG.getConstant(0, dl, MVT::i32));
4674193323Sed  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4675288943Sdim                           DAG.getConstant(1, dl, MVT::i32));
4676193323Sed
4677193323Sed  // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4678193323Sed  // captures the result into a carry flag.
4679193323Sed  unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4680276479Sdim  Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4681193323Sed
4682193323Sed  // The low part is an ARMISD::RRX operand, which shifts the carry in.
4683193323Sed  Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4684193323Sed
4685193323Sed  // Merge the pieces into a single i64 value.
4686193323Sed return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4687193323Sed}
4688193323Sed
4689194710Sedstatic SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4690194710Sed  SDValue TmpOp0, TmpOp1;
4691194710Sed  bool Invert = false;
4692194710Sed  bool Swap = false;
4693194710Sed  unsigned Opc = 0;
4694194710Sed
4695194710Sed  SDValue Op0 = Op.getOperand(0);
4696194710Sed  SDValue Op1 = Op.getOperand(1);
4697194710Sed  SDValue CC = Op.getOperand(2);
4698280031Sdim  EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4699198090Srdivacky  EVT VT = Op.getValueType();
4700194710Sed  ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4701261991Sdim  SDLoc dl(Op);
4702194710Sed
4703288943Sdim  if (CmpVT.getVectorElementType() == MVT::i64)
4704288943Sdim    // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4705288943Sdim    // but it's possible that our operands are 64-bit but our result is 32-bit.
4706288943Sdim    // Bail in this case.
4707288943Sdim    return SDValue();
4708288943Sdim
4709280031Sdim  if (Op1.getValueType().isFloatingPoint()) {
4710194710Sed    switch (SetCCOpcode) {
4711234353Sdim    default: llvm_unreachable("Illegal FP comparison");
4712194710Sed    case ISD::SETUNE:
4713194710Sed    case ISD::SETNE:  Invert = true; // Fallthrough
4714194710Sed    case ISD::SETOEQ:
4715194710Sed    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4716194710Sed    case ISD::SETOLT:
4717194710Sed    case ISD::SETLT: Swap = true; // Fallthrough
4718194710Sed    case ISD::SETOGT:
4719194710Sed    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4720194710Sed    case ISD::SETOLE:
4721194710Sed    case ISD::SETLE:  Swap = true; // Fallthrough
4722194710Sed    case ISD::SETOGE:
4723194710Sed    case ISD::SETGE: Opc = ARMISD::VCGE; break;
4724194710Sed    case ISD::SETUGE: Swap = true; // Fallthrough
4725194710Sed    case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4726194710Sed    case ISD::SETUGT: Swap = true; // Fallthrough
4727194710Sed    case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4728194710Sed    case ISD::SETUEQ: Invert = true; // Fallthrough
4729194710Sed    case ISD::SETONE:
4730194710Sed      // Expand this to (OLT | OGT).
4731194710Sed      TmpOp0 = Op0;
4732194710Sed      TmpOp1 = Op1;
4733194710Sed      Opc = ISD::OR;
4734280031Sdim      Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4735280031Sdim      Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4736194710Sed      break;
4737194710Sed    case ISD::SETUO: Invert = true; // Fallthrough
4738194710Sed    case ISD::SETO:
4739194710Sed      // Expand this to (OLT | OGE).
4740194710Sed      TmpOp0 = Op0;
4741194710Sed      TmpOp1 = Op1;
4742194710Sed      Opc = ISD::OR;
4743280031Sdim      Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4744280031Sdim      Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4745194710Sed      break;
4746194710Sed    }
4747194710Sed  } else {
4748194710Sed    // Integer comparisons.
4749194710Sed    switch (SetCCOpcode) {
4750234353Sdim    default: llvm_unreachable("Illegal integer comparison");
4751194710Sed    case ISD::SETNE:  Invert = true;
4752194710Sed    case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4753194710Sed    case ISD::SETLT:  Swap = true;
4754194710Sed    case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4755194710Sed    case ISD::SETLE:  Swap = true;
4756194710Sed    case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4757194710Sed    case ISD::SETULT: Swap = true;
4758194710Sed    case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4759194710Sed    case ISD::SETULE: Swap = true;
4760194710Sed    case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4761194710Sed    }
4762194710Sed
4763198090Srdivacky    // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4764194710Sed    if (Opc == ARMISD::VCEQ) {
4765194710Sed
4766194710Sed      SDValue AndOp;
4767194710Sed      if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4768194710Sed        AndOp = Op0;
4769194710Sed      else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4770194710Sed        AndOp = Op1;
4771194710Sed
4772194710Sed      // Ignore bitconvert.
4773218893Sdim      if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4774194710Sed        AndOp = AndOp.getOperand(0);
4775194710Sed
4776194710Sed      if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4777194710Sed        Opc = ARMISD::VTST;
4778280031Sdim        Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4779280031Sdim        Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4780194710Sed        Invert = !Invert;
4781194710Sed      }
4782194710Sed    }
4783194710Sed  }
4784194710Sed
4785194710Sed  if (Swap)
4786194710Sed    std::swap(Op0, Op1);
4787194710Sed
4788218893Sdim  // If one of the operands is a constant vector zero, attempt to fold the
4789218893Sdim  // comparison to a specialized compare-against-zero form.
4790218893Sdim  SDValue SingleOp;
4791218893Sdim  if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4792218893Sdim    SingleOp = Op0;
4793218893Sdim  else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4794218893Sdim    if (Opc == ARMISD::VCGE)
4795218893Sdim      Opc = ARMISD::VCLEZ;
4796218893Sdim    else if (Opc == ARMISD::VCGT)
4797218893Sdim      Opc = ARMISD::VCLTZ;
4798218893Sdim    SingleOp = Op1;
4799218893Sdim  }
4800194710Sed
4801218893Sdim  SDValue Result;
4802218893Sdim  if (SingleOp.getNode()) {
4803218893Sdim    switch (Opc) {
4804218893Sdim    case ARMISD::VCEQ:
4805280031Sdim      Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4806218893Sdim    case ARMISD::VCGE:
4807280031Sdim      Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4808218893Sdim    case ARMISD::VCLEZ:
4809280031Sdim      Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4810218893Sdim    case ARMISD::VCGT:
4811280031Sdim      Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4812218893Sdim    case ARMISD::VCLTZ:
4813280031Sdim      Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4814218893Sdim    default:
4815280031Sdim      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4816218893Sdim    }
4817218893Sdim  } else {
4818280031Sdim     Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4819218893Sdim  }
4820218893Sdim
4821280031Sdim  Result = DAG.getSExtOrTrunc(Result, dl, VT);
4822280031Sdim
4823194710Sed  if (Invert)
4824194710Sed    Result = DAG.getNOT(dl, Result, VT);
4825194710Sed
4826194710Sed  return Result;
4827194710Sed}
4828194710Sed
4829210299Sed/// isNEONModifiedImm - Check if the specified splat value corresponds to a
4830210299Sed/// valid vector constant for a NEON instruction with a "modified immediate"
4831210299Sed/// operand (e.g., VMOV).  If so, return the encoded value.
4832210299Sedstatic SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4833210299Sed                                 unsigned SplatBitSize, SelectionDAG &DAG,
4834288943Sdim                                 SDLoc dl, EVT &VT, bool is128Bits,
4835288943Sdim                                 NEONModImmType type) {
4836210299Sed  unsigned OpCmode, Imm;
4837210299Sed
4838210299Sed  // SplatBitSize is set to the smallest size that splats the vector, so a
4839210299Sed  // zero vector will always have SplatBitSize == 8.  However, NEON modified
4840210299Sed  // immediate instructions others than VMOV do not support the 8-bit encoding
4841210299Sed  // of a zero vector, and the default encoding of zero is supposed to be the
4842210299Sed  // 32-bit version.
4843210299Sed  if (SplatBits == 0)
4844210299Sed    SplatBitSize = 32;
4845210299Sed
4846194710Sed  switch (SplatBitSize) {
4847194710Sed  case 8:
4848218893Sdim    if (type != VMOVModImm)
4849210299Sed      return SDValue();
4850210299Sed    // Any 1-byte value is OK.  Op=0, Cmode=1110.
4851194710Sed    assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4852210299Sed    OpCmode = 0xe;
4853210299Sed    Imm = SplatBits;
4854210299Sed    VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4855210299Sed    break;
4856194710Sed
4857194710Sed  case 16:
4858194710Sed    // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4859210299Sed    VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4860210299Sed    if ((SplatBits & ~0xff) == 0) {
4861210299Sed      // Value = 0x00nn: Op=x, Cmode=100x.
4862210299Sed      OpCmode = 0x8;
4863210299Sed      Imm = SplatBits;
4864210299Sed      break;
4865210299Sed    }
4866210299Sed    if ((SplatBits & ~0xff00) == 0) {
4867210299Sed      // Value = 0xnn00: Op=x, Cmode=101x.
4868210299Sed      OpCmode = 0xa;
4869210299Sed      Imm = SplatBits >> 8;
4870210299Sed      break;
4871210299Sed    }
4872210299Sed    return SDValue();
4873194710Sed
4874194710Sed  case 32:
4875194710Sed    // NEON's 32-bit VMOV supports splat values where:
4876194710Sed    // * only one byte is nonzero, or
4877194710Sed    // * the least significant byte is 0xff and the second byte is nonzero, or
4878194710Sed    // * the least significant 2 bytes are 0xff and the third is nonzero.
4879210299Sed    VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4880210299Sed    if ((SplatBits & ~0xff) == 0) {
4881210299Sed      // Value = 0x000000nn: Op=x, Cmode=000x.
4882210299Sed      OpCmode = 0;
4883210299Sed      Imm = SplatBits;
4884210299Sed      break;
4885210299Sed    }
4886210299Sed    if ((SplatBits & ~0xff00) == 0) {
4887210299Sed      // Value = 0x0000nn00: Op=x, Cmode=001x.
4888210299Sed      OpCmode = 0x2;
4889210299Sed      Imm = SplatBits >> 8;
4890210299Sed      break;
4891210299Sed    }
4892210299Sed    if ((SplatBits & ~0xff0000) == 0) {
4893210299Sed      // Value = 0x00nn0000: Op=x, Cmode=010x.
4894210299Sed      OpCmode = 0x4;
4895210299Sed      Imm = SplatBits >> 16;
4896210299Sed      break;
4897210299Sed    }
4898210299Sed    if ((SplatBits & ~0xff000000) == 0) {
4899210299Sed      // Value = 0xnn000000: Op=x, Cmode=011x.
4900210299Sed      OpCmode = 0x6;
4901210299Sed      Imm = SplatBits >> 24;
4902210299Sed      break;
4903210299Sed    }
4904194710Sed
4905218893Sdim    // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4906218893Sdim    if (type == OtherModImm) return SDValue();
4907218893Sdim
4908194710Sed    if ((SplatBits & ~0xffff) == 0 &&
4909210299Sed        ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4910210299Sed      // Value = 0x0000nnff: Op=x, Cmode=1100.
4911210299Sed      OpCmode = 0xc;
4912210299Sed      Imm = SplatBits >> 8;
4913210299Sed      break;
4914210299Sed    }
4915194710Sed
4916194710Sed    if ((SplatBits & ~0xffffff) == 0 &&
4917210299Sed        ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4918210299Sed      // Value = 0x00nnffff: Op=x, Cmode=1101.
4919210299Sed      OpCmode = 0xd;
4920210299Sed      Imm = SplatBits >> 16;
4921210299Sed      break;
4922210299Sed    }
4923194710Sed
4924194710Sed    // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4925194710Sed    // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4926194710Sed    // VMOV.I32.  A (very) minor optimization would be to replicate the value
4927194710Sed    // and fall through here to test for a valid 64-bit splat.  But, then the
4928194710Sed    // caller would also need to check and handle the change in size.
4929210299Sed    return SDValue();
4930194710Sed
4931194710Sed  case 64: {
4932218893Sdim    if (type != VMOVModImm)
4933210299Sed      return SDValue();
4934194710Sed    // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4935194710Sed    uint64_t BitMask = 0xff;
4936194710Sed    uint64_t Val = 0;
4937210299Sed    unsigned ImmMask = 1;
4938210299Sed    Imm = 0;
4939194710Sed    for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4940210299Sed      if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4941194710Sed        Val |= BitMask;
4942210299Sed        Imm |= ImmMask;
4943210299Sed      } else if ((SplatBits & BitMask) != 0) {
4944194710Sed        return SDValue();
4945210299Sed      }
4946194710Sed      BitMask <<= 8;
4947210299Sed      ImmMask <<= 1;
4948194710Sed    }
4949276479Sdim
4950288943Sdim    if (DAG.getDataLayout().isBigEndian())
4951276479Sdim      // swap higher and lower 32 bit word
4952276479Sdim      Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4953276479Sdim
4954210299Sed    // Op=1, Cmode=1110.
4955210299Sed    OpCmode = 0x1e;
4956210299Sed    VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4957210299Sed    break;
4958194710Sed  }
4959194710Sed
4960194710Sed  default:
4961210299Sed    llvm_unreachable("unexpected size for isNEONModifiedImm");
4962194710Sed  }
4963194710Sed
4964210299Sed  unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4965288943Sdim  return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4966194710Sed}
4967194710Sed
4968234353SdimSDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4969234353Sdim                                           const ARMSubtarget *ST) const {
4970261991Sdim  if (!ST->hasVFP3())
4971234353Sdim    return SDValue();
4972234353Sdim
4973261991Sdim  bool IsDouble = Op.getValueType() == MVT::f64;
4974234353Sdim  ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4975234353Sdim
4976280031Sdim  // Use the default (constant pool) lowering for double constants when we have
4977280031Sdim  // an SP-only FPU
4978280031Sdim  if (IsDouble && Subtarget->isFPOnlySP())
4979280031Sdim    return SDValue();
4980280031Sdim
4981234353Sdim  // Try splatting with a VMOV.f32...
4982234353Sdim  APFloat FPVal = CFP->getValueAPF();
4983261991Sdim  int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4984261991Sdim
4985234353Sdim  if (ImmVal != -1) {
4986261991Sdim    if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4987261991Sdim      // We have code in place to select a valid ConstantFP already, no need to
4988261991Sdim      // do any mangling.
4989261991Sdim      return Op;
4990261991Sdim    }
4991261991Sdim
4992261991Sdim    // It's a float and we are trying to use NEON operations where
4993261991Sdim    // possible. Lower it to a splat followed by an extract.
4994261991Sdim    SDLoc DL(Op);
4995288943Sdim    SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4996234353Sdim    SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4997234353Sdim                                      NewVal);
4998234353Sdim    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4999288943Sdim                       DAG.getConstant(0, DL, MVT::i32));
5000234353Sdim  }
5001234353Sdim
5002261991Sdim  // The rest of our options are NEON only, make sure that's allowed before
5003261991Sdim  // proceeding..
5004261991Sdim  if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5005261991Sdim    return SDValue();
5006261991Sdim
5007234353Sdim  EVT VMovVT;
5008261991Sdim  uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5009261991Sdim
5010261991Sdim  // It wouldn't really be worth bothering for doubles except for one very
5011261991Sdim  // important value, which does happen to match: 0.0. So make sure we don't do
5012261991Sdim  // anything stupid.
5013261991Sdim  if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5014261991Sdim    return SDValue();
5015261991Sdim
5016261991Sdim  // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5017288943Sdim  SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5018288943Sdim                                     VMovVT, false, VMOVModImm);
5019234353Sdim  if (NewVal != SDValue()) {
5020261991Sdim    SDLoc DL(Op);
5021234353Sdim    SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5022234353Sdim                                      NewVal);
5023261991Sdim    if (IsDouble)
5024261991Sdim      return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5025261991Sdim
5026261991Sdim    // It's a float: cast and extract a vector element.
5027234353Sdim    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5028234353Sdim                                       VecConstant);
5029234353Sdim    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5030288943Sdim                       DAG.getConstant(0, DL, MVT::i32));
5031234353Sdim  }
5032234353Sdim
5033234353Sdim  // Finally, try a VMVN.i32
5034288943Sdim  NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5035261991Sdim                             false, VMVNModImm);
5036234353Sdim  if (NewVal != SDValue()) {
5037261991Sdim    SDLoc DL(Op);
5038234353Sdim    SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5039261991Sdim
5040261991Sdim    if (IsDouble)
5041261991Sdim      return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5042261991Sdim
5043261991Sdim    // It's a float: cast and extract a vector element.
5044234353Sdim    SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5045234353Sdim                                       VecConstant);
5046234353Sdim    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5047288943Sdim                       DAG.getConstant(0, DL, MVT::i32));
5048234353Sdim  }
5049234353Sdim
5050234353Sdim  return SDValue();
5051234353Sdim}
5052234353Sdim
5053243830Sdim// check if an VEXT instruction can handle the shuffle mask when the
5054243830Sdim// vector sources of the shuffle are the same.
5055243830Sdimstatic bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5056243830Sdim  unsigned NumElts = VT.getVectorNumElements();
5057234353Sdim
5058243830Sdim  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5059243830Sdim  if (M[0] < 0)
5060243830Sdim    return false;
5061243830Sdim
5062243830Sdim  Imm = M[0];
5063243830Sdim
5064243830Sdim  // If this is a VEXT shuffle, the immediate value is the index of the first
5065243830Sdim  // element.  The other shuffle indices must be the successive elements after
5066243830Sdim  // the first one.
5067243830Sdim  unsigned ExpectedElt = Imm;
5068243830Sdim  for (unsigned i = 1; i < NumElts; ++i) {
5069243830Sdim    // Increment the expected index.  If it wraps around, just follow it
5070243830Sdim    // back to index zero and keep going.
5071243830Sdim    ++ExpectedElt;
5072243830Sdim    if (ExpectedElt == NumElts)
5073243830Sdim      ExpectedElt = 0;
5074243830Sdim
5075243830Sdim    if (M[i] < 0) continue; // ignore UNDEF indices
5076243830Sdim    if (ExpectedElt != static_cast<unsigned>(M[i]))
5077243830Sdim      return false;
5078243830Sdim  }
5079243830Sdim
5080243830Sdim  return true;
5081243830Sdim}
5082243830Sdim
5083243830Sdim
5084234353Sdimstatic bool isVEXTMask(ArrayRef<int> M, EVT VT,
5085198090Srdivacky                       bool &ReverseVEXT, unsigned &Imm) {
5086198090Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5087198090Srdivacky  ReverseVEXT = false;
5088212904Sdim
5089212904Sdim  // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5090212904Sdim  if (M[0] < 0)
5091212904Sdim    return false;
5092212904Sdim
5093198090Srdivacky  Imm = M[0];
5094198090Srdivacky
5095198090Srdivacky  // If this is a VEXT shuffle, the immediate value is the index of the first
5096198090Srdivacky  // element.  The other shuffle indices must be the successive elements after
5097198090Srdivacky  // the first one.
5098198090Srdivacky  unsigned ExpectedElt = Imm;
5099198090Srdivacky  for (unsigned i = 1; i < NumElts; ++i) {
5100198090Srdivacky    // Increment the expected index.  If it wraps around, it may still be
5101198090Srdivacky    // a VEXT but the source vectors must be swapped.
5102198090Srdivacky    ExpectedElt += 1;
5103198090Srdivacky    if (ExpectedElt == NumElts * 2) {
5104198090Srdivacky      ExpectedElt = 0;
5105198090Srdivacky      ReverseVEXT = true;
5106198090Srdivacky    }
5107198090Srdivacky
5108212904Sdim    if (M[i] < 0) continue; // ignore UNDEF indices
5109198090Srdivacky    if (ExpectedElt != static_cast<unsigned>(M[i]))
5110198090Srdivacky      return false;
5111198090Srdivacky  }
5112198090Srdivacky
5113198090Srdivacky  // Adjust the index value if the source operands will be swapped.
5114198090Srdivacky  if (ReverseVEXT)
5115198090Srdivacky    Imm -= NumElts;
5116198090Srdivacky
5117198090Srdivacky  return true;
5118198090Srdivacky}
5119198090Srdivacky
5120198090Srdivacky/// isVREVMask - Check if a vector shuffle corresponds to a VREV
5121198090Srdivacky/// instruction with the specified blocksize.  (The order of the elements
5122198090Srdivacky/// within each block of the vector is reversed.)
5123234353Sdimstatic bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5124198090Srdivacky  assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5125198090Srdivacky         "Only possible block sizes for VREV are: 16, 32, 64");
5126198090Srdivacky
5127198396Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5128198396Srdivacky  if (EltSz == 64)
5129198396Srdivacky    return false;
5130198396Srdivacky
5131198090Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5132198090Srdivacky  unsigned BlockElts = M[0] + 1;
5133212904Sdim  // If the first shuffle index is UNDEF, be optimistic.
5134212904Sdim  if (M[0] < 0)
5135212904Sdim    BlockElts = BlockSize / EltSz;
5136198090Srdivacky
5137198090Srdivacky  if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5138198090Srdivacky    return false;
5139198090Srdivacky
5140198090Srdivacky  for (unsigned i = 0; i < NumElts; ++i) {
5141212904Sdim    if (M[i] < 0) continue; // ignore UNDEF indices
5142212904Sdim    if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5143198090Srdivacky      return false;
5144198090Srdivacky  }
5145198090Srdivacky
5146198090Srdivacky  return true;
5147198090Srdivacky}
5148198090Srdivacky
5149234353Sdimstatic bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5150221345Sdim  // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5151221345Sdim  // range, then 0 is placed into the resulting vector. So pretty much any mask
5152221345Sdim  // of 8 elements can work here.
5153221345Sdim  return VT == MVT::v8i8 && M.size() == 8;
5154221345Sdim}
5155221345Sdim
5156296417Sdim// Checks whether the shuffle mask represents a vector transpose (VTRN) by
5157296417Sdim// checking that pairs of elements in the shuffle mask represent the same index
5158296417Sdim// in each vector, incrementing the expected index by 2 at each step.
5159296417Sdim// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5160296417Sdim//  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5161296417Sdim//  v2={e,f,g,h}
5162296417Sdim// WhichResult gives the offset for each element in the mask based on which
5163296417Sdim// of the two results it belongs to.
5164296417Sdim//
5165296417Sdim// The transpose can be represented either as:
5166296417Sdim// result1 = shufflevector v1, v2, result1_shuffle_mask
5167296417Sdim// result2 = shufflevector v1, v2, result2_shuffle_mask
5168296417Sdim// where v1/v2 and the shuffle masks have the same number of elements
5169296417Sdim// (here WhichResult (see below) indicates which result is being checked)
5170296417Sdim//
5171296417Sdim// or as:
5172296417Sdim// results = shufflevector v1, v2, shuffle_mask
5173296417Sdim// where both results are returned in one vector and the shuffle mask has twice
5174296417Sdim// as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5175296417Sdim// want to check the low half and high half of the shuffle mask as if it were
5176296417Sdim// the other case
5177234353Sdimstatic bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5178198396Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5179198396Srdivacky  if (EltSz == 64)
5180198396Srdivacky    return false;
5181198396Srdivacky
5182198090Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5183296417Sdim  if (M.size() != NumElts && M.size() != NumElts*2)
5184296417Sdim    return false;
5185296417Sdim
5186296417Sdim  // If the mask is twice as long as the input vector then we need to check the
5187296417Sdim  // upper and lower parts of the mask with a matching value for WhichResult
5188296417Sdim  // FIXME: A mask with only even values will be rejected in case the first
5189296417Sdim  // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5190296417Sdim  // M[0] is used to determine WhichResult
5191296417Sdim  for (unsigned i = 0; i < M.size(); i += NumElts) {
5192296417Sdim    if (M.size() == NumElts * 2)
5193296417Sdim      WhichResult = i / NumElts;
5194296417Sdim    else
5195296417Sdim      WhichResult = M[i] == 0 ? 0 : 1;
5196296417Sdim    for (unsigned j = 0; j < NumElts; j += 2) {
5197296417Sdim      if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5198296417Sdim          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5199296417Sdim        return false;
5200296417Sdim    }
5201198090Srdivacky  }
5202296417Sdim
5203296417Sdim  if (M.size() == NumElts*2)
5204296417Sdim    WhichResult = 0;
5205296417Sdim
5206198090Srdivacky  return true;
5207198090Srdivacky}
5208198090Srdivacky
5209200581Srdivacky/// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5210200581Srdivacky/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5211200581Srdivacky/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5212234353Sdimstatic bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5213200581Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5214200581Srdivacky  if (EltSz == 64)
5215200581Srdivacky    return false;
5216200581Srdivacky
5217200581Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5218296417Sdim  if (M.size() != NumElts && M.size() != NumElts*2)
5219296417Sdim    return false;
5220296417Sdim
5221296417Sdim  for (unsigned i = 0; i < M.size(); i += NumElts) {
5222296417Sdim    if (M.size() == NumElts * 2)
5223296417Sdim      WhichResult = i / NumElts;
5224296417Sdim    else
5225296417Sdim      WhichResult = M[i] == 0 ? 0 : 1;
5226296417Sdim    for (unsigned j = 0; j < NumElts; j += 2) {
5227296417Sdim      if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5228296417Sdim          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5229296417Sdim        return false;
5230296417Sdim    }
5231200581Srdivacky  }
5232296417Sdim
5233296417Sdim  if (M.size() == NumElts*2)
5234296417Sdim    WhichResult = 0;
5235296417Sdim
5236200581Srdivacky  return true;
5237200581Srdivacky}
5238200581Srdivacky
5239296417Sdim// Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5240296417Sdim// that the mask elements are either all even and in steps of size 2 or all odd
5241296417Sdim// and in steps of size 2.
5242296417Sdim// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5243296417Sdim//  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5244296417Sdim//  v2={e,f,g,h}
5245296417Sdim// Requires similar checks to that of isVTRNMask with
5246296417Sdim// respect the how results are returned.
5247234353Sdimstatic bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5248198396Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5249198396Srdivacky  if (EltSz == 64)
5250198396Srdivacky    return false;
5251198396Srdivacky
5252198090Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5253296417Sdim  if (M.size() != NumElts && M.size() != NumElts*2)
5254296417Sdim    return false;
5255296417Sdim
5256296417Sdim  for (unsigned i = 0; i < M.size(); i += NumElts) {
5257296417Sdim    WhichResult = M[i] == 0 ? 0 : 1;
5258296417Sdim    for (unsigned j = 0; j < NumElts; ++j) {
5259296417Sdim      if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5260296417Sdim        return false;
5261296417Sdim    }
5262198090Srdivacky  }
5263198090Srdivacky
5264296417Sdim  if (M.size() == NumElts*2)
5265296417Sdim    WhichResult = 0;
5266296417Sdim
5267198090Srdivacky  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5268198396Srdivacky  if (VT.is64BitVector() && EltSz == 32)
5269198090Srdivacky    return false;
5270198090Srdivacky
5271198090Srdivacky  return true;
5272198090Srdivacky}
5273198090Srdivacky
5274200581Srdivacky/// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5275200581Srdivacky/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5276200581Srdivacky/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5277234353Sdimstatic bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5278200581Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5279200581Srdivacky  if (EltSz == 64)
5280200581Srdivacky    return false;
5281200581Srdivacky
5282296417Sdim  unsigned NumElts = VT.getVectorNumElements();
5283296417Sdim  if (M.size() != NumElts && M.size() != NumElts*2)
5284296417Sdim    return false;
5285296417Sdim
5286296417Sdim  unsigned Half = NumElts / 2;
5287296417Sdim  for (unsigned i = 0; i < M.size(); i += NumElts) {
5288296417Sdim    WhichResult = M[i] == 0 ? 0 : 1;
5289296417Sdim    for (unsigned j = 0; j < NumElts; j += Half) {
5290296417Sdim      unsigned Idx = WhichResult;
5291296417Sdim      for (unsigned k = 0; k < Half; ++k) {
5292296417Sdim        int MIdx = M[i + j + k];
5293296417Sdim        if (MIdx >= 0 && (unsigned) MIdx != Idx)
5294296417Sdim          return false;
5295296417Sdim        Idx += 2;
5296296417Sdim      }
5297200581Srdivacky    }
5298200581Srdivacky  }
5299200581Srdivacky
5300296417Sdim  if (M.size() == NumElts*2)
5301296417Sdim    WhichResult = 0;
5302296417Sdim
5303200581Srdivacky  // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5304200581Srdivacky  if (VT.is64BitVector() && EltSz == 32)
5305200581Srdivacky    return false;
5306200581Srdivacky
5307200581Srdivacky  return true;
5308200581Srdivacky}
5309200581Srdivacky
5310296417Sdim// Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5311296417Sdim// that pairs of elements of the shufflemask represent the same index in each
5312296417Sdim// vector incrementing sequentially through the vectors.
5313296417Sdim// e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5314296417Sdim//  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5315296417Sdim//  v2={e,f,g,h}
5316296417Sdim// Requires similar checks to that of isVTRNMask with respect the how results
5317296417Sdim// are returned.
5318234353Sdimstatic bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5319198396Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5320198396Srdivacky  if (EltSz == 64)
5321198396Srdivacky    return false;
5322198396Srdivacky
5323198090Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5324296417Sdim  if (M.size() != NumElts && M.size() != NumElts*2)
5325296417Sdim    return false;
5326296417Sdim
5327296417Sdim  for (unsigned i = 0; i < M.size(); i += NumElts) {
5328296417Sdim    WhichResult = M[i] == 0 ? 0 : 1;
5329296417Sdim    unsigned Idx = WhichResult * NumElts / 2;
5330296417Sdim    for (unsigned j = 0; j < NumElts; j += 2) {
5331296417Sdim      if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5332296417Sdim          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5333296417Sdim        return false;
5334296417Sdim      Idx += 1;
5335296417Sdim    }
5336198090Srdivacky  }
5337198090Srdivacky
5338296417Sdim  if (M.size() == NumElts*2)
5339296417Sdim    WhichResult = 0;
5340296417Sdim
5341198090Srdivacky  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5342198396Srdivacky  if (VT.is64BitVector() && EltSz == 32)
5343198090Srdivacky    return false;
5344198090Srdivacky
5345198090Srdivacky  return true;
5346198090Srdivacky}
5347198090Srdivacky
5348200581Srdivacky/// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5349200581Srdivacky/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5350200581Srdivacky/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5351234353Sdimstatic bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5352200581Srdivacky  unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5353200581Srdivacky  if (EltSz == 64)
5354200581Srdivacky    return false;
5355200581Srdivacky
5356200581Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5357296417Sdim  if (M.size() != NumElts && M.size() != NumElts*2)
5358296417Sdim    return false;
5359296417Sdim
5360296417Sdim  for (unsigned i = 0; i < M.size(); i += NumElts) {
5361296417Sdim    WhichResult = M[i] == 0 ? 0 : 1;
5362296417Sdim    unsigned Idx = WhichResult * NumElts / 2;
5363296417Sdim    for (unsigned j = 0; j < NumElts; j += 2) {
5364296417Sdim      if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5365296417Sdim          (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5366296417Sdim        return false;
5367296417Sdim      Idx += 1;
5368296417Sdim    }
5369200581Srdivacky  }
5370200581Srdivacky
5371296417Sdim  if (M.size() == NumElts*2)
5372296417Sdim    WhichResult = 0;
5373296417Sdim
5374200581Srdivacky  // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5375200581Srdivacky  if (VT.is64BitVector() && EltSz == 32)
5376200581Srdivacky    return false;
5377200581Srdivacky
5378200581Srdivacky  return true;
5379200581Srdivacky}
5380200581Srdivacky
5381288943Sdim/// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5382288943Sdim/// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5383288943Sdimstatic unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5384288943Sdim                                           unsigned &WhichResult,
5385288943Sdim                                           bool &isV_UNDEF) {
5386288943Sdim  isV_UNDEF = false;
5387288943Sdim  if (isVTRNMask(ShuffleMask, VT, WhichResult))
5388288943Sdim    return ARMISD::VTRN;
5389288943Sdim  if (isVUZPMask(ShuffleMask, VT, WhichResult))
5390288943Sdim    return ARMISD::VUZP;
5391288943Sdim  if (isVZIPMask(ShuffleMask, VT, WhichResult))
5392288943Sdim    return ARMISD::VZIP;
5393288943Sdim
5394288943Sdim  isV_UNDEF = true;
5395288943Sdim  if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5396288943Sdim    return ARMISD::VTRN;
5397288943Sdim  if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5398288943Sdim    return ARMISD::VUZP;
5399288943Sdim  if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5400288943Sdim    return ARMISD::VZIP;
5401288943Sdim
5402288943Sdim  return 0;
5403288943Sdim}
5404288943Sdim
5405249423Sdim/// \return true if this is a reverse operation on an vector.
5406249423Sdimstatic bool isReverseMask(ArrayRef<int> M, EVT VT) {
5407249423Sdim  unsigned NumElts = VT.getVectorNumElements();
5408249423Sdim  // Make sure the mask has the right size.
5409249423Sdim  if (NumElts != M.size())
5410249423Sdim      return false;
5411249423Sdim
5412249423Sdim  // Look for <15, ..., 3, -1, 1, 0>.
5413249423Sdim  for (unsigned i = 0; i != NumElts; ++i)
5414249423Sdim    if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5415249423Sdim      return false;
5416249423Sdim
5417249423Sdim  return true;
5418249423Sdim}
5419249423Sdim
5420212904Sdim// If N is an integer constant that can be moved into a register in one
5421212904Sdim// instruction, return an SDValue of such a constant (will become a MOV
5422212904Sdim// instruction).  Otherwise return null.
5423212904Sdimstatic SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5424261991Sdim                                     const ARMSubtarget *ST, SDLoc dl) {
5425212904Sdim  uint64_t Val;
5426212904Sdim  if (!isa<ConstantSDNode>(N))
5427212904Sdim    return SDValue();
5428212904Sdim  Val = cast<ConstantSDNode>(N)->getZExtValue();
5429212904Sdim
5430212904Sdim  if (ST->isThumb1Only()) {
5431212904Sdim    if (Val <= 255 || ~Val <= 255)
5432288943Sdim      return DAG.getConstant(Val, dl, MVT::i32);
5433212904Sdim  } else {
5434212904Sdim    if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5435288943Sdim      return DAG.getConstant(Val, dl, MVT::i32);
5436212904Sdim  }
5437212904Sdim  return SDValue();
5438212904Sdim}
5439212904Sdim
5440194710Sed// If this is a case we can't handle, return null and let the default
5441194710Sed// expansion code take care of it.
5442218893SdimSDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5443218893Sdim                                             const ARMSubtarget *ST) const {
5444198090Srdivacky  BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5445261991Sdim  SDLoc dl(Op);
5446198090Srdivacky  EVT VT = Op.getValueType();
5447194710Sed
5448194710Sed  APInt SplatBits, SplatUndef;
5449194710Sed  unsigned SplatBitSize;
5450194710Sed  bool HasAnyUndefs;
5451194710Sed  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5452198090Srdivacky    if (SplatBitSize <= 64) {
5453210299Sed      // Check if an immediate VMOV works.
5454210299Sed      EVT VmovVT;
5455210299Sed      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5456210299Sed                                      SplatUndef.getZExtValue(), SplatBitSize,
5457288943Sdim                                      DAG, dl, VmovVT, VT.is128BitVector(),
5458218893Sdim                                      VMOVModImm);
5459210299Sed      if (Val.getNode()) {
5460210299Sed        SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5461218893Sdim        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5462210299Sed      }
5463210299Sed
5464210299Sed      // Try an immediate VMVN.
5465226633Sdim      uint64_t NegatedImm = (~SplatBits).getZExtValue();
5466210299Sed      Val = isNEONModifiedImm(NegatedImm,
5467210299Sed                                      SplatUndef.getZExtValue(), SplatBitSize,
5468288943Sdim                                      DAG, dl, VmovVT, VT.is128BitVector(),
5469218893Sdim                                      VMVNModImm);
5470210299Sed      if (Val.getNode()) {
5471210299Sed        SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5472218893Sdim        return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5473210299Sed      }
5474234353Sdim
5475234353Sdim      // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5476234353Sdim      if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5477234353Sdim        int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5478234353Sdim        if (ImmVal != -1) {
5479288943Sdim          SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5480234353Sdim          return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5481234353Sdim        }
5482234353Sdim      }
5483198090Srdivacky    }
5484194710Sed  }
5485194710Sed
5486208599Srdivacky  // Scan through the operands to see if only one value is used.
5487243830Sdim  //
5488243830Sdim  // As an optimisation, even if more than one value is used it may be more
5489243830Sdim  // profitable to splat with one value then change some lanes.
5490243830Sdim  //
5491243830Sdim  // Heuristically we decide to do this if the vector has a "dominant" value,
5492243830Sdim  // defined as splatted to more than half of the lanes.
5493208599Srdivacky  unsigned NumElts = VT.getVectorNumElements();
5494208599Srdivacky  bool isOnlyLowElement = true;
5495208599Srdivacky  bool usesOnlyOneValue = true;
5496243830Sdim  bool hasDominantValue = false;
5497208599Srdivacky  bool isConstant = true;
5498243830Sdim
5499243830Sdim  // Map of the number of times a particular SDValue appears in the
5500243830Sdim  // element list.
5501243830Sdim  DenseMap<SDValue, unsigned> ValueCounts;
5502208599Srdivacky  SDValue Value;
5503208599Srdivacky  for (unsigned i = 0; i < NumElts; ++i) {
5504208599Srdivacky    SDValue V = Op.getOperand(i);
5505208599Srdivacky    if (V.getOpcode() == ISD::UNDEF)
5506208599Srdivacky      continue;
5507208599Srdivacky    if (i > 0)
5508208599Srdivacky      isOnlyLowElement = false;
5509208599Srdivacky    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5510208599Srdivacky      isConstant = false;
5511208599Srdivacky
5512243830Sdim    ValueCounts.insert(std::make_pair(V, 0));
5513243830Sdim    unsigned &Count = ValueCounts[V];
5514249423Sdim
5515243830Sdim    // Is this value dominant? (takes up more than half of the lanes)
5516243830Sdim    if (++Count > (NumElts / 2)) {
5517243830Sdim      hasDominantValue = true;
5518208599Srdivacky      Value = V;
5519243830Sdim    }
5520198090Srdivacky  }
5521243830Sdim  if (ValueCounts.size() != 1)
5522243830Sdim    usesOnlyOneValue = false;
5523243830Sdim  if (!Value.getNode() && ValueCounts.size() > 0)
5524243830Sdim    Value = ValueCounts.begin()->first;
5525198090Srdivacky
5526243830Sdim  if (ValueCounts.size() == 0)
5527208599Srdivacky    return DAG.getUNDEF(VT);
5528208599Srdivacky
5529261991Sdim  // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5530261991Sdim  // Keep going if we are hitting this case.
5531261991Sdim  if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5532208599Srdivacky    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5533208599Srdivacky
5534212904Sdim  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5535212904Sdim
5536218893Sdim  // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5537218893Sdim  // i32 and try again.
5538243830Sdim  if (hasDominantValue && EltSize <= 32) {
5539243830Sdim    if (!isConstant) {
5540243830Sdim      SDValue N;
5541243830Sdim
5542243830Sdim      // If we are VDUPing a value that comes directly from a vector, that will
5543243830Sdim      // cause an unnecessary move to and from a GPR, where instead we could
5544249423Sdim      // just use VDUPLANE. We can only do this if the lane being extracted
5545249423Sdim      // is at a constant index, as the VDUP from lane instructions only have
5546249423Sdim      // constant-index forms.
5547296417Sdim      ConstantSDNode *constIndex;
5548249423Sdim      if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5549296417Sdim          (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5550243830Sdim        // We need to create a new undef vector to use for the VDUPLANE if the
5551243830Sdim        // size of the vector from which we get the value is different than the
5552243830Sdim        // size of the vector that we need to create. We will insert the element
5553243830Sdim        // such that the register coalescer will remove unnecessary copies.
5554243830Sdim        if (VT != Value->getOperand(0).getValueType()) {
5555243830Sdim          unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5556243830Sdim                             VT.getVectorNumElements();
5557243830Sdim          N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5558243830Sdim                 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5559288943Sdim                        Value, DAG.getConstant(index, dl, MVT::i32)),
5560288943Sdim                           DAG.getConstant(index, dl, MVT::i32));
5561249423Sdim        } else
5562243830Sdim          N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5563243830Sdim                        Value->getOperand(0), Value->getOperand(1));
5564249423Sdim      } else
5565243830Sdim        N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5566243830Sdim
5567243830Sdim      if (!usesOnlyOneValue) {
5568243830Sdim        // The dominant value was splatted as 'N', but we now have to insert
5569243830Sdim        // all differing elements.
5570243830Sdim        for (unsigned I = 0; I < NumElts; ++I) {
5571243830Sdim          if (Op.getOperand(I) == Value)
5572243830Sdim            continue;
5573243830Sdim          SmallVector<SDValue, 3> Ops;
5574243830Sdim          Ops.push_back(N);
5575243830Sdim          Ops.push_back(Op.getOperand(I));
5576288943Sdim          Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5577276479Sdim          N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5578243830Sdim        }
5579243830Sdim      }
5580243830Sdim      return N;
5581243830Sdim    }
5582218893Sdim    if (VT.getVectorElementType().isFloatingPoint()) {
5583218893Sdim      SmallVector<SDValue, 8> Ops;
5584218893Sdim      for (unsigned i = 0; i < NumElts; ++i)
5585218893Sdim        Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5586218893Sdim                                  Op.getOperand(i)));
5587218893Sdim      EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5588276479Sdim      SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5589218893Sdim      Val = LowerBUILD_VECTOR(Val, DAG, ST);
5590212904Sdim      if (Val.getNode())
5591218893Sdim        return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5592212904Sdim    }
5593243830Sdim    if (usesOnlyOneValue) {
5594243830Sdim      SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5595243830Sdim      if (isConstant && Val.getNode())
5596249423Sdim        return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5597243830Sdim    }
5598212904Sdim  }
5599212904Sdim
5600212904Sdim  // If all elements are constants and the case above didn't get hit, fall back
5601212904Sdim  // to the default expansion, which will generate a load from the constant
5602212904Sdim  // pool.
5603208599Srdivacky  if (isConstant)
5604208599Srdivacky    return SDValue();
5605208599Srdivacky
5606218893Sdim  // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5607218893Sdim  if (NumElts >= 4) {
5608218893Sdim    SDValue shuffle = ReconstructShuffle(Op, DAG);
5609218893Sdim    if (shuffle != SDValue())
5610218893Sdim      return shuffle;
5611212904Sdim  }
5612208599Srdivacky
5613208599Srdivacky  // Vectors with 32- or 64-bit elements can be built by directly assigning
5614210299Sed  // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5615210299Sed  // will be legalized.
5616208599Srdivacky  if (EltSize >= 32) {
5617208599Srdivacky    // Do the expansion with floating-point types, since that is what the VFP
5618208599Srdivacky    // registers are defined to use, and since i64 is not legal.
5619208599Srdivacky    EVT EltVT = EVT::getFloatingPointVT(EltSize);
5620208599Srdivacky    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5621210299Sed    SmallVector<SDValue, 8> Ops;
5622210299Sed    for (unsigned i = 0; i < NumElts; ++i)
5623218893Sdim      Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5624276479Sdim    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5625218893Sdim    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5626208599Srdivacky  }
5627208599Srdivacky
5628261991Sdim  // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5629261991Sdim  // know the default expansion would otherwise fall back on something even
5630261991Sdim  // worse. For a vector with one or two non-undef values, that's
5631261991Sdim  // scalar_to_vector for the elements followed by a shuffle (provided the
5632261991Sdim  // shuffle is valid for the target) and materialization element by element
5633261991Sdim  // on the stack followed by a load for everything else.
5634261991Sdim  if (!isConstant && !usesOnlyOneValue) {
5635261991Sdim    SDValue Vec = DAG.getUNDEF(VT);
5636261991Sdim    for (unsigned i = 0 ; i < NumElts; ++i) {
5637261991Sdim      SDValue V = Op.getOperand(i);
5638261991Sdim      if (V.getOpcode() == ISD::UNDEF)
5639261991Sdim        continue;
5640288943Sdim      SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5641261991Sdim      Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5642261991Sdim    }
5643261991Sdim    return Vec;
5644261991Sdim  }
5645261991Sdim
5646194710Sed  return SDValue();
5647194710Sed}
5648194710Sed
5649218893Sdim// Gather data to see if the operation can be modelled as a
5650218893Sdim// shuffle in combination with VEXTs.
5651218893SdimSDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5652218893Sdim                                              SelectionDAG &DAG) const {
5653296417Sdim  assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5654261991Sdim  SDLoc dl(Op);
5655218893Sdim  EVT VT = Op.getValueType();
5656218893Sdim  unsigned NumElts = VT.getVectorNumElements();
5657218893Sdim
5658296417Sdim  struct ShuffleSourceInfo {
5659296417Sdim    SDValue Vec;
5660296417Sdim    unsigned MinElt;
5661296417Sdim    unsigned MaxElt;
5662218893Sdim
5663296417Sdim    // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5664296417Sdim    // be compatible with the shuffle we intend to construct. As a result
5665296417Sdim    // ShuffleVec will be some sliding window into the original Vec.
5666296417Sdim    SDValue ShuffleVec;
5667296417Sdim
5668296417Sdim    // Code should guarantee that element i in Vec starts at element "WindowBase
5669296417Sdim    // + i * WindowScale in ShuffleVec".
5670296417Sdim    int WindowBase;
5671296417Sdim    int WindowScale;
5672296417Sdim
5673296417Sdim    bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5674296417Sdim    ShuffleSourceInfo(SDValue Vec)
5675296417Sdim        : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5676296417Sdim          WindowScale(1) {}
5677296417Sdim  };
5678296417Sdim
5679296417Sdim  // First gather all vectors used as an immediate source for this BUILD_VECTOR
5680296417Sdim  // node.
5681296417Sdim  SmallVector<ShuffleSourceInfo, 2> Sources;
5682218893Sdim  for (unsigned i = 0; i < NumElts; ++i) {
5683218893Sdim    SDValue V = Op.getOperand(i);
5684218893Sdim    if (V.getOpcode() == ISD::UNDEF)
5685218893Sdim      continue;
5686218893Sdim    else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5687218893Sdim      // A shuffle can only come from building a vector from various
5688218893Sdim      // elements of other vectors.
5689218893Sdim      return SDValue();
5690296417Sdim    } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5691296417Sdim      // Furthermore, shuffles require a constant mask, whereas extractelts
5692296417Sdim      // accept variable indices.
5693226633Sdim      return SDValue();
5694218893Sdim    }
5695218893Sdim
5696296417Sdim    // Add this element source to the list if it's not already there.
5697218893Sdim    SDValue SourceVec = V.getOperand(0);
5698296417Sdim    auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5699296417Sdim    if (Source == Sources.end())
5700296417Sdim      Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5701296417Sdim
5702296417Sdim    // Update the minimum and maximum lane number seen.
5703218893Sdim    unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5704296417Sdim    Source->MinElt = std::min(Source->MinElt, EltNo);
5705296417Sdim    Source->MaxElt = std::max(Source->MaxElt, EltNo);
5706218893Sdim  }
5707218893Sdim
5708218893Sdim  // Currently only do something sane when at most two source vectors
5709296417Sdim  // are involved.
5710296417Sdim  if (Sources.size() > 2)
5711218893Sdim    return SDValue();
5712218893Sdim
5713296417Sdim  // Find out the smallest element size among result and two sources, and use
5714296417Sdim  // it as element size to build the shuffle_vector.
5715296417Sdim  EVT SmallestEltTy = VT.getVectorElementType();
5716296417Sdim  for (auto &Source : Sources) {
5717296417Sdim    EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5718296417Sdim    if (SrcEltTy.bitsLT(SmallestEltTy))
5719296417Sdim      SmallestEltTy = SrcEltTy;
5720296417Sdim  }
5721296417Sdim  unsigned ResMultiplier =
5722296417Sdim      VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5723296417Sdim  NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5724296417Sdim  EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5725218893Sdim
5726296417Sdim  // If the source vector is too wide or too narrow, we may nevertheless be able
5727296417Sdim  // to construct a compatible shuffle either by concatenating it with UNDEF or
5728296417Sdim  // extracting a suitable range of elements.
5729296417Sdim  for (auto &Src : Sources) {
5730296417Sdim    EVT SrcVT = Src.ShuffleVec.getValueType();
5731296417Sdim
5732296417Sdim    if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5733218893Sdim      continue;
5734296417Sdim
5735296417Sdim    // This stage of the search produces a source with the same element type as
5736296417Sdim    // the original, but with a total width matching the BUILD_VECTOR output.
5737296417Sdim    EVT EltVT = SrcVT.getVectorElementType();
5738296417Sdim    unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5739296417Sdim    EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5740296417Sdim
5741296417Sdim    if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5742296417Sdim      if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5743296417Sdim        return SDValue();
5744296417Sdim      // We can pad out the smaller vector for free, so if it's part of a
5745296417Sdim      // shuffle...
5746296417Sdim      Src.ShuffleVec =
5747296417Sdim          DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5748296417Sdim                      DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5749296417Sdim      continue;
5750218893Sdim    }
5751218893Sdim
5752296417Sdim    if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5753296417Sdim      return SDValue();
5754218893Sdim
5755296417Sdim    if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5756218893Sdim      // Span too large for a VEXT to cope
5757218893Sdim      return SDValue();
5758218893Sdim    }
5759218893Sdim
5760296417Sdim    if (Src.MinElt >= NumSrcElts) {
5761218893Sdim      // The extraction can just take the second half
5762296417Sdim      Src.ShuffleVec =
5763296417Sdim          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5764296417Sdim                      DAG.getConstant(NumSrcElts, dl, MVT::i32));
5765296417Sdim      Src.WindowBase = -NumSrcElts;
5766296417Sdim    } else if (Src.MaxElt < NumSrcElts) {
5767218893Sdim      // The extraction can just take the first half
5768296417Sdim      Src.ShuffleVec =
5769296417Sdim          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5770296417Sdim                      DAG.getConstant(0, dl, MVT::i32));
5771218893Sdim    } else {
5772218893Sdim      // An actual VEXT is needed
5773296417Sdim      SDValue VEXTSrc1 =
5774296417Sdim          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5775296417Sdim                      DAG.getConstant(0, dl, MVT::i32));
5776296417Sdim      SDValue VEXTSrc2 =
5777296417Sdim          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5778296417Sdim                      DAG.getConstant(NumSrcElts, dl, MVT::i32));
5779296417Sdim
5780296417Sdim      Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5781296417Sdim                                   VEXTSrc2,
5782296417Sdim                                   DAG.getConstant(Src.MinElt, dl, MVT::i32));
5783296417Sdim      Src.WindowBase = -Src.MinElt;
5784218893Sdim    }
5785218893Sdim  }
5786218893Sdim
5787296417Sdim  // Another possible incompatibility occurs from the vector element types. We
5788296417Sdim  // can fix this by bitcasting the source vectors to the same type we intend
5789296417Sdim  // for the shuffle.
5790296417Sdim  for (auto &Src : Sources) {
5791296417Sdim    EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5792296417Sdim    if (SrcEltTy == SmallestEltTy)
5793296417Sdim      continue;
5794296417Sdim    assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5795296417Sdim    Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5796296417Sdim    Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5797296417Sdim    Src.WindowBase *= Src.WindowScale;
5798296417Sdim  }
5799218893Sdim
5800296417Sdim  // Final sanity check before we try to actually produce a shuffle.
5801296417Sdim  DEBUG(
5802296417Sdim    for (auto Src : Sources)
5803296417Sdim      assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5804296417Sdim  );
5805296417Sdim
5806296417Sdim  // The stars all align, our next step is to produce the mask for the shuffle.
5807296417Sdim  SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5808296417Sdim  int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5809296417Sdim  for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5810218893Sdim    SDValue Entry = Op.getOperand(i);
5811296417Sdim    if (Entry.getOpcode() == ISD::UNDEF)
5812218893Sdim      continue;
5813218893Sdim
5814296417Sdim    auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5815296417Sdim    int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5816296417Sdim
5817296417Sdim    // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5818296417Sdim    // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5819296417Sdim    // segment.
5820296417Sdim    EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5821296417Sdim    int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5822296417Sdim                               VT.getVectorElementType().getSizeInBits());
5823296417Sdim    int LanesDefined = BitsDefined / BitsPerShuffleLane;
5824296417Sdim
5825296417Sdim    // This source is expected to fill ResMultiplier lanes of the final shuffle,
5826296417Sdim    // starting at the appropriate offset.
5827296417Sdim    int *LaneMask = &Mask[i * ResMultiplier];
5828296417Sdim
5829296417Sdim    int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5830296417Sdim    ExtractBase += NumElts * (Src - Sources.begin());
5831296417Sdim    for (int j = 0; j < LanesDefined; ++j)
5832296417Sdim      LaneMask[j] = ExtractBase + j;
5833218893Sdim  }
5834218893Sdim
5835218893Sdim  // Final check before we try to produce nonsense...
5836296417Sdim  if (!isShuffleMaskLegal(Mask, ShuffleVT))
5837296417Sdim    return SDValue();
5838218893Sdim
5839296417Sdim  // We can't handle more than two sources. This should have already
5840296417Sdim  // been checked before this point.
5841296417Sdim  assert(Sources.size() <= 2 && "Too many sources!");
5842296417Sdim
5843296417Sdim  SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5844296417Sdim  for (unsigned i = 0; i < Sources.size(); ++i)
5845296417Sdim    ShuffleOps[i] = Sources[i].ShuffleVec;
5846296417Sdim
5847296417Sdim  SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5848296417Sdim                                         ShuffleOps[1], &Mask[0]);
5849296417Sdim  return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5850218893Sdim}
5851218893Sdim
5852198090Srdivacky/// isShuffleMaskLegal - Targets can use this to indicate that they only
5853198090Srdivacky/// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5854198090Srdivacky/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5855198090Srdivacky/// are assumed to be legal.
5856198090Srdivackybool
5857198090SrdivackyARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5858198090Srdivacky                                      EVT VT) const {
5859198090Srdivacky  if (VT.getVectorNumElements() == 4 &&
5860198090Srdivacky      (VT.is128BitVector() || VT.is64BitVector())) {
5861198090Srdivacky    unsigned PFIndexes[4];
5862198090Srdivacky    for (unsigned i = 0; i != 4; ++i) {
5863198090Srdivacky      if (M[i] < 0)
5864198090Srdivacky        PFIndexes[i] = 8;
5865198090Srdivacky      else
5866198090Srdivacky        PFIndexes[i] = M[i];
5867198090Srdivacky    }
5868198090Srdivacky
5869198090Srdivacky    // Compute the index in the perfect shuffle table.
5870198090Srdivacky    unsigned PFTableIndex =
5871198090Srdivacky      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5872198090Srdivacky    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5873198090Srdivacky    unsigned Cost = (PFEntry >> 30);
5874198090Srdivacky
5875198090Srdivacky    if (Cost <= 4)
5876198090Srdivacky      return true;
5877198090Srdivacky  }
5878198090Srdivacky
5879288943Sdim  bool ReverseVEXT, isV_UNDEF;
5880198090Srdivacky  unsigned Imm, WhichResult;
5881198090Srdivacky
5882210299Sed  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5883210299Sed  return (EltSize >= 32 ||
5884210299Sed          ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5885198090Srdivacky          isVREVMask(M, VT, 64) ||
5886198090Srdivacky          isVREVMask(M, VT, 32) ||
5887198090Srdivacky          isVREVMask(M, VT, 16) ||
5888198090Srdivacky          isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5889221345Sdim          isVTBLMask(M, VT) ||
5890288943Sdim          isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5891249423Sdim          ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5892194710Sed}
5893194710Sed
5894198090Srdivacky/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5895198090Srdivacky/// the specified operations to build the shuffle.
5896198090Srdivackystatic SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5897198090Srdivacky                                      SDValue RHS, SelectionDAG &DAG,
5898261991Sdim                                      SDLoc dl) {
5899198090Srdivacky  unsigned OpNum = (PFEntry >> 26) & 0x0F;
5900198090Srdivacky  unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5901198090Srdivacky  unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5902198090Srdivacky
5903198090Srdivacky  enum {
5904198090Srdivacky    OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5905198090Srdivacky    OP_VREV,
5906198090Srdivacky    OP_VDUP0,
5907198090Srdivacky    OP_VDUP1,
5908198090Srdivacky    OP_VDUP2,
5909198090Srdivacky    OP_VDUP3,
5910198090Srdivacky    OP_VEXT1,
5911198090Srdivacky    OP_VEXT2,
5912198090Srdivacky    OP_VEXT3,
5913198090Srdivacky    OP_VUZPL, // VUZP, left result
5914198090Srdivacky    OP_VUZPR, // VUZP, right result
5915198090Srdivacky    OP_VZIPL, // VZIP, left result
5916198090Srdivacky    OP_VZIPR, // VZIP, right result
5917198090Srdivacky    OP_VTRNL, // VTRN, left result
5918198090Srdivacky    OP_VTRNR  // VTRN, right result
5919198090Srdivacky  };
5920198090Srdivacky
5921198090Srdivacky  if (OpNum == OP_COPY) {
5922198090Srdivacky    if (LHSID == (1*9+2)*9+3) return LHS;
5923198090Srdivacky    assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5924198090Srdivacky    return RHS;
5925198090Srdivacky  }
5926198090Srdivacky
5927198090Srdivacky  SDValue OpLHS, OpRHS;
5928198090Srdivacky  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5929198090Srdivacky  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5930198090Srdivacky  EVT VT = OpLHS.getValueType();
5931198090Srdivacky
5932198090Srdivacky  switch (OpNum) {
5933198090Srdivacky  default: llvm_unreachable("Unknown shuffle opcode!");
5934198090Srdivacky  case OP_VREV:
5935223017Sdim    // VREV divides the vector in half and swaps within the half.
5936223017Sdim    if (VT.getVectorElementType() == MVT::i32 ||
5937223017Sdim        VT.getVectorElementType() == MVT::f32)
5938223017Sdim      return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5939223017Sdim    // vrev <4 x i16> -> VREV32
5940223017Sdim    if (VT.getVectorElementType() == MVT::i16)
5941223017Sdim      return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5942223017Sdim    // vrev <4 x i8> -> VREV16
5943223017Sdim    assert(VT.getVectorElementType() == MVT::i8);
5944223017Sdim    return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5945198090Srdivacky  case OP_VDUP0:
5946198090Srdivacky  case OP_VDUP1:
5947198090Srdivacky  case OP_VDUP2:
5948198090Srdivacky  case OP_VDUP3:
5949198090Srdivacky    return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5950288943Sdim                       OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5951198090Srdivacky  case OP_VEXT1:
5952198090Srdivacky  case OP_VEXT2:
5953198090Srdivacky  case OP_VEXT3:
5954198090Srdivacky    return DAG.getNode(ARMISD::VEXT, dl, VT,
5955198090Srdivacky                       OpLHS, OpRHS,
5956288943Sdim                       DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5957198090Srdivacky  case OP_VUZPL:
5958198090Srdivacky  case OP_VUZPR:
5959198090Srdivacky    return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5960198090Srdivacky                       OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5961198090Srdivacky  case OP_VZIPL:
5962198090Srdivacky  case OP_VZIPR:
5963198090Srdivacky    return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5964198090Srdivacky                       OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5965198090Srdivacky  case OP_VTRNL:
5966198090Srdivacky  case OP_VTRNR:
5967198090Srdivacky    return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5968198090Srdivacky                       OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5969198090Srdivacky  }
5970194710Sed}
5971194710Sed
5972221345Sdimstatic SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5973234353Sdim                                       ArrayRef<int> ShuffleMask,
5974221345Sdim                                       SelectionDAG &DAG) {
5975221345Sdim  // Check to see if we can use the VTBL instruction.
5976221345Sdim  SDValue V1 = Op.getOperand(0);
5977221345Sdim  SDValue V2 = Op.getOperand(1);
5978261991Sdim  SDLoc DL(Op);
5979221345Sdim
5980221345Sdim  SmallVector<SDValue, 8> VTBLMask;
5981234353Sdim  for (ArrayRef<int>::iterator
5982221345Sdim         I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5983288943Sdim    VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5984221345Sdim
5985221345Sdim  if (V2.getNode()->getOpcode() == ISD::UNDEF)
5986221345Sdim    return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5987276479Sdim                       DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5988221345Sdim
5989221345Sdim  return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5990276479Sdim                     DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5991221345Sdim}
5992221345Sdim
5993249423Sdimstatic SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5994249423Sdim                                                      SelectionDAG &DAG) {
5995261991Sdim  SDLoc DL(Op);
5996249423Sdim  SDValue OpLHS = Op.getOperand(0);
5997249423Sdim  EVT VT = OpLHS.getValueType();
5998249423Sdim
5999249423Sdim  assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6000249423Sdim         "Expect an v8i16/v16i8 type");
6001249423Sdim  OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6002249423Sdim  // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6003249423Sdim  // extract the first 8 bytes into the top double word and the last 8 bytes
6004249423Sdim  // into the bottom double word. The v8i16 case is similar.
6005249423Sdim  unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6006249423Sdim  return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6007288943Sdim                     DAG.getConstant(ExtractNum, DL, MVT::i32));
6008249423Sdim}
6009249423Sdim
6010198090Srdivackystatic SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6011198090Srdivacky  SDValue V1 = Op.getOperand(0);
6012198090Srdivacky  SDValue V2 = Op.getOperand(1);
6013261991Sdim  SDLoc dl(Op);
6014198090Srdivacky  EVT VT = Op.getValueType();
6015198090Srdivacky  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6016198090Srdivacky
6017198090Srdivacky  // Convert shuffles that are directly supported on NEON to target-specific
6018198090Srdivacky  // DAG nodes, instead of keeping them as shuffles and matching them again
6019198090Srdivacky  // during code selection.  This is more efficient and avoids the possibility
6020198090Srdivacky  // of inconsistencies between legalization and selection.
6021198090Srdivacky  // FIXME: floating-point vectors should be canonicalized to integer vectors
6022198090Srdivacky  // of the same time so that they get CSEd properly.
6023234353Sdim  ArrayRef<int> ShuffleMask = SVN->getMask();
6024198090Srdivacky
6025210299Sed  unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6026210299Sed  if (EltSize <= 32) {
6027210299Sed    if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
6028210299Sed      int Lane = SVN->getSplatIndex();
6029210299Sed      // If this is undef splat, generate it via "just" vdup, if possible.
6030210299Sed      if (Lane == -1) Lane = 0;
6031198892Srdivacky
6032234353Sdim      // Test if V1 is a SCALAR_TO_VECTOR.
6033210299Sed      if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6034210299Sed        return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6035210299Sed      }
6036234353Sdim      // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6037234353Sdim      // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6038234353Sdim      // reaches it).
6039234353Sdim      if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6040234353Sdim          !isa<ConstantSDNode>(V1.getOperand(0))) {
6041234353Sdim        bool IsScalarToVector = true;
6042234353Sdim        for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6043234353Sdim          if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
6044234353Sdim            IsScalarToVector = false;
6045234353Sdim            break;
6046234353Sdim          }
6047234353Sdim        if (IsScalarToVector)
6048234353Sdim          return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6049234353Sdim      }
6050210299Sed      return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6051288943Sdim                         DAG.getConstant(Lane, dl, MVT::i32));
6052198090Srdivacky    }
6053198090Srdivacky
6054210299Sed    bool ReverseVEXT;
6055210299Sed    unsigned Imm;
6056210299Sed    if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6057210299Sed      if (ReverseVEXT)
6058210299Sed        std::swap(V1, V2);
6059210299Sed      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6060288943Sdim                         DAG.getConstant(Imm, dl, MVT::i32));
6061210299Sed    }
6062198090Srdivacky
6063210299Sed    if (isVREVMask(ShuffleMask, VT, 64))
6064210299Sed      return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6065210299Sed    if (isVREVMask(ShuffleMask, VT, 32))
6066210299Sed      return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6067210299Sed    if (isVREVMask(ShuffleMask, VT, 16))
6068210299Sed      return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6069198090Srdivacky
6070243830Sdim    if (V2->getOpcode() == ISD::UNDEF &&
6071243830Sdim        isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6072243830Sdim      return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6073288943Sdim                         DAG.getConstant(Imm, dl, MVT::i32));
6074243830Sdim    }
6075243830Sdim
6076210299Sed    // Check for Neon shuffles that modify both input vectors in place.
6077210299Sed    // If both results are used, i.e., if there are two shuffles with the same
6078210299Sed    // source operands and with masks corresponding to both results of one of
6079210299Sed    // these operations, DAG memoization will ensure that a single node is
6080210299Sed    // used for both shuffles.
6081210299Sed    unsigned WhichResult;
6082288943Sdim    bool isV_UNDEF;
6083288943Sdim    if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6084288943Sdim            ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6085288943Sdim      if (isV_UNDEF)
6086288943Sdim        V2 = V1;
6087288943Sdim      return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6088288943Sdim          .getValue(WhichResult);
6089288943Sdim    }
6090198090Srdivacky
6091288943Sdim    // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6092288943Sdim    // shuffles that produce a result larger than their operands with:
6093288943Sdim    //   shuffle(concat(v1, undef), concat(v2, undef))
6094288943Sdim    // ->
6095288943Sdim    //   shuffle(concat(v1, v2), undef)
6096288943Sdim    // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6097288943Sdim    //
6098288943Sdim    // This is useful in the general case, but there are special cases where
6099288943Sdim    // native shuffles produce larger results: the two-result ops.
6100288943Sdim    //
6101288943Sdim    // Look through the concat when lowering them:
6102288943Sdim    //   shuffle(concat(v1, v2), undef)
6103288943Sdim    // ->
6104288943Sdim    //   concat(VZIP(v1, v2):0, :1)
6105288943Sdim    //
6106288943Sdim    if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6107288943Sdim        V2->getOpcode() == ISD::UNDEF) {
6108288943Sdim      SDValue SubV1 = V1->getOperand(0);
6109288943Sdim      SDValue SubV2 = V1->getOperand(1);
6110288943Sdim      EVT SubVT = SubV1.getValueType();
6111288943Sdim
6112288943Sdim      // We expect these to have been canonicalized to -1.
6113288943Sdim      assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6114288943Sdim        return i < (int)VT.getVectorNumElements();
6115288943Sdim      }) && "Unexpected shuffle index into UNDEF operand!");
6116288943Sdim
6117288943Sdim      if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6118288943Sdim              ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6119288943Sdim        if (isV_UNDEF)
6120288943Sdim          SubV2 = SubV1;
6121288943Sdim        assert((WhichResult == 0) &&
6122288943Sdim               "In-place shuffle of concat can only have one result!");
6123288943Sdim        SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6124288943Sdim                                  SubV1, SubV2);
6125288943Sdim        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6126288943Sdim                           Res.getValue(1));
6127288943Sdim      }
6128288943Sdim    }
6129210299Sed  }
6130200581Srdivacky
6131198090Srdivacky  // If the shuffle is not directly supported and it has 4 elements, use
6132198090Srdivacky  // the PerfectShuffle-generated table to synthesize it from other shuffles.
6133208599Srdivacky  unsigned NumElts = VT.getVectorNumElements();
6134208599Srdivacky  if (NumElts == 4) {
6135198090Srdivacky    unsigned PFIndexes[4];
6136198090Srdivacky    for (unsigned i = 0; i != 4; ++i) {
6137198090Srdivacky      if (ShuffleMask[i] < 0)
6138198090Srdivacky        PFIndexes[i] = 8;
6139198090Srdivacky      else
6140198090Srdivacky        PFIndexes[i] = ShuffleMask[i];
6141198090Srdivacky    }
6142198090Srdivacky
6143198090Srdivacky    // Compute the index in the perfect shuffle table.
6144198090Srdivacky    unsigned PFTableIndex =
6145198090Srdivacky      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6146198090Srdivacky    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6147198090Srdivacky    unsigned Cost = (PFEntry >> 30);
6148198090Srdivacky
6149198090Srdivacky    if (Cost <= 4)
6150198090Srdivacky      return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6151198090Srdivacky  }
6152198090Srdivacky
6153210299Sed  // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6154208599Srdivacky  if (EltSize >= 32) {
6155208599Srdivacky    // Do the expansion with floating-point types, since that is what the VFP
6156208599Srdivacky    // registers are defined to use, and since i64 is not legal.
6157208599Srdivacky    EVT EltVT = EVT::getFloatingPointVT(EltSize);
6158208599Srdivacky    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6159218893Sdim    V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6160218893Sdim    V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6161210299Sed    SmallVector<SDValue, 8> Ops;
6162208599Srdivacky    for (unsigned i = 0; i < NumElts; ++i) {
6163208599Srdivacky      if (ShuffleMask[i] < 0)
6164210299Sed        Ops.push_back(DAG.getUNDEF(EltVT));
6165210299Sed      else
6166210299Sed        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6167210299Sed                                  ShuffleMask[i] < (int)NumElts ? V1 : V2,
6168210299Sed                                  DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6169288943Sdim                                                  dl, MVT::i32)));
6170208599Srdivacky    }
6171276479Sdim    SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6172218893Sdim    return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6173208599Srdivacky  }
6174208599Srdivacky
6175249423Sdim  if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6176249423Sdim    return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6177249423Sdim
6178221345Sdim  if (VT == MVT::v8i8) {
6179221345Sdim    SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6180221345Sdim    if (NewOp.getNode())
6181221345Sdim      return NewOp;
6182221345Sdim  }
6183221345Sdim
6184198090Srdivacky  return SDValue();
6185198090Srdivacky}
6186198090Srdivacky
6187234353Sdimstatic SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6188234353Sdim  // INSERT_VECTOR_ELT is legal only for immediate indexes.
6189234353Sdim  SDValue Lane = Op.getOperand(2);
6190234353Sdim  if (!isa<ConstantSDNode>(Lane))
6191234353Sdim    return SDValue();
6192234353Sdim
6193234353Sdim  return Op;
6194234353Sdim}
6195234353Sdim
6196194710Sedstatic SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6197218893Sdim  // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6198218893Sdim  SDValue Lane = Op.getOperand(1);
6199218893Sdim  if (!isa<ConstantSDNode>(Lane))
6200218893Sdim    return SDValue();
6201218893Sdim
6202194710Sed  SDValue Vec = Op.getOperand(0);
6203218893Sdim  if (Op.getValueType() == MVT::i32 &&
6204218893Sdim      Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6205261991Sdim    SDLoc dl(Op);
6206218893Sdim    return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6207218893Sdim  }
6208218893Sdim
6209218893Sdim  return Op;
6210194710Sed}
6211194710Sed
6212198090Srdivackystatic SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6213198090Srdivacky  // The only time a CONCAT_VECTORS operation can have legal types is when
6214198090Srdivacky  // two 64-bit vectors are concatenated to a 128-bit vector.
6215198090Srdivacky  assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6216198090Srdivacky         "unexpected CONCAT_VECTORS");
6217261991Sdim  SDLoc dl(Op);
6218198090Srdivacky  SDValue Val = DAG.getUNDEF(MVT::v2f64);
6219198090Srdivacky  SDValue Op0 = Op.getOperand(0);
6220198090Srdivacky  SDValue Op1 = Op.getOperand(1);
6221198090Srdivacky  if (Op0.getOpcode() != ISD::UNDEF)
6222198090Srdivacky    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6223218893Sdim                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6224288943Sdim                      DAG.getIntPtrConstant(0, dl));
6225198090Srdivacky  if (Op1.getOpcode() != ISD::UNDEF)
6226198090Srdivacky    Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6227218893Sdim                      DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6228288943Sdim                      DAG.getIntPtrConstant(1, dl));
6229218893Sdim  return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6230194710Sed}
6231194710Sed
6232218893Sdim/// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6233218893Sdim/// element has been zero/sign-extended, depending on the isSigned parameter,
6234218893Sdim/// from an integer type half its size.
6235218893Sdimstatic bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6236218893Sdim                                   bool isSigned) {
6237218893Sdim  // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6238218893Sdim  EVT VT = N->getValueType(0);
6239218893Sdim  if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6240218893Sdim    SDNode *BVN = N->getOperand(0).getNode();
6241218893Sdim    if (BVN->getValueType(0) != MVT::v4i32 ||
6242218893Sdim        BVN->getOpcode() != ISD::BUILD_VECTOR)
6243218893Sdim      return false;
6244288943Sdim    unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6245218893Sdim    unsigned HiElt = 1 - LoElt;
6246218893Sdim    ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6247218893Sdim    ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6248218893Sdim    ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6249218893Sdim    ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6250218893Sdim    if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6251218893Sdim      return false;
6252218893Sdim    if (isSigned) {
6253218893Sdim      if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6254218893Sdim          Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6255218893Sdim        return true;
6256218893Sdim    } else {
6257218893Sdim      if (Hi0->isNullValue() && Hi1->isNullValue())
6258218893Sdim        return true;
6259218893Sdim    }
6260218893Sdim    return false;
6261218893Sdim  }
6262218893Sdim
6263218893Sdim  if (N->getOpcode() != ISD::BUILD_VECTOR)
6264218893Sdim    return false;
6265218893Sdim
6266218893Sdim  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6267218893Sdim    SDNode *Elt = N->getOperand(i).getNode();
6268218893Sdim    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6269218893Sdim      unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6270218893Sdim      unsigned HalfSize = EltSize / 2;
6271218893Sdim      if (isSigned) {
6272234353Sdim        if (!isIntN(HalfSize, C->getSExtValue()))
6273218893Sdim          return false;
6274218893Sdim      } else {
6275234353Sdim        if (!isUIntN(HalfSize, C->getZExtValue()))
6276218893Sdim          return false;
6277218893Sdim      }
6278218893Sdim      continue;
6279218893Sdim    }
6280218893Sdim    return false;
6281218893Sdim  }
6282218893Sdim
6283218893Sdim  return true;
6284218893Sdim}
6285218893Sdim
6286218893Sdim/// isSignExtended - Check if a node is a vector value that is sign-extended
6287218893Sdim/// or a constant BUILD_VECTOR with sign-extended elements.
6288218893Sdimstatic bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6289218893Sdim  if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6290218893Sdim    return true;
6291218893Sdim  if (isExtendedBUILD_VECTOR(N, DAG, true))
6292218893Sdim    return true;
6293218893Sdim  return false;
6294218893Sdim}
6295218893Sdim
6296218893Sdim/// isZeroExtended - Check if a node is a vector value that is zero-extended
6297218893Sdim/// or a constant BUILD_VECTOR with zero-extended elements.
6298218893Sdimstatic bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6299218893Sdim  if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6300218893Sdim    return true;
6301218893Sdim  if (isExtendedBUILD_VECTOR(N, DAG, false))
6302218893Sdim    return true;
6303218893Sdim  return false;
6304218893Sdim}
6305218893Sdim
6306251662Sdimstatic EVT getExtensionTo64Bits(const EVT &OrigVT) {
6307251662Sdim  if (OrigVT.getSizeInBits() >= 64)
6308251662Sdim    return OrigVT;
6309251662Sdim
6310251662Sdim  assert(OrigVT.isSimple() && "Expecting a simple value type");
6311251662Sdim
6312251662Sdim  MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6313251662Sdim  switch (OrigSimpleTy) {
6314251662Sdim  default: llvm_unreachable("Unexpected Vector Type");
6315251662Sdim  case MVT::v2i8:
6316251662Sdim  case MVT::v2i16:
6317251662Sdim     return MVT::v2i32;
6318251662Sdim  case MVT::v4i8:
6319251662Sdim    return  MVT::v4i16;
6320251662Sdim  }
6321251662Sdim}
6322251662Sdim
6323249423Sdim/// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6324249423Sdim/// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6325249423Sdim/// We insert the required extension here to get the vector to fill a D register.
6326249423Sdimstatic SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6327249423Sdim                                            const EVT &OrigTy,
6328249423Sdim                                            const EVT &ExtTy,
6329249423Sdim                                            unsigned ExtOpcode) {
6330249423Sdim  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6331249423Sdim  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6332249423Sdim  // 64-bits we need to insert a new extension so that it will be 64-bits.
6333249423Sdim  assert(ExtTy.is128BitVector() && "Unexpected extension size");
6334249423Sdim  if (OrigTy.getSizeInBits() >= 64)
6335249423Sdim    return N;
6336249423Sdim
6337249423Sdim  // Must extend size to at least 64 bits to be used as an operand for VMULL.
6338251662Sdim  EVT NewVT = getExtensionTo64Bits(OrigTy);
6339251662Sdim
6340261991Sdim  return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6341249423Sdim}
6342249423Sdim
6343249423Sdim/// SkipLoadExtensionForVMULL - return a load of the original vector size that
6344249423Sdim/// does not do any sign/zero extension. If the original vector is less
6345249423Sdim/// than 64 bits, an appropriate extension will be added after the load to
6346249423Sdim/// reach a total size of 64 bits. We have to add the extension separately
6347249423Sdim/// because ARM does not have a sign/zero extending load for vectors.
6348249423Sdimstatic SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6349251662Sdim  EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6350251662Sdim
6351251662Sdim  // The load already has the right type.
6352251662Sdim  if (ExtendedTy == LD->getMemoryVT())
6353261991Sdim    return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6354249423Sdim                LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6355249423Sdim                LD->isNonTemporal(), LD->isInvariant(),
6356249423Sdim                LD->getAlignment());
6357251662Sdim
6358251662Sdim  // We need to create a zextload/sextload. We cannot just create a load
6359251662Sdim  // followed by a zext/zext node because LowerMUL is also run during normal
6360251662Sdim  // operation legalization where we can't create illegal types.
6361261991Sdim  return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6362251662Sdim                        LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6363280031Sdim                        LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6364251662Sdim                        LD->isNonTemporal(), LD->getAlignment());
6365249423Sdim}
6366249423Sdim
6367249423Sdim/// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6368249423Sdim/// extending load, or BUILD_VECTOR with extended elements, return the
6369249423Sdim/// unextended value. The unextended vector should be 64 bits so that it can
6370249423Sdim/// be used as an operand to a VMULL instruction. If the original vector size
6371249423Sdim/// before extension is less than 64 bits we add a an extension to resize
6372249423Sdim/// the vector to 64 bits.
6373249423Sdimstatic SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6374212904Sdim  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6375249423Sdim    return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6376249423Sdim                                        N->getOperand(0)->getValueType(0),
6377249423Sdim                                        N->getValueType(0),
6378249423Sdim                                        N->getOpcode());
6379249423Sdim
6380218893Sdim  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6381249423Sdim    return SkipLoadExtensionForVMULL(LD, DAG);
6382249423Sdim
6383218893Sdim  // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6384218893Sdim  // have been legalized as a BITCAST from v4i32.
6385218893Sdim  if (N->getOpcode() == ISD::BITCAST) {
6386218893Sdim    SDNode *BVN = N->getOperand(0).getNode();
6387218893Sdim    assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6388218893Sdim           BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6389288943Sdim    unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6390261991Sdim    return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6391218893Sdim                       BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6392218893Sdim  }
6393218893Sdim  // Construct a new BUILD_VECTOR with elements truncated to half the size.
6394218893Sdim  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6395218893Sdim  EVT VT = N->getValueType(0);
6396218893Sdim  unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6397218893Sdim  unsigned NumElts = VT.getVectorNumElements();
6398218893Sdim  MVT TruncVT = MVT::getIntegerVT(EltSize);
6399218893Sdim  SmallVector<SDValue, 8> Ops;
6400288943Sdim  SDLoc dl(N);
6401218893Sdim  for (unsigned i = 0; i != NumElts; ++i) {
6402218893Sdim    ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6403218893Sdim    const APInt &CInt = C->getAPIntValue();
6404239462Sdim    // Element types smaller than 32 bits are not legal, so use i32 elements.
6405239462Sdim    // The values are implicitly truncated so sext vs. zext doesn't matter.
6406288943Sdim    Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6407218893Sdim  }
6408288943Sdim  return DAG.getNode(ISD::BUILD_VECTOR, dl,
6409276479Sdim                     MVT::getVectorVT(TruncVT, NumElts), Ops);
6410212904Sdim}
6411212904Sdim
6412221345Sdimstatic bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6413221345Sdim  unsigned Opcode = N->getOpcode();
6414221345Sdim  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6415221345Sdim    SDNode *N0 = N->getOperand(0).getNode();
6416221345Sdim    SDNode *N1 = N->getOperand(1).getNode();
6417221345Sdim    return N0->hasOneUse() && N1->hasOneUse() &&
6418221345Sdim      isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6419221345Sdim  }
6420221345Sdim  return false;
6421221345Sdim}
6422221345Sdim
6423221345Sdimstatic bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6424221345Sdim  unsigned Opcode = N->getOpcode();
6425221345Sdim  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6426221345Sdim    SDNode *N0 = N->getOperand(0).getNode();
6427221345Sdim    SDNode *N1 = N->getOperand(1).getNode();
6428221345Sdim    return N0->hasOneUse() && N1->hasOneUse() &&
6429221345Sdim      isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6430221345Sdim  }
6431221345Sdim  return false;
6432221345Sdim}
6433221345Sdim
6434212904Sdimstatic SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6435212904Sdim  // Multiplications are only custom-lowered for 128-bit vectors so that
6436212904Sdim  // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6437212904Sdim  EVT VT = Op.getValueType();
6438249423Sdim  assert(VT.is128BitVector() && VT.isInteger() &&
6439249423Sdim         "unexpected type for custom-lowering ISD::MUL");
6440212904Sdim  SDNode *N0 = Op.getOperand(0).getNode();
6441212904Sdim  SDNode *N1 = Op.getOperand(1).getNode();
6442212904Sdim  unsigned NewOpc = 0;
6443221345Sdim  bool isMLA = false;
6444221345Sdim  bool isN0SExt = isSignExtended(N0, DAG);
6445221345Sdim  bool isN1SExt = isSignExtended(N1, DAG);
6446221345Sdim  if (isN0SExt && isN1SExt)
6447212904Sdim    NewOpc = ARMISD::VMULLs;
6448221345Sdim  else {
6449221345Sdim    bool isN0ZExt = isZeroExtended(N0, DAG);
6450221345Sdim    bool isN1ZExt = isZeroExtended(N1, DAG);
6451221345Sdim    if (isN0ZExt && isN1ZExt)
6452221345Sdim      NewOpc = ARMISD::VMULLu;
6453221345Sdim    else if (isN1SExt || isN1ZExt) {
6454221345Sdim      // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6455221345Sdim      // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6456221345Sdim      if (isN1SExt && isAddSubSExt(N0, DAG)) {
6457221345Sdim        NewOpc = ARMISD::VMULLs;
6458221345Sdim        isMLA = true;
6459221345Sdim      } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6460221345Sdim        NewOpc = ARMISD::VMULLu;
6461221345Sdim        isMLA = true;
6462221345Sdim      } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6463221345Sdim        std::swap(N0, N1);
6464221345Sdim        NewOpc = ARMISD::VMULLu;
6465221345Sdim        isMLA = true;
6466221345Sdim      }
6467221345Sdim    }
6468212904Sdim
6469221345Sdim    if (!NewOpc) {
6470221345Sdim      if (VT == MVT::v2i64)
6471221345Sdim        // Fall through to expand this.  It is not legal.
6472221345Sdim        return SDValue();
6473221345Sdim      else
6474221345Sdim        // Other vector multiplications are legal.
6475221345Sdim        return Op;
6476221345Sdim    }
6477221345Sdim  }
6478221345Sdim
6479212904Sdim  // Legalize to a VMULL instruction.
6480261991Sdim  SDLoc DL(Op);
6481221345Sdim  SDValue Op0;
6482249423Sdim  SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6483221345Sdim  if (!isMLA) {
6484249423Sdim    Op0 = SkipExtensionForVMULL(N0, DAG);
6485221345Sdim    assert(Op0.getValueType().is64BitVector() &&
6486221345Sdim           Op1.getValueType().is64BitVector() &&
6487221345Sdim           "unexpected types for extended operands to VMULL");
6488221345Sdim    return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6489221345Sdim  }
6490212904Sdim
6491221345Sdim  // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6492221345Sdim  // isel lowering to take advantage of no-stall back to back vmul + vmla.
6493221345Sdim  //   vmull q0, d4, d6
6494221345Sdim  //   vmlal q0, d5, d6
6495221345Sdim  // is faster than
6496221345Sdim  //   vaddl q0, d4, d5
6497221345Sdim  //   vmovl q1, d6
6498221345Sdim  //   vmul  q0, q0, q1
6499249423Sdim  SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6500249423Sdim  SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6501221345Sdim  EVT Op1VT = Op1.getValueType();
6502221345Sdim  return DAG.getNode(N0->getOpcode(), DL, VT,
6503221345Sdim                     DAG.getNode(NewOpc, DL, VT,
6504221345Sdim                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6505221345Sdim                     DAG.getNode(NewOpc, DL, VT,
6506221345Sdim                               DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6507212904Sdim}
6508212904Sdim
6509221345Sdimstatic SDValue
6510261991SdimLowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6511296417Sdim  // TODO: Should this propagate fast-math-flags?
6512296417Sdim
6513218893Sdim  // Convert to float
6514218893Sdim  // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6515218893Sdim  // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6516218893Sdim  X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6517218893Sdim  Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6518218893Sdim  X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6519218893Sdim  Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6520218893Sdim  // Get reciprocal estimate.
6521218893Sdim  // float4 recip = vrecpeq_f32(yf);
6522221345Sdim  Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6523288943Sdim                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6524288943Sdim                   Y);
6525218893Sdim  // Because char has a smaller range than uchar, we can actually get away
6526218893Sdim  // without any newton steps.  This requires that we use a weird bias
6527218893Sdim  // of 0xb000, however (again, this has been exhaustively tested).
6528218893Sdim  // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6529218893Sdim  X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6530218893Sdim  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6531288943Sdim  Y = DAG.getConstant(0xb000, dl, MVT::i32);
6532218893Sdim  Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6533218893Sdim  X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6534218893Sdim  X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6535218893Sdim  // Convert back to short.
6536218893Sdim  X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6537218893Sdim  X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6538218893Sdim  return X;
6539218893Sdim}
6540218893Sdim
6541221345Sdimstatic SDValue
6542261991SdimLowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6543296417Sdim  // TODO: Should this propagate fast-math-flags?
6544296417Sdim
6545218893Sdim  SDValue N2;
6546218893Sdim  // Convert to float.
6547218893Sdim  // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6548218893Sdim  // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6549218893Sdim  N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6550218893Sdim  N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6551218893Sdim  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6552218893Sdim  N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6553221345Sdim
6554218893Sdim  // Use reciprocal estimate and one refinement step.
6555218893Sdim  // float4 recip = vrecpeq_f32(yf);
6556218893Sdim  // recip *= vrecpsq_f32(yf, recip);
6557221345Sdim  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6558288943Sdim                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6559288943Sdim                   N1);
6560221345Sdim  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6561288943Sdim                   DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6562218893Sdim                   N1, N2);
6563218893Sdim  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6564218893Sdim  // Because short has a smaller range than ushort, we can actually get away
6565218893Sdim  // with only a single newton step.  This requires that we use a weird bias
6566218893Sdim  // of 89, however (again, this has been exhaustively tested).
6567223017Sdim  // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6568218893Sdim  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6569218893Sdim  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6570288943Sdim  N1 = DAG.getConstant(0x89, dl, MVT::i32);
6571218893Sdim  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6572218893Sdim  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6573218893Sdim  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6574218893Sdim  // Convert back to integer and return.
6575218893Sdim  // return vmovn_s32(vcvt_s32_f32(result));
6576218893Sdim  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6577218893Sdim  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6578218893Sdim  return N0;
6579218893Sdim}
6580218893Sdim
6581218893Sdimstatic SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6582218893Sdim  EVT VT = Op.getValueType();
6583218893Sdim  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6584218893Sdim         "unexpected type for custom-lowering ISD::SDIV");
6585218893Sdim
6586261991Sdim  SDLoc dl(Op);
6587218893Sdim  SDValue N0 = Op.getOperand(0);
6588218893Sdim  SDValue N1 = Op.getOperand(1);
6589218893Sdim  SDValue N2, N3;
6590221345Sdim
6591218893Sdim  if (VT == MVT::v8i8) {
6592218893Sdim    N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6593218893Sdim    N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6594221345Sdim
6595218893Sdim    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6596288943Sdim                     DAG.getIntPtrConstant(4, dl));
6597218893Sdim    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6598288943Sdim                     DAG.getIntPtrConstant(4, dl));
6599218893Sdim    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6600288943Sdim                     DAG.getIntPtrConstant(0, dl));
6601218893Sdim    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6602288943Sdim                     DAG.getIntPtrConstant(0, dl));
6603218893Sdim
6604218893Sdim    N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6605218893Sdim    N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6606218893Sdim
6607218893Sdim    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6608218893Sdim    N0 = LowerCONCAT_VECTORS(N0, DAG);
6609221345Sdim
6610218893Sdim    N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6611218893Sdim    return N0;
6612218893Sdim  }
6613218893Sdim  return LowerSDIV_v4i16(N0, N1, dl, DAG);
6614218893Sdim}
6615218893Sdim
6616218893Sdimstatic SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6617296417Sdim  // TODO: Should this propagate fast-math-flags?
6618218893Sdim  EVT VT = Op.getValueType();
6619218893Sdim  assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6620218893Sdim         "unexpected type for custom-lowering ISD::UDIV");
6621218893Sdim
6622261991Sdim  SDLoc dl(Op);
6623218893Sdim  SDValue N0 = Op.getOperand(0);
6624218893Sdim  SDValue N1 = Op.getOperand(1);
6625218893Sdim  SDValue N2, N3;
6626221345Sdim
6627218893Sdim  if (VT == MVT::v8i8) {
6628218893Sdim    N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6629218893Sdim    N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6630221345Sdim
6631218893Sdim    N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6632288943Sdim                     DAG.getIntPtrConstant(4, dl));
6633218893Sdim    N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6634288943Sdim                     DAG.getIntPtrConstant(4, dl));
6635218893Sdim    N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6636288943Sdim                     DAG.getIntPtrConstant(0, dl));
6637218893Sdim    N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6638288943Sdim                     DAG.getIntPtrConstant(0, dl));
6639221345Sdim
6640218893Sdim    N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6641218893Sdim    N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6642221345Sdim
6643218893Sdim    N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6644218893Sdim    N0 = LowerCONCAT_VECTORS(N0, DAG);
6645221345Sdim
6646221345Sdim    N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6647288943Sdim                     DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6648288943Sdim                                     MVT::i32),
6649218893Sdim                     N0);
6650218893Sdim    return N0;
6651218893Sdim  }
6652221345Sdim
6653218893Sdim  // v4i16 sdiv ... Convert to float.
6654218893Sdim  // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6655218893Sdim  // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6656218893Sdim  N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6657218893Sdim  N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6658218893Sdim  N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6659223017Sdim  SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6660218893Sdim
6661218893Sdim  // Use reciprocal estimate and two refinement steps.
6662218893Sdim  // float4 recip = vrecpeq_f32(yf);
6663218893Sdim  // recip *= vrecpsq_f32(yf, recip);
6664218893Sdim  // recip *= vrecpsq_f32(yf, recip);
6665221345Sdim  N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6666288943Sdim                   DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6667288943Sdim                   BN1);
6668221345Sdim  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6669288943Sdim                   DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6670223017Sdim                   BN1, N2);
6671218893Sdim  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6672221345Sdim  N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6673288943Sdim                   DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6674223017Sdim                   BN1, N2);
6675218893Sdim  N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6676218893Sdim  // Simply multiplying by the reciprocal estimate can leave us a few ulps
6677218893Sdim  // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6678218893Sdim  // and that it will never cause us to return an answer too large).
6679223017Sdim  // float4 result = as_float4(as_int4(xf*recip) + 2);
6680218893Sdim  N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6681218893Sdim  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6682288943Sdim  N1 = DAG.getConstant(2, dl, MVT::i32);
6683218893Sdim  N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6684218893Sdim  N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6685218893Sdim  N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6686218893Sdim  // Convert back to integer and return.
6687218893Sdim  // return vmovn_u32(vcvt_s32_f32(result));
6688218893Sdim  N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6689218893Sdim  N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6690218893Sdim  return N0;
6691218893Sdim}
6692218893Sdim
6693226633Sdimstatic SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6694226633Sdim  EVT VT = Op.getNode()->getValueType(0);
6695226633Sdim  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6696226633Sdim
6697226633Sdim  unsigned Opc;
6698226633Sdim  bool ExtraOp = false;
6699226633Sdim  switch (Op.getOpcode()) {
6700234353Sdim  default: llvm_unreachable("Invalid code");
6701226633Sdim  case ISD::ADDC: Opc = ARMISD::ADDC; break;
6702226633Sdim  case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6703226633Sdim  case ISD::SUBC: Opc = ARMISD::SUBC; break;
6704226633Sdim  case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6705226633Sdim  }
6706226633Sdim
6707226633Sdim  if (!ExtraOp)
6708261991Sdim    return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6709226633Sdim                       Op.getOperand(1));
6710261991Sdim  return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6711226633Sdim                     Op.getOperand(1), Op.getOperand(2));
6712226633Sdim}
6713226633Sdim
6714261991SdimSDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6715261991Sdim  assert(Subtarget->isTargetDarwin());
6716261991Sdim
6717261991Sdim  // For iOS, we want to call an alternative entry point: __sincos_stret,
6718261991Sdim  // return values are passed via sret.
6719261991Sdim  SDLoc dl(Op);
6720261991Sdim  SDValue Arg = Op.getOperand(0);
6721261991Sdim  EVT ArgVT = Arg.getValueType();
6722261991Sdim  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6723288943Sdim  auto PtrVT = getPointerTy(DAG.getDataLayout());
6724261991Sdim
6725261991Sdim  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6726296417Sdim  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6727261991Sdim
6728261991Sdim  // Pair of floats / doubles used to pass the result.
6729296417Sdim  Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6730288943Sdim  auto &DL = DAG.getDataLayout();
6731261991Sdim
6732261991Sdim  ArgListTy Args;
6733296417Sdim  bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6734296417Sdim  SDValue SRet;
6735296417Sdim  if (ShouldUseSRet) {
6736296417Sdim    // Create stack object for sret.
6737296417Sdim    const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6738296417Sdim    const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6739296417Sdim    int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6740296417Sdim    SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6741261991Sdim
6742296417Sdim    ArgListEntry Entry;
6743296417Sdim    Entry.Node = SRet;
6744296417Sdim    Entry.Ty = RetTy->getPointerTo();
6745296417Sdim    Entry.isSExt = false;
6746296417Sdim    Entry.isZExt = false;
6747296417Sdim    Entry.isSRet = true;
6748296417Sdim    Args.push_back(Entry);
6749296417Sdim    RetTy = Type::getVoidTy(*DAG.getContext());
6750296417Sdim  }
6751261991Sdim
6752296417Sdim  ArgListEntry Entry;
6753261991Sdim  Entry.Node = Arg;
6754261991Sdim  Entry.Ty = ArgTy;
6755261991Sdim  Entry.isSExt = false;
6756261991Sdim  Entry.isZExt = false;
6757261991Sdim  Args.push_back(Entry);
6758261991Sdim
6759296417Sdim  const char *LibcallName =
6760296417Sdim      (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6761296417Sdim  RTLIB::Libcall LC =
6762296417Sdim      (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6763296417Sdim  CallingConv::ID CC = getLibcallCallingConv(LC);
6764288943Sdim  SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6765261991Sdim
6766276479Sdim  TargetLowering::CallLoweringInfo CLI(DAG);
6767296417Sdim  CLI.setDebugLoc(dl)
6768296417Sdim      .setChain(DAG.getEntryNode())
6769296417Sdim      .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6770296417Sdim      .setDiscardResult(ShouldUseSRet);
6771261991Sdim  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6772261991Sdim
6773296417Sdim  if (!ShouldUseSRet)
6774296417Sdim    return CallResult.first;
6775296417Sdim
6776261991Sdim  SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6777261991Sdim                                MachinePointerInfo(), false, false, false, 0);
6778261991Sdim
6779261991Sdim  // Address of cos field.
6780288943Sdim  SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6781288943Sdim                            DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6782261991Sdim  SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6783261991Sdim                                MachinePointerInfo(), false, false, false, 0);
6784261991Sdim
6785261991Sdim  SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6786261991Sdim  return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6787261991Sdim                     LoadSin.getValue(0), LoadCos.getValue(0));
6788261991Sdim}
6789261991Sdim
6790296417SdimSDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6791296417Sdim                                                  bool Signed,
6792296417Sdim                                                  SDValue &Chain) const {
6793296417Sdim  EVT VT = Op.getValueType();
6794296417Sdim  assert((VT == MVT::i32 || VT == MVT::i64) &&
6795296417Sdim         "unexpected type for custom lowering DIV");
6796296417Sdim  SDLoc dl(Op);
6797296417Sdim
6798296417Sdim  const auto &DL = DAG.getDataLayout();
6799296417Sdim  const auto &TLI = DAG.getTargetLoweringInfo();
6800296417Sdim
6801296417Sdim  const char *Name = nullptr;
6802296417Sdim  if (Signed)
6803296417Sdim    Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6804296417Sdim  else
6805296417Sdim    Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6806296417Sdim
6807296417Sdim  SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6808296417Sdim
6809296417Sdim  ARMTargetLowering::ArgListTy Args;
6810296417Sdim
6811296417Sdim  for (auto AI : {1, 0}) {
6812296417Sdim    ArgListEntry Arg;
6813296417Sdim    Arg.Node = Op.getOperand(AI);
6814296417Sdim    Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6815296417Sdim    Args.push_back(Arg);
6816296417Sdim  }
6817296417Sdim
6818296417Sdim  CallLoweringInfo CLI(DAG);
6819296417Sdim  CLI.setDebugLoc(dl)
6820296417Sdim    .setChain(Chain)
6821296417Sdim    .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6822296417Sdim               ES, std::move(Args), 0);
6823296417Sdim
6824296417Sdim  return LowerCallTo(CLI).first;
6825296417Sdim}
6826296417Sdim
6827296417SdimSDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6828296417Sdim                                            bool Signed) const {
6829296417Sdim  assert(Op.getValueType() == MVT::i32 &&
6830296417Sdim         "unexpected type for custom lowering DIV");
6831296417Sdim  SDLoc dl(Op);
6832296417Sdim
6833296417Sdim  SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6834296417Sdim                               DAG.getEntryNode(), Op.getOperand(1));
6835296417Sdim
6836296417Sdim  return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6837296417Sdim}
6838296417Sdim
6839296417Sdimvoid ARMTargetLowering::ExpandDIV_Windows(
6840296417Sdim    SDValue Op, SelectionDAG &DAG, bool Signed,
6841296417Sdim    SmallVectorImpl<SDValue> &Results) const {
6842296417Sdim  const auto &DL = DAG.getDataLayout();
6843296417Sdim  const auto &TLI = DAG.getTargetLoweringInfo();
6844296417Sdim
6845296417Sdim  assert(Op.getValueType() == MVT::i64 &&
6846296417Sdim         "unexpected type for custom lowering DIV");
6847296417Sdim  SDLoc dl(Op);
6848296417Sdim
6849296417Sdim  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6850296417Sdim                           DAG.getConstant(0, dl, MVT::i32));
6851296417Sdim  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6852296417Sdim                           DAG.getConstant(1, dl, MVT::i32));
6853296417Sdim  SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6854296417Sdim
6855296417Sdim  SDValue DBZCHK =
6856296417Sdim      DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6857296417Sdim
6858296417Sdim  SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6859296417Sdim
6860296417Sdim  SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6861296417Sdim  SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6862296417Sdim                              DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6863296417Sdim  Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6864296417Sdim
6865296417Sdim  Results.push_back(Lower);
6866296417Sdim  Results.push_back(Upper);
6867296417Sdim}
6868296417Sdim
6869226633Sdimstatic SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6870226633Sdim  // Monotonic load/store is legal for all targets
6871226633Sdim  if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6872226633Sdim    return Op;
6873226633Sdim
6874276479Sdim  // Acquire/Release load/store is not legal for targets without a
6875226633Sdim  // dmb or equivalent available.
6876226633Sdim  return SDValue();
6877226633Sdim}
6878226633Sdim
6879261991Sdimstatic void ReplaceREADCYCLECOUNTER(SDNode *N,
6880261991Sdim                                    SmallVectorImpl<SDValue> &Results,
6881261991Sdim                                    SelectionDAG &DAG,
6882261991Sdim                                    const ARMSubtarget *Subtarget) {
6883261991Sdim  SDLoc DL(N);
6884296417Sdim  // Under Power Management extensions, the cycle-count is:
6885296417Sdim  //    mrc p15, #0, <Rt>, c9, c13, #0
6886296417Sdim  SDValue Ops[] = { N->getOperand(0), // Chain
6887296417Sdim                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6888296417Sdim                    DAG.getConstant(15, DL, MVT::i32),
6889296417Sdim                    DAG.getConstant(0, DL, MVT::i32),
6890296417Sdim                    DAG.getConstant(9, DL, MVT::i32),
6891296417Sdim                    DAG.getConstant(13, DL, MVT::i32),
6892296417Sdim                    DAG.getConstant(0, DL, MVT::i32)
6893296417Sdim  };
6894261991Sdim
6895296417Sdim  SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6896296417Sdim                                 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6897296417Sdim  Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6898296417Sdim                                DAG.getConstant(0, DL, MVT::i32)));
6899296417Sdim  Results.push_back(Cycles32.getValue(1));
6900261991Sdim}
6901261991Sdim
6902207618SrdivackySDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6903193323Sed  switch (Op.getOpcode()) {
6904198090Srdivacky  default: llvm_unreachable("Don't know how to custom lower this!");
6905288943Sdim  case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6906193323Sed  case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6907198892Srdivacky  case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6908193323Sed  case ISD::GlobalAddress:
6909276479Sdim    switch (Subtarget->getTargetTriple().getObjectFormat()) {
6910276479Sdim    default: llvm_unreachable("unknown object format");
6911276479Sdim    case Triple::COFF:
6912276479Sdim      return LowerGlobalAddressWindows(Op, DAG);
6913276479Sdim    case Triple::ELF:
6914276479Sdim      return LowerGlobalAddressELF(Op, DAG);
6915276479Sdim    case Triple::MachO:
6916276479Sdim      return LowerGlobalAddressDarwin(Op, DAG);
6917276479Sdim    }
6918221345Sdim  case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6919212904Sdim  case ISD::SELECT:        return LowerSELECT(Op, DAG);
6920199481Srdivacky  case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6921199481Srdivacky  case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6922193323Sed  case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6923207618Srdivacky  case ISD::VASTART:       return LowerVASTART(Op, DAG);
6924226633Sdim  case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6925218893Sdim  case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6926193323Sed  case ISD::SINT_TO_FP:
6927193323Sed  case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6928193323Sed  case ISD::FP_TO_SINT:
6929193323Sed  case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6930193323Sed  case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6931208599Srdivacky  case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6932193323Sed  case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6933208599Srdivacky  case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6934208599Srdivacky  case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6935296417Sdim  case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6936203954Srdivacky  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6937203954Srdivacky                                                               Subtarget);
6938221345Sdim  case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6939194710Sed  case ISD::SHL:
6940193323Sed  case ISD::SRL:
6941194710Sed  case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6942296417Sdim  case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6943296417Sdim  case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6944199481Srdivacky  case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6945198892Srdivacky  case ISD::SRL_PARTS:
6946199481Srdivacky  case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6947288943Sdim  case ISD::CTTZ:
6948288943Sdim  case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6949249423Sdim  case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6950226633Sdim  case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6951234353Sdim  case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6952212904Sdim  case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6953194710Sed  case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6954234353Sdim  case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6955194710Sed  case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6956198090Srdivacky  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6957212904Sdim  case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6958212904Sdim  case ISD::MUL:           return LowerMUL(Op, DAG);
6959218893Sdim  case ISD::SDIV:          return LowerSDIV(Op, DAG);
6960218893Sdim  case ISD::UDIV:          return LowerUDIV(Op, DAG);
6961226633Sdim  case ISD::ADDC:
6962226633Sdim  case ISD::ADDE:
6963226633Sdim  case ISD::SUBC:
6964226633Sdim  case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6965276479Sdim  case ISD::SADDO:
6966276479Sdim  case ISD::UADDO:
6967276479Sdim  case ISD::SSUBO:
6968276479Sdim  case ISD::USUBO:
6969276479Sdim    return LowerXALUO(Op, DAG);
6970226633Sdim  case ISD::ATOMIC_LOAD:
6971226633Sdim  case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6972261991Sdim  case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6973261991Sdim  case ISD::SDIVREM:
6974261991Sdim  case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6975276479Sdim  case ISD::DYNAMIC_STACKALLOC:
6976276479Sdim    if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6977276479Sdim      return LowerDYNAMIC_STACKALLOC(Op, DAG);
6978276479Sdim    llvm_unreachable("Don't know how to custom lower this!");
6979280031Sdim  case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6980280031Sdim  case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6981296417Sdim  case ARMISD::WIN__DBZCHK: return SDValue();
6982193323Sed  }
6983193323Sed}
6984193323Sed
6985193323Sed/// ReplaceNodeResults - Replace the results of node with an illegal result
6986193323Sed/// type with new values built out of custom code.
6987193323Sedvoid ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6988296417Sdim                                           SmallVectorImpl<SDValue> &Results,
6989207618Srdivacky                                           SelectionDAG &DAG) const {
6990207618Srdivacky  SDValue Res;
6991193323Sed  switch (N->getOpcode()) {
6992193323Sed  default:
6993198090Srdivacky    llvm_unreachable("Don't know how to custom expand this!");
6994288943Sdim  case ISD::READ_REGISTER:
6995288943Sdim    ExpandREAD_REGISTER(N, Results, DAG);
6996288943Sdim    break;
6997218893Sdim  case ISD::BITCAST:
6998218893Sdim    Res = ExpandBITCAST(N, DAG);
6999207618Srdivacky    break;
7000193323Sed  case ISD::SRL:
7001207618Srdivacky  case ISD::SRA:
7002218893Sdim    Res = Expand64BitShift(N, DAG, Subtarget);
7003207618Srdivacky    break;
7004296417Sdim  case ISD::SREM:
7005296417Sdim  case ISD::UREM:
7006296417Sdim    Res = LowerREM(N, DAG);
7007296417Sdim    break;
7008261991Sdim  case ISD::READCYCLECOUNTER:
7009261991Sdim    ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7010261991Sdim    return;
7011296417Sdim  case ISD::UDIV:
7012296417Sdim  case ISD::SDIV:
7013296417Sdim    assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7014296417Sdim    return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7015296417Sdim                             Results);
7016193323Sed  }
7017207618Srdivacky  if (Res.getNode())
7018207618Srdivacky    Results.push_back(Res);
7019193323Sed}
7020193323Sed
7021193323Sed//===----------------------------------------------------------------------===//
7022193323Sed//                           ARM Scheduler Hooks
7023193323Sed//===----------------------------------------------------------------------===//
7024193323Sed
7025226633Sdim/// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7026226633Sdim/// registers the function context.
7027226633Sdimvoid ARMTargetLowering::
7028226633SdimSetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
7029226633Sdim                       MachineBasicBlock *DispatchBB, int FI) const {
7030288943Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7031226633Sdim  DebugLoc dl = MI->getDebugLoc();
7032226633Sdim  MachineFunction *MF = MBB->getParent();
7033226633Sdim  MachineRegisterInfo *MRI = &MF->getRegInfo();
7034226633Sdim  MachineConstantPool *MCP = MF->getConstantPool();
7035226633Sdim  ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7036226633Sdim  const Function *F = MF->getFunction();
7037226633Sdim
7038226633Sdim  bool isThumb = Subtarget->isThumb();
7039226633Sdim  bool isThumb2 = Subtarget->isThumb2();
7040226633Sdim
7041226633Sdim  unsigned PCLabelId = AFI->createPICLabelUId();
7042226633Sdim  unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7043226633Sdim  ARMConstantPoolValue *CPV =
7044226633Sdim    ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7045226633Sdim  unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7046226633Sdim
7047280031Sdim  const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7048280031Sdim                                           : &ARM::GPRRegClass;
7049226633Sdim
7050226633Sdim  // Grab constant pool and fixed stack memory operands.
7051226633Sdim  MachineMemOperand *CPMMO =
7052296417Sdim      MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7053296417Sdim                               MachineMemOperand::MOLoad, 4, 4);
7054226633Sdim
7055226633Sdim  MachineMemOperand *FIMMOSt =
7056296417Sdim      MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7057296417Sdim                               MachineMemOperand::MOStore, 4, 4);
7058226633Sdim
7059226633Sdim  // Load the address of the dispatch MBB into the jump buffer.
7060226633Sdim  if (isThumb2) {
7061226633Sdim    // Incoming value: jbuf
7062226633Sdim    //   ldr.n  r5, LCPI1_1
7063226633Sdim    //   orr    r5, r5, #1
7064226633Sdim    //   add    r5, pc
7065226633Sdim    //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7066226633Sdim    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7067226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7068226633Sdim                   .addConstantPoolIndex(CPI)
7069226633Sdim                   .addMemOperand(CPMMO));
7070226633Sdim    // Set the low bit because of thumb mode.
7071226633Sdim    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7072226633Sdim    AddDefaultCC(
7073226633Sdim      AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7074226633Sdim                     .addReg(NewVReg1, RegState::Kill)
7075226633Sdim                     .addImm(0x01)));
7076226633Sdim    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7077226633Sdim    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7078226633Sdim      .addReg(NewVReg2, RegState::Kill)
7079226633Sdim      .addImm(PCLabelId);
7080226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7081226633Sdim                   .addReg(NewVReg3, RegState::Kill)
7082226633Sdim                   .addFrameIndex(FI)
7083226633Sdim                   .addImm(36)  // &jbuf[1] :: pc
7084226633Sdim                   .addMemOperand(FIMMOSt));
7085226633Sdim  } else if (isThumb) {
7086226633Sdim    // Incoming value: jbuf
7087226633Sdim    //   ldr.n  r1, LCPI1_4
7088226633Sdim    //   add    r1, pc
7089226633Sdim    //   mov    r2, #1
7090226633Sdim    //   orrs   r1, r2
7091226633Sdim    //   add    r2, $jbuf, #+4 ; &jbuf[1]
7092226633Sdim    //   str    r1, [r2]
7093226633Sdim    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7094226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7095226633Sdim                   .addConstantPoolIndex(CPI)
7096226633Sdim                   .addMemOperand(CPMMO));
7097226633Sdim    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7098226633Sdim    BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7099226633Sdim      .addReg(NewVReg1, RegState::Kill)
7100226633Sdim      .addImm(PCLabelId);
7101226633Sdim    // Set the low bit because of thumb mode.
7102226633Sdim    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7103226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7104226633Sdim                   .addReg(ARM::CPSR, RegState::Define)
7105226633Sdim                   .addImm(1));
7106226633Sdim    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7107226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7108226633Sdim                   .addReg(ARM::CPSR, RegState::Define)
7109226633Sdim                   .addReg(NewVReg2, RegState::Kill)
7110226633Sdim                   .addReg(NewVReg3, RegState::Kill));
7111226633Sdim    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7112280031Sdim    BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7113280031Sdim            .addFrameIndex(FI)
7114280031Sdim            .addImm(36); // &jbuf[1] :: pc
7115226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7116226633Sdim                   .addReg(NewVReg4, RegState::Kill)
7117226633Sdim                   .addReg(NewVReg5, RegState::Kill)
7118226633Sdim                   .addImm(0)
7119226633Sdim                   .addMemOperand(FIMMOSt));
7120226633Sdim  } else {
7121226633Sdim    // Incoming value: jbuf
7122226633Sdim    //   ldr  r1, LCPI1_1
7123226633Sdim    //   add  r1, pc, r1
7124226633Sdim    //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7125226633Sdim    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7126226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7127226633Sdim                   .addConstantPoolIndex(CPI)
7128226633Sdim                   .addImm(0)
7129226633Sdim                   .addMemOperand(CPMMO));
7130226633Sdim    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7131226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7132226633Sdim                   .addReg(NewVReg1, RegState::Kill)
7133226633Sdim                   .addImm(PCLabelId));
7134226633Sdim    AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7135226633Sdim                   .addReg(NewVReg2, RegState::Kill)
7136226633Sdim                   .addFrameIndex(FI)
7137226633Sdim                   .addImm(36)  // &jbuf[1] :: pc
7138226633Sdim                   .addMemOperand(FIMMOSt));
7139226633Sdim  }
7140226633Sdim}
7141226633Sdim
7142288943Sdimvoid ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7143288943Sdim                                              MachineBasicBlock *MBB) const {
7144288943Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7145226633Sdim  DebugLoc dl = MI->getDebugLoc();
7146226633Sdim  MachineFunction *MF = MBB->getParent();
7147226633Sdim  MachineRegisterInfo *MRI = &MF->getRegInfo();
7148226633Sdim  MachineFrameInfo *MFI = MF->getFrameInfo();
7149226633Sdim  int FI = MFI->getFunctionContextIndex();
7150226633Sdim
7151280031Sdim  const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7152280031Sdim                                                        : &ARM::GPRnopcRegClass;
7153226633Sdim
7154226633Sdim  // Get a mapping of the call site numbers to all of the landing pads they're
7155226633Sdim  // associated with.
7156226633Sdim  DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7157226633Sdim  unsigned MaxCSNum = 0;
7158226633Sdim  MachineModuleInfo &MMI = MF->getMMI();
7159234353Sdim  for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7160234353Sdim       ++BB) {
7161296417Sdim    if (!BB->isEHPad()) continue;
7162226633Sdim
7163226633Sdim    // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7164226633Sdim    // pad.
7165226633Sdim    for (MachineBasicBlock::iterator
7166226633Sdim           II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7167226633Sdim      if (!II->isEHLabel()) continue;
7168226633Sdim
7169226633Sdim      MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7170226633Sdim      if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7171226633Sdim
7172226633Sdim      SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7173226633Sdim      for (SmallVectorImpl<unsigned>::iterator
7174226633Sdim             CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7175226633Sdim           CSI != CSE; ++CSI) {
7176296417Sdim        CallSiteNumToLPad[*CSI].push_back(&*BB);
7177226633Sdim        MaxCSNum = std::max(MaxCSNum, *CSI);
7178226633Sdim      }
7179221345Sdim      break;
7180221345Sdim    }
7181221345Sdim  }
7182221345Sdim
7183226633Sdim  // Get an ordered list of the machine basic blocks for the jump table.
7184226633Sdim  std::vector<MachineBasicBlock*> LPadList;
7185226633Sdim  SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7186226633Sdim  LPadList.reserve(CallSiteNumToLPad.size());
7187226633Sdim  for (unsigned I = 1; I <= MaxCSNum; ++I) {
7188226633Sdim    SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7189226633Sdim    for (SmallVectorImpl<MachineBasicBlock*>::iterator
7190226633Sdim           II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7191226633Sdim      LPadList.push_back(*II);
7192226633Sdim      InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7193226633Sdim    }
7194226633Sdim  }
7195226633Sdim
7196226633Sdim  assert(!LPadList.empty() &&
7197226633Sdim         "No landing pad destinations for the dispatch jump table!");
7198226633Sdim
7199226633Sdim  // Create the jump table and associated information.
7200226633Sdim  MachineJumpTableInfo *JTI =
7201226633Sdim    MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7202226633Sdim  unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7203249423Sdim  Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7204226633Sdim
7205226633Sdim  // Create the MBBs for the dispatch code.
7206226633Sdim
7207226633Sdim  // Shove the dispatch's address into the return slot in the function context.
7208226633Sdim  MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7209296417Sdim  DispatchBB->setIsEHPad();
7210226633Sdim
7211226633Sdim  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7212249423Sdim  unsigned trap_opcode;
7213249423Sdim  if (Subtarget->isThumb())
7214249423Sdim    trap_opcode = ARM::tTRAP;
7215249423Sdim  else
7216249423Sdim    trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7217249423Sdim
7218249423Sdim  BuildMI(TrapBB, dl, TII->get(trap_opcode));
7219226633Sdim  DispatchBB->addSuccessor(TrapBB);
7220226633Sdim
7221226633Sdim  MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7222226633Sdim  DispatchBB->addSuccessor(DispContBB);
7223226633Sdim
7224234353Sdim  // Insert and MBBs.
7225226633Sdim  MF->insert(MF->end(), DispatchBB);
7226226633Sdim  MF->insert(MF->end(), DispContBB);
7227226633Sdim  MF->insert(MF->end(), TrapBB);
7228226633Sdim
7229226633Sdim  // Insert code into the entry block that creates and registers the function
7230226633Sdim  // context.
7231226633Sdim  SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7232226633Sdim
7233296417Sdim  MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7234296417Sdim      MachinePointerInfo::getFixedStack(*MF, FI),
7235296417Sdim      MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7236226633Sdim
7237243830Sdim  MachineInstrBuilder MIB;
7238243830Sdim  MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7239234353Sdim
7240243830Sdim  const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7241243830Sdim  const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7242243830Sdim
7243243830Sdim  // Add a register mask with no preserved registers.  This results in all
7244243830Sdim  // registers being marked as clobbered.
7245243830Sdim  MIB.addRegMask(RI.getNoPreservedMask());
7246243830Sdim
7247234353Sdim  unsigned NumLPads = LPadList.size();
7248226633Sdim  if (Subtarget->isThumb2()) {
7249226633Sdim    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7250226633Sdim    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7251226633Sdim                   .addFrameIndex(FI)
7252226633Sdim                   .addImm(4)
7253226633Sdim                   .addMemOperand(FIMMOLd));
7254234353Sdim
7255234353Sdim    if (NumLPads < 256) {
7256234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7257234353Sdim                     .addReg(NewVReg1)
7258234353Sdim                     .addImm(LPadList.size()));
7259234353Sdim    } else {
7260234353Sdim      unsigned VReg1 = MRI->createVirtualRegister(TRC);
7261234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7262234353Sdim                     .addImm(NumLPads & 0xFFFF));
7263234353Sdim
7264234353Sdim      unsigned VReg2 = VReg1;
7265234353Sdim      if ((NumLPads & 0xFFFF0000) != 0) {
7266234353Sdim        VReg2 = MRI->createVirtualRegister(TRC);
7267234353Sdim        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7268234353Sdim                       .addReg(VReg1)
7269234353Sdim                       .addImm(NumLPads >> 16));
7270234353Sdim      }
7271234353Sdim
7272234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7273234353Sdim                     .addReg(NewVReg1)
7274234353Sdim                     .addReg(VReg2));
7275234353Sdim    }
7276234353Sdim
7277226633Sdim    BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7278226633Sdim      .addMBB(TrapBB)
7279226633Sdim      .addImm(ARMCC::HI)
7280226633Sdim      .addReg(ARM::CPSR);
7281226633Sdim
7282234353Sdim    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7283234353Sdim    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7284288943Sdim                   .addJumpTableIndex(MJTI));
7285226633Sdim
7286234353Sdim    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7287226633Sdim    AddDefaultCC(
7288226633Sdim      AddDefaultPred(
7289234353Sdim        BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7290234353Sdim        .addReg(NewVReg3, RegState::Kill)
7291226633Sdim        .addReg(NewVReg1)
7292226633Sdim        .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7293226633Sdim
7294226633Sdim    BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7295234353Sdim      .addReg(NewVReg4, RegState::Kill)
7296226633Sdim      .addReg(NewVReg1)
7297288943Sdim      .addJumpTableIndex(MJTI);
7298226633Sdim  } else if (Subtarget->isThumb()) {
7299226633Sdim    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7300226633Sdim    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7301226633Sdim                   .addFrameIndex(FI)
7302226633Sdim                   .addImm(1)
7303226633Sdim                   .addMemOperand(FIMMOLd));
7304226633Sdim
7305234353Sdim    if (NumLPads < 256) {
7306234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7307234353Sdim                     .addReg(NewVReg1)
7308234353Sdim                     .addImm(NumLPads));
7309234353Sdim    } else {
7310234353Sdim      MachineConstantPool *ConstantPool = MF->getConstantPool();
7311234353Sdim      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7312234353Sdim      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7313234353Sdim
7314234353Sdim      // MachineConstantPool wants an explicit alignment.
7315288943Sdim      unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7316234353Sdim      if (Align == 0)
7317288943Sdim        Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7318234353Sdim      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7319234353Sdim
7320234353Sdim      unsigned VReg1 = MRI->createVirtualRegister(TRC);
7321234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7322234353Sdim                     .addReg(VReg1, RegState::Define)
7323234353Sdim                     .addConstantPoolIndex(Idx));
7324234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7325234353Sdim                     .addReg(NewVReg1)
7326234353Sdim                     .addReg(VReg1));
7327234353Sdim    }
7328234353Sdim
7329226633Sdim    BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7330226633Sdim      .addMBB(TrapBB)
7331226633Sdim      .addImm(ARMCC::HI)
7332226633Sdim      .addReg(ARM::CPSR);
7333226633Sdim
7334226633Sdim    unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7335226633Sdim    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7336226633Sdim                   .addReg(ARM::CPSR, RegState::Define)
7337226633Sdim                   .addReg(NewVReg1)
7338226633Sdim                   .addImm(2));
7339226633Sdim
7340226633Sdim    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7341226633Sdim    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7342288943Sdim                   .addJumpTableIndex(MJTI));
7343226633Sdim
7344226633Sdim    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7345226633Sdim    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7346226633Sdim                   .addReg(ARM::CPSR, RegState::Define)
7347226633Sdim                   .addReg(NewVReg2, RegState::Kill)
7348226633Sdim                   .addReg(NewVReg3));
7349226633Sdim
7350296417Sdim    MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7351296417Sdim        MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7352226633Sdim
7353226633Sdim    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7354226633Sdim    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7355226633Sdim                   .addReg(NewVReg4, RegState::Kill)
7356226633Sdim                   .addImm(0)
7357226633Sdim                   .addMemOperand(JTMMOLd));
7358226633Sdim
7359249423Sdim    unsigned NewVReg6 = NewVReg5;
7360249423Sdim    if (RelocM == Reloc::PIC_) {
7361249423Sdim      NewVReg6 = MRI->createVirtualRegister(TRC);
7362249423Sdim      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7363249423Sdim                     .addReg(ARM::CPSR, RegState::Define)
7364249423Sdim                     .addReg(NewVReg5, RegState::Kill)
7365249423Sdim                     .addReg(NewVReg3));
7366249423Sdim    }
7367226633Sdim
7368226633Sdim    BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7369226633Sdim      .addReg(NewVReg6, RegState::Kill)
7370288943Sdim      .addJumpTableIndex(MJTI);
7371226633Sdim  } else {
7372226633Sdim    unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7373226633Sdim    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7374226633Sdim                   .addFrameIndex(FI)
7375226633Sdim                   .addImm(4)
7376226633Sdim                   .addMemOperand(FIMMOLd));
7377234353Sdim
7378234353Sdim    if (NumLPads < 256) {
7379234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7380234353Sdim                     .addReg(NewVReg1)
7381234353Sdim                     .addImm(NumLPads));
7382234353Sdim    } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7383234353Sdim      unsigned VReg1 = MRI->createVirtualRegister(TRC);
7384234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7385234353Sdim                     .addImm(NumLPads & 0xFFFF));
7386234353Sdim
7387234353Sdim      unsigned VReg2 = VReg1;
7388234353Sdim      if ((NumLPads & 0xFFFF0000) != 0) {
7389234353Sdim        VReg2 = MRI->createVirtualRegister(TRC);
7390234353Sdim        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7391234353Sdim                       .addReg(VReg1)
7392234353Sdim                       .addImm(NumLPads >> 16));
7393234353Sdim      }
7394234353Sdim
7395234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7396234353Sdim                     .addReg(NewVReg1)
7397234353Sdim                     .addReg(VReg2));
7398234353Sdim    } else {
7399234353Sdim      MachineConstantPool *ConstantPool = MF->getConstantPool();
7400234353Sdim      Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7401234353Sdim      const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7402234353Sdim
7403234353Sdim      // MachineConstantPool wants an explicit alignment.
7404288943Sdim      unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7405234353Sdim      if (Align == 0)
7406288943Sdim        Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7407234353Sdim      unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7408234353Sdim
7409234353Sdim      unsigned VReg1 = MRI->createVirtualRegister(TRC);
7410234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7411234353Sdim                     .addReg(VReg1, RegState::Define)
7412234353Sdim                     .addConstantPoolIndex(Idx)
7413234353Sdim                     .addImm(0));
7414234353Sdim      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7415234353Sdim                     .addReg(NewVReg1)
7416234353Sdim                     .addReg(VReg1, RegState::Kill));
7417234353Sdim    }
7418234353Sdim
7419226633Sdim    BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7420226633Sdim      .addMBB(TrapBB)
7421226633Sdim      .addImm(ARMCC::HI)
7422226633Sdim      .addReg(ARM::CPSR);
7423226633Sdim
7424234353Sdim    unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7425226633Sdim    AddDefaultCC(
7426234353Sdim      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7427226633Sdim                     .addReg(NewVReg1)
7428226633Sdim                     .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7429234353Sdim    unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7430234353Sdim    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7431288943Sdim                   .addJumpTableIndex(MJTI));
7432226633Sdim
7433296417Sdim    MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7434296417Sdim        MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7435234353Sdim    unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7436226633Sdim    AddDefaultPred(
7437234353Sdim      BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7438234353Sdim      .addReg(NewVReg3, RegState::Kill)
7439234353Sdim      .addReg(NewVReg4)
7440226633Sdim      .addImm(0)
7441226633Sdim      .addMemOperand(JTMMOLd));
7442226633Sdim
7443249423Sdim    if (RelocM == Reloc::PIC_) {
7444249423Sdim      BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7445249423Sdim        .addReg(NewVReg5, RegState::Kill)
7446249423Sdim        .addReg(NewVReg4)
7447288943Sdim        .addJumpTableIndex(MJTI);
7448249423Sdim    } else {
7449249423Sdim      BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7450249423Sdim        .addReg(NewVReg5, RegState::Kill)
7451288943Sdim        .addJumpTableIndex(MJTI);
7452249423Sdim    }
7453226633Sdim  }
7454226633Sdim
7455226633Sdim  // Add the jump table entries as successors to the MBB.
7456243830Sdim  SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7457226633Sdim  for (std::vector<MachineBasicBlock*>::iterator
7458226633Sdim         I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7459226633Sdim    MachineBasicBlock *CurMBB = *I;
7460280031Sdim    if (SeenMBBs.insert(CurMBB).second)
7461226633Sdim      DispContBB->addSuccessor(CurMBB);
7462226633Sdim  }
7463226633Sdim
7464234353Sdim  // N.B. the order the invoke BBs are processed in doesn't matter here.
7465276479Sdim  const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7466234353Sdim  SmallVector<MachineBasicBlock*, 64> MBBLPads;
7467280031Sdim  for (MachineBasicBlock *BB : InvokeBBs) {
7468226633Sdim
7469226633Sdim    // Remove the landing pad successor from the invoke block and replace it
7470226633Sdim    // with the new dispatch block.
7471234353Sdim    SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7472234353Sdim                                                  BB->succ_end());
7473234353Sdim    while (!Successors.empty()) {
7474234353Sdim      MachineBasicBlock *SMBB = Successors.pop_back_val();
7475296417Sdim      if (SMBB->isEHPad()) {
7476226633Sdim        BB->removeSuccessor(SMBB);
7477234353Sdim        MBBLPads.push_back(SMBB);
7478226633Sdim      }
7479226633Sdim    }
7480226633Sdim
7481296417Sdim    BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7482296417Sdim    BB->normalizeSuccProbs();
7483226633Sdim
7484226633Sdim    // Find the invoke call and mark all of the callee-saved registers as
7485226633Sdim    // 'implicit defined' so that they're spilled. This prevents code from
7486226633Sdim    // moving instructions to before the EH block, where they will never be
7487226633Sdim    // executed.
7488226633Sdim    for (MachineBasicBlock::reverse_iterator
7489226633Sdim           II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7490234353Sdim      if (!II->isCall()) continue;
7491226633Sdim
7492226633Sdim      DenseMap<unsigned, bool> DefRegs;
7493226633Sdim      for (MachineInstr::mop_iterator
7494226633Sdim             OI = II->operands_begin(), OE = II->operands_end();
7495226633Sdim           OI != OE; ++OI) {
7496226633Sdim        if (!OI->isReg()) continue;
7497226633Sdim        DefRegs[OI->getReg()] = true;
7498226633Sdim      }
7499226633Sdim
7500249423Sdim      MachineInstrBuilder MIB(*MF, &*II);
7501226633Sdim
7502226633Sdim      for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7503234353Sdim        unsigned Reg = SavedRegs[i];
7504234353Sdim        if (Subtarget->isThumb2() &&
7505239462Sdim            !ARM::tGPRRegClass.contains(Reg) &&
7506239462Sdim            !ARM::hGPRRegClass.contains(Reg))
7507234353Sdim          continue;
7508239462Sdim        if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7509234353Sdim          continue;
7510239462Sdim        if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7511234353Sdim          continue;
7512234353Sdim        if (!DefRegs[Reg])
7513234353Sdim          MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7514226633Sdim      }
7515226633Sdim
7516226633Sdim      break;
7517226633Sdim    }
7518226633Sdim  }
7519226633Sdim
7520234353Sdim  // Mark all former landing pads as non-landing pads. The dispatch is the only
7521234353Sdim  // landing pad now.
7522234353Sdim  for (SmallVectorImpl<MachineBasicBlock*>::iterator
7523234353Sdim         I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7524296417Sdim    (*I)->setIsEHPad(false);
7525234353Sdim
7526226633Sdim  // The instruction is gone now.
7527221345Sdim  MI->eraseFromParent();
7528221345Sdim}
7529221345Sdim
7530226633Sdimstatic
7531226633SdimMachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7532226633Sdim  for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7533226633Sdim       E = MBB->succ_end(); I != E; ++I)
7534226633Sdim    if (*I != Succ)
7535226633Sdim      return *I;
7536226633Sdim  llvm_unreachable("Expecting a BB with two successors!");
7537226633Sdim}
7538226633Sdim
7539261991Sdim/// Return the load opcode for a given load size. If load size >= 8,
7540261991Sdim/// neon opcode will be returned.
7541261991Sdimstatic unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7542261991Sdim  if (LdSize >= 8)
7543261991Sdim    return LdSize == 16 ? ARM::VLD1q32wb_fixed
7544261991Sdim                        : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7545261991Sdim  if (IsThumb1)
7546261991Sdim    return LdSize == 4 ? ARM::tLDRi
7547261991Sdim                       : LdSize == 2 ? ARM::tLDRHi
7548261991Sdim                                     : LdSize == 1 ? ARM::tLDRBi : 0;
7549261991Sdim  if (IsThumb2)
7550261991Sdim    return LdSize == 4 ? ARM::t2LDR_POST
7551261991Sdim                       : LdSize == 2 ? ARM::t2LDRH_POST
7552261991Sdim                                     : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7553261991Sdim  return LdSize == 4 ? ARM::LDR_POST_IMM
7554261991Sdim                     : LdSize == 2 ? ARM::LDRH_POST
7555261991Sdim                                   : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7556261991Sdim}
7557261991Sdim
7558261991Sdim/// Return the store opcode for a given store size. If store size >= 8,
7559261991Sdim/// neon opcode will be returned.
7560261991Sdimstatic unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7561261991Sdim  if (StSize >= 8)
7562261991Sdim    return StSize == 16 ? ARM::VST1q32wb_fixed
7563261991Sdim                        : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7564261991Sdim  if (IsThumb1)
7565261991Sdim    return StSize == 4 ? ARM::tSTRi
7566261991Sdim                       : StSize == 2 ? ARM::tSTRHi
7567261991Sdim                                     : StSize == 1 ? ARM::tSTRBi : 0;
7568261991Sdim  if (IsThumb2)
7569261991Sdim    return StSize == 4 ? ARM::t2STR_POST
7570261991Sdim                       : StSize == 2 ? ARM::t2STRH_POST
7571261991Sdim                                     : StSize == 1 ? ARM::t2STRB_POST : 0;
7572261991Sdim  return StSize == 4 ? ARM::STR_POST_IMM
7573261991Sdim                     : StSize == 2 ? ARM::STRH_POST
7574261991Sdim                                   : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7575261991Sdim}
7576261991Sdim
7577261991Sdim/// Emit a post-increment load operation with given size. The instructions
7578261991Sdim/// will be added to BB at Pos.
7579261991Sdimstatic void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7580261991Sdim                       const TargetInstrInfo *TII, DebugLoc dl,
7581261991Sdim                       unsigned LdSize, unsigned Data, unsigned AddrIn,
7582261991Sdim                       unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7583261991Sdim  unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7584261991Sdim  assert(LdOpc != 0 && "Should have a load opcode");
7585261991Sdim  if (LdSize >= 8) {
7586261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7587261991Sdim                       .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7588261991Sdim                       .addImm(0));
7589261991Sdim  } else if (IsThumb1) {
7590261991Sdim    // load + update AddrIn
7591261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7592261991Sdim                       .addReg(AddrIn).addImm(0));
7593261991Sdim    MachineInstrBuilder MIB =
7594261991Sdim        BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7595261991Sdim    MIB = AddDefaultT1CC(MIB);
7596261991Sdim    MIB.addReg(AddrIn).addImm(LdSize);
7597261991Sdim    AddDefaultPred(MIB);
7598261991Sdim  } else if (IsThumb2) {
7599261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7600261991Sdim                       .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7601261991Sdim                       .addImm(LdSize));
7602261991Sdim  } else { // arm
7603261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7604261991Sdim                       .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7605261991Sdim                       .addReg(0).addImm(LdSize));
7606261991Sdim  }
7607261991Sdim}
7608261991Sdim
7609261991Sdim/// Emit a post-increment store operation with given size. The instructions
7610261991Sdim/// will be added to BB at Pos.
7611261991Sdimstatic void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7612261991Sdim                       const TargetInstrInfo *TII, DebugLoc dl,
7613261991Sdim                       unsigned StSize, unsigned Data, unsigned AddrIn,
7614261991Sdim                       unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7615261991Sdim  unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7616261991Sdim  assert(StOpc != 0 && "Should have a store opcode");
7617261991Sdim  if (StSize >= 8) {
7618261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7619261991Sdim                       .addReg(AddrIn).addImm(0).addReg(Data));
7620261991Sdim  } else if (IsThumb1) {
7621261991Sdim    // store + update AddrIn
7622261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7623261991Sdim                       .addReg(AddrIn).addImm(0));
7624261991Sdim    MachineInstrBuilder MIB =
7625261991Sdim        BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7626261991Sdim    MIB = AddDefaultT1CC(MIB);
7627261991Sdim    MIB.addReg(AddrIn).addImm(StSize);
7628261991Sdim    AddDefaultPred(MIB);
7629261991Sdim  } else if (IsThumb2) {
7630261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7631261991Sdim                       .addReg(Data).addReg(AddrIn).addImm(StSize));
7632261991Sdim  } else { // arm
7633261991Sdim    AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7634261991Sdim                       .addReg(Data).addReg(AddrIn).addReg(0)
7635261991Sdim                       .addImm(StSize));
7636261991Sdim  }
7637261991Sdim}
7638261991Sdim
7639261991SdimMachineBasicBlock *
7640261991SdimARMTargetLowering::EmitStructByval(MachineInstr *MI,
7641261991Sdim                                   MachineBasicBlock *BB) const {
7642239462Sdim  // This pseudo instruction has 3 operands: dst, src, size
7643239462Sdim  // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7644239462Sdim  // Otherwise, we will generate unrolled scalar copies.
7645288943Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7646239462Sdim  const BasicBlock *LLVM_BB = BB->getBasicBlock();
7647296417Sdim  MachineFunction::iterator It = ++BB->getIterator();
7648239462Sdim
7649239462Sdim  unsigned dest = MI->getOperand(0).getReg();
7650239462Sdim  unsigned src = MI->getOperand(1).getReg();
7651239462Sdim  unsigned SizeVal = MI->getOperand(2).getImm();
7652239462Sdim  unsigned Align = MI->getOperand(3).getImm();
7653239462Sdim  DebugLoc dl = MI->getDebugLoc();
7654239462Sdim
7655239462Sdim  MachineFunction *MF = BB->getParent();
7656239462Sdim  MachineRegisterInfo &MRI = MF->getRegInfo();
7657261991Sdim  unsigned UnitSize = 0;
7658276479Sdim  const TargetRegisterClass *TRC = nullptr;
7659276479Sdim  const TargetRegisterClass *VecTRC = nullptr;
7660239462Sdim
7661261991Sdim  bool IsThumb1 = Subtarget->isThumb1Only();
7662261991Sdim  bool IsThumb2 = Subtarget->isThumb2();
7663239462Sdim
7664239462Sdim  if (Align & 1) {
7665239462Sdim    UnitSize = 1;
7666239462Sdim  } else if (Align & 2) {
7667239462Sdim    UnitSize = 2;
7668239462Sdim  } else {
7669239462Sdim    // Check whether we can use NEON instructions.
7670288943Sdim    if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7671239462Sdim        Subtarget->hasNEON()) {
7672261991Sdim      if ((Align % 16 == 0) && SizeVal >= 16)
7673239462Sdim        UnitSize = 16;
7674261991Sdim      else if ((Align % 8 == 0) && SizeVal >= 8)
7675239462Sdim        UnitSize = 8;
7676239462Sdim    }
7677239462Sdim    // Can't use NEON instructions.
7678261991Sdim    if (UnitSize == 0)
7679239462Sdim      UnitSize = 4;
7680239462Sdim  }
7681239462Sdim
7682261991Sdim  // Select the correct opcode and register class for unit size load/store
7683261991Sdim  bool IsNeon = UnitSize >= 8;
7684280031Sdim  TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7685261991Sdim  if (IsNeon)
7686280031Sdim    VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7687280031Sdim                            : UnitSize == 8 ? &ARM::DPRRegClass
7688280031Sdim                                            : nullptr;
7689261991Sdim
7690239462Sdim  unsigned BytesLeft = SizeVal % UnitSize;
7691239462Sdim  unsigned LoopSize = SizeVal - BytesLeft;
7692239462Sdim
7693239462Sdim  if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7694239462Sdim    // Use LDR and STR to copy.
7695239462Sdim    // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7696239462Sdim    // [destOut] = STR_POST(scratch, destIn, UnitSize)
7697239462Sdim    unsigned srcIn = src;
7698239462Sdim    unsigned destIn = dest;
7699239462Sdim    for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7700239462Sdim      unsigned srcOut = MRI.createVirtualRegister(TRC);
7701239462Sdim      unsigned destOut = MRI.createVirtualRegister(TRC);
7702261991Sdim      unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7703261991Sdim      emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7704261991Sdim                 IsThumb1, IsThumb2);
7705261991Sdim      emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7706261991Sdim                 IsThumb1, IsThumb2);
7707239462Sdim      srcIn = srcOut;
7708239462Sdim      destIn = destOut;
7709239462Sdim    }
7710239462Sdim
7711239462Sdim    // Handle the leftover bytes with LDRB and STRB.
7712239462Sdim    // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7713239462Sdim    // [destOut] = STRB_POST(scratch, destIn, 1)
7714239462Sdim    for (unsigned i = 0; i < BytesLeft; i++) {
7715239462Sdim      unsigned srcOut = MRI.createVirtualRegister(TRC);
7716239462Sdim      unsigned destOut = MRI.createVirtualRegister(TRC);
7717261991Sdim      unsigned scratch = MRI.createVirtualRegister(TRC);
7718261991Sdim      emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7719261991Sdim                 IsThumb1, IsThumb2);
7720261991Sdim      emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7721261991Sdim                 IsThumb1, IsThumb2);
7722239462Sdim      srcIn = srcOut;
7723239462Sdim      destIn = destOut;
7724239462Sdim    }
7725239462Sdim    MI->eraseFromParent();   // The instruction is gone now.
7726239462Sdim    return BB;
7727239462Sdim  }
7728239462Sdim
7729239462Sdim  // Expand the pseudo op to a loop.
7730239462Sdim  // thisMBB:
7731239462Sdim  //   ...
7732239462Sdim  //   movw varEnd, # --> with thumb2
7733239462Sdim  //   movt varEnd, #
7734239462Sdim  //   ldrcp varEnd, idx --> without thumb2
7735239462Sdim  //   fallthrough --> loopMBB
7736239462Sdim  // loopMBB:
7737239462Sdim  //   PHI varPhi, varEnd, varLoop
7738239462Sdim  //   PHI srcPhi, src, srcLoop
7739239462Sdim  //   PHI destPhi, dst, destLoop
7740239462Sdim  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7741239462Sdim  //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7742239462Sdim  //   subs varLoop, varPhi, #UnitSize
7743239462Sdim  //   bne loopMBB
7744239462Sdim  //   fallthrough --> exitMBB
7745239462Sdim  // exitMBB:
7746239462Sdim  //   epilogue to handle left-over bytes
7747239462Sdim  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7748239462Sdim  //   [destOut] = STRB_POST(scratch, destLoop, 1)
7749239462Sdim  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7750239462Sdim  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7751239462Sdim  MF->insert(It, loopMBB);
7752239462Sdim  MF->insert(It, exitMBB);
7753239462Sdim
7754239462Sdim  // Transfer the remainder of BB and its successor edges to exitMBB.
7755239462Sdim  exitMBB->splice(exitMBB->begin(), BB,
7756276479Sdim                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
7757239462Sdim  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7758239462Sdim
7759239462Sdim  // Load an immediate to varEnd.
7760239462Sdim  unsigned varEnd = MRI.createVirtualRegister(TRC);
7761288943Sdim  if (Subtarget->useMovt(*MF)) {
7762261991Sdim    unsigned Vtmp = varEnd;
7763239462Sdim    if ((LoopSize & 0xFFFF0000) != 0)
7764261991Sdim      Vtmp = MRI.createVirtualRegister(TRC);
7765288943Sdim    AddDefaultPred(BuildMI(BB, dl,
7766288943Sdim                           TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7767288943Sdim                           Vtmp).addImm(LoopSize & 0xFFFF));
7768239462Sdim
7769239462Sdim    if ((LoopSize & 0xFFFF0000) != 0)
7770288943Sdim      AddDefaultPred(BuildMI(BB, dl,
7771288943Sdim                             TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7772288943Sdim                             varEnd)
7773288943Sdim                         .addReg(Vtmp)
7774288943Sdim                         .addImm(LoopSize >> 16));
7775239462Sdim  } else {
7776239462Sdim    MachineConstantPool *ConstantPool = MF->getConstantPool();
7777239462Sdim    Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7778239462Sdim    const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7779239462Sdim
7780239462Sdim    // MachineConstantPool wants an explicit alignment.
7781288943Sdim    unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7782239462Sdim    if (Align == 0)
7783288943Sdim      Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7784239462Sdim    unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7785239462Sdim
7786261991Sdim    if (IsThumb1)
7787261991Sdim      AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7788261991Sdim          varEnd, RegState::Define).addConstantPoolIndex(Idx));
7789261991Sdim    else
7790261991Sdim      AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7791261991Sdim          varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7792239462Sdim  }
7793239462Sdim  BB->addSuccessor(loopMBB);
7794239462Sdim
7795239462Sdim  // Generate the loop body:
7796239462Sdim  //   varPhi = PHI(varLoop, varEnd)
7797239462Sdim  //   srcPhi = PHI(srcLoop, src)
7798239462Sdim  //   destPhi = PHI(destLoop, dst)
7799239462Sdim  MachineBasicBlock *entryBB = BB;
7800239462Sdim  BB = loopMBB;
7801239462Sdim  unsigned varLoop = MRI.createVirtualRegister(TRC);
7802239462Sdim  unsigned varPhi = MRI.createVirtualRegister(TRC);
7803239462Sdim  unsigned srcLoop = MRI.createVirtualRegister(TRC);
7804239462Sdim  unsigned srcPhi = MRI.createVirtualRegister(TRC);
7805239462Sdim  unsigned destLoop = MRI.createVirtualRegister(TRC);
7806239462Sdim  unsigned destPhi = MRI.createVirtualRegister(TRC);
7807239462Sdim
7808239462Sdim  BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7809239462Sdim    .addReg(varLoop).addMBB(loopMBB)
7810239462Sdim    .addReg(varEnd).addMBB(entryBB);
7811239462Sdim  BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7812239462Sdim    .addReg(srcLoop).addMBB(loopMBB)
7813239462Sdim    .addReg(src).addMBB(entryBB);
7814239462Sdim  BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7815239462Sdim    .addReg(destLoop).addMBB(loopMBB)
7816239462Sdim    .addReg(dest).addMBB(entryBB);
7817239462Sdim
7818239462Sdim  //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7819239462Sdim  //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7820261991Sdim  unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7821261991Sdim  emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7822261991Sdim             IsThumb1, IsThumb2);
7823261991Sdim  emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7824261991Sdim             IsThumb1, IsThumb2);
7825239462Sdim
7826261991Sdim  // Decrement loop variable by UnitSize.
7827261991Sdim  if (IsThumb1) {
7828261991Sdim    MachineInstrBuilder MIB =
7829261991Sdim        BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7830261991Sdim    MIB = AddDefaultT1CC(MIB);
7831261991Sdim    MIB.addReg(varPhi).addImm(UnitSize);
7832261991Sdim    AddDefaultPred(MIB);
7833239462Sdim  } else {
7834261991Sdim    MachineInstrBuilder MIB =
7835261991Sdim        BuildMI(*BB, BB->end(), dl,
7836261991Sdim                TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7837261991Sdim    AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7838261991Sdim    MIB->getOperand(5).setReg(ARM::CPSR);
7839261991Sdim    MIB->getOperand(5).setIsDef(true);
7840239462Sdim  }
7841261991Sdim  BuildMI(*BB, BB->end(), dl,
7842261991Sdim          TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7843261991Sdim      .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7844239462Sdim
7845239462Sdim  // loopMBB can loop back to loopMBB or fall through to exitMBB.
7846239462Sdim  BB->addSuccessor(loopMBB);
7847239462Sdim  BB->addSuccessor(exitMBB);
7848239462Sdim
7849239462Sdim  // Add epilogue to handle BytesLeft.
7850239462Sdim  BB = exitMBB;
7851239462Sdim  MachineInstr *StartOfExit = exitMBB->begin();
7852239462Sdim
7853239462Sdim  //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7854239462Sdim  //   [destOut] = STRB_POST(scratch, destLoop, 1)
7855239462Sdim  unsigned srcIn = srcLoop;
7856239462Sdim  unsigned destIn = destLoop;
7857239462Sdim  for (unsigned i = 0; i < BytesLeft; i++) {
7858239462Sdim    unsigned srcOut = MRI.createVirtualRegister(TRC);
7859239462Sdim    unsigned destOut = MRI.createVirtualRegister(TRC);
7860261991Sdim    unsigned scratch = MRI.createVirtualRegister(TRC);
7861261991Sdim    emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7862261991Sdim               IsThumb1, IsThumb2);
7863261991Sdim    emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7864261991Sdim               IsThumb1, IsThumb2);
7865239462Sdim    srcIn = srcOut;
7866239462Sdim    destIn = destOut;
7867239462Sdim  }
7868239462Sdim
7869239462Sdim  MI->eraseFromParent();   // The instruction is gone now.
7870239462Sdim  return BB;
7871239462Sdim}
7872239462Sdim
7873200581SrdivackyMachineBasicBlock *
7874276479SdimARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7875276479Sdim                                       MachineBasicBlock *MBB) const {
7876276479Sdim  const TargetMachine &TM = getTargetMachine();
7877288943Sdim  const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7878276479Sdim  DebugLoc DL = MI->getDebugLoc();
7879276479Sdim
7880276479Sdim  assert(Subtarget->isTargetWindows() &&
7881276479Sdim         "__chkstk is only supported on Windows");
7882276479Sdim  assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7883276479Sdim
7884276479Sdim  // __chkstk takes the number of words to allocate on the stack in R4, and
7885276479Sdim  // returns the stack adjustment in number of bytes in R4.  This will not
7886276479Sdim  // clober any other registers (other than the obvious lr).
7887276479Sdim  //
7888276479Sdim  // Although, technically, IP should be considered a register which may be
7889276479Sdim  // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7890276479Sdim  // thumb-2 environment, so there is no interworking required.  As a result, we
7891276479Sdim  // do not expect a veneer to be emitted by the linker, clobbering IP.
7892276479Sdim  //
7893276479Sdim  // Each module receives its own copy of __chkstk, so no import thunk is
7894276479Sdim  // required, again, ensuring that IP is not clobbered.
7895276479Sdim  //
7896276479Sdim  // Finally, although some linkers may theoretically provide a trampoline for
7897276479Sdim  // out of range calls (which is quite common due to a 32M range limitation of
7898276479Sdim  // branches for Thumb), we can generate the long-call version via
7899276479Sdim  // -mcmodel=large, alleviating the need for the trampoline which may clobber
7900276479Sdim  // IP.
7901276479Sdim
7902276479Sdim  switch (TM.getCodeModel()) {
7903276479Sdim  case CodeModel::Small:
7904276479Sdim  case CodeModel::Medium:
7905276479Sdim  case CodeModel::Default:
7906276479Sdim  case CodeModel::Kernel:
7907276479Sdim    BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7908276479Sdim      .addImm((unsigned)ARMCC::AL).addReg(0)
7909276479Sdim      .addExternalSymbol("__chkstk")
7910276479Sdim      .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7911276479Sdim      .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7912276479Sdim      .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7913276479Sdim    break;
7914276479Sdim  case CodeModel::Large:
7915276479Sdim  case CodeModel::JITDefault: {
7916276479Sdim    MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7917276479Sdim    unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7918276479Sdim
7919276479Sdim    BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7920276479Sdim      .addExternalSymbol("__chkstk");
7921276479Sdim    BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7922276479Sdim      .addImm((unsigned)ARMCC::AL).addReg(0)
7923276479Sdim      .addReg(Reg, RegState::Kill)
7924276479Sdim      .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7925276479Sdim      .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7926276479Sdim      .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7927276479Sdim    break;
7928276479Sdim  }
7929276479Sdim  }
7930276479Sdim
7931276479Sdim  AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7932276479Sdim                                      ARM::SP)
7933276479Sdim                              .addReg(ARM::SP).addReg(ARM::R4)));
7934276479Sdim
7935276479Sdim  MI->eraseFromParent();
7936276479Sdim  return MBB;
7937276479Sdim}
7938276479Sdim
7939276479SdimMachineBasicBlock *
7940296417SdimARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7941296417Sdim                                       MachineBasicBlock *MBB) const {
7942296417Sdim  DebugLoc DL = MI->getDebugLoc();
7943296417Sdim  MachineFunction *MF = MBB->getParent();
7944296417Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7945296417Sdim
7946296417Sdim  MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7947296417Sdim  MF->push_back(ContBB);
7948296417Sdim  ContBB->splice(ContBB->begin(), MBB,
7949296417Sdim                 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7950296417Sdim  MBB->addSuccessor(ContBB);
7951296417Sdim
7952296417Sdim  MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7953296417Sdim  MF->push_back(TrapBB);
7954296417Sdim  BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7955296417Sdim  MBB->addSuccessor(TrapBB);
7956296417Sdim
7957296417Sdim  BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7958296417Sdim      .addReg(MI->getOperand(0).getReg())
7959296417Sdim      .addMBB(TrapBB);
7960296417Sdim
7961296417Sdim  MI->eraseFromParent();
7962296417Sdim  return ContBB;
7963296417Sdim}
7964296417Sdim
7965296417SdimMachineBasicBlock *
7966193323SedARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7967207618Srdivacky                                               MachineBasicBlock *BB) const {
7968288943Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7969193323Sed  DebugLoc dl = MI->getDebugLoc();
7970200581Srdivacky  bool isThumb2 = Subtarget->isThumb2();
7971193323Sed  switch (MI->getOpcode()) {
7972221345Sdim  default: {
7973200581Srdivacky    MI->dump();
7974198090Srdivacky    llvm_unreachable("Unexpected instr type to insert");
7975221345Sdim  }
7976226633Sdim  // The Thumb2 pre-indexed stores have the same MI operands, they just
7977226633Sdim  // define them differently in the .td files from the isel patterns, so
7978226633Sdim  // they need pseudos.
7979226633Sdim  case ARM::t2STR_preidx:
7980226633Sdim    MI->setDesc(TII->get(ARM::t2STR_PRE));
7981226633Sdim    return BB;
7982226633Sdim  case ARM::t2STRB_preidx:
7983226633Sdim    MI->setDesc(TII->get(ARM::t2STRB_PRE));
7984226633Sdim    return BB;
7985226633Sdim  case ARM::t2STRH_preidx:
7986226633Sdim    MI->setDesc(TII->get(ARM::t2STRH_PRE));
7987226633Sdim    return BB;
7988226633Sdim
7989226633Sdim  case ARM::STRi_preidx:
7990226633Sdim  case ARM::STRBi_preidx: {
7991226633Sdim    unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7992226633Sdim      ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7993226633Sdim    // Decode the offset.
7994226633Sdim    unsigned Offset = MI->getOperand(4).getImm();
7995226633Sdim    bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7996226633Sdim    Offset = ARM_AM::getAM2Offset(Offset);
7997226633Sdim    if (isSub)
7998226633Sdim      Offset = -Offset;
7999226633Sdim
8000226633Sdim    MachineMemOperand *MMO = *MI->memoperands_begin();
8001226633Sdim    BuildMI(*BB, MI, dl, TII->get(NewOpc))
8002226633Sdim      .addOperand(MI->getOperand(0))  // Rn_wb
8003226633Sdim      .addOperand(MI->getOperand(1))  // Rt
8004226633Sdim      .addOperand(MI->getOperand(2))  // Rn
8005226633Sdim      .addImm(Offset)                 // offset (skip GPR==zero_reg)
8006226633Sdim      .addOperand(MI->getOperand(5))  // pred
8007226633Sdim      .addOperand(MI->getOperand(6))
8008226633Sdim      .addMemOperand(MMO);
8009226633Sdim    MI->eraseFromParent();
8010226633Sdim    return BB;
8011226633Sdim  }
8012226633Sdim  case ARM::STRr_preidx:
8013226633Sdim  case ARM::STRBr_preidx:
8014226633Sdim  case ARM::STRH_preidx: {
8015226633Sdim    unsigned NewOpc;
8016226633Sdim    switch (MI->getOpcode()) {
8017226633Sdim    default: llvm_unreachable("unexpected opcode!");
8018226633Sdim    case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8019226633Sdim    case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8020226633Sdim    case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8021226633Sdim    }
8022226633Sdim    MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8023226633Sdim    for (unsigned i = 0; i < MI->getNumOperands(); ++i)
8024226633Sdim      MIB.addOperand(MI->getOperand(i));
8025226633Sdim    MI->eraseFromParent();
8026226633Sdim    return BB;
8027226633Sdim  }
8028200581Srdivacky
8029198090Srdivacky  case ARM::tMOVCCr_pseudo: {
8030193323Sed    // To "insert" a SELECT_CC instruction, we actually have to insert the
8031193323Sed    // diamond control-flow pattern.  The incoming instruction knows the
8032193323Sed    // destination vreg to set, the condition code register to branch on, the
8033193323Sed    // true/false values to select between, and a branch opcode to use.
8034193323Sed    const BasicBlock *LLVM_BB = BB->getBasicBlock();
8035296417Sdim    MachineFunction::iterator It = ++BB->getIterator();
8036193323Sed
8037193323Sed    //  thisMBB:
8038193323Sed    //  ...
8039193323Sed    //   TrueVal = ...
8040193323Sed    //   cmpTY ccX, r1, r2
8041193323Sed    //   bCC copy1MBB
8042193323Sed    //   fallthrough --> copy0MBB
8043193323Sed    MachineBasicBlock *thisMBB  = BB;
8044193323Sed    MachineFunction *F = BB->getParent();
8045193323Sed    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8046193323Sed    MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8047193323Sed    F->insert(It, copy0MBB);
8048193323Sed    F->insert(It, sinkMBB);
8049210299Sed
8050210299Sed    // Transfer the remainder of BB and its successor edges to sinkMBB.
8051210299Sed    sinkMBB->splice(sinkMBB->begin(), BB,
8052276479Sdim                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8053210299Sed    sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8054210299Sed
8055193323Sed    BB->addSuccessor(copy0MBB);
8056193323Sed    BB->addSuccessor(sinkMBB);
8057193323Sed
8058210299Sed    BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
8059210299Sed      .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
8060210299Sed
8061193323Sed    //  copy0MBB:
8062193323Sed    //   %FalseValue = ...
8063193323Sed    //   # fallthrough to sinkMBB
8064193323Sed    BB = copy0MBB;
8065193323Sed
8066193323Sed    // Update machine-CFG edges
8067193323Sed    BB->addSuccessor(sinkMBB);
8068193323Sed
8069193323Sed    //  sinkMBB:
8070193323Sed    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8071193323Sed    //  ...
8072193323Sed    BB = sinkMBB;
8073210299Sed    BuildMI(*BB, BB->begin(), dl,
8074210299Sed            TII->get(ARM::PHI), MI->getOperand(0).getReg())
8075193323Sed      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8076193323Sed      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8077193323Sed
8078210299Sed    MI->eraseFromParent();   // The pseudo instruction is gone now.
8079193323Sed    return BB;
8080193323Sed  }
8081198090Srdivacky
8082210299Sed  case ARM::BCCi64:
8083210299Sed  case ARM::BCCZi64: {
8084218893Sdim    // If there is an unconditional branch to the other successor, remove it.
8085276479Sdim    BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8086218893Sdim
8087210299Sed    // Compare both parts that make up the double comparison separately for
8088210299Sed    // equality.
8089210299Sed    bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8090210299Sed
8091210299Sed    unsigned LHS1 = MI->getOperand(1).getReg();
8092210299Sed    unsigned LHS2 = MI->getOperand(2).getReg();
8093210299Sed    if (RHSisZero) {
8094210299Sed      AddDefaultPred(BuildMI(BB, dl,
8095210299Sed                             TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8096210299Sed                     .addReg(LHS1).addImm(0));
8097210299Sed      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8098210299Sed        .addReg(LHS2).addImm(0)
8099210299Sed        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8100210299Sed    } else {
8101210299Sed      unsigned RHS1 = MI->getOperand(3).getReg();
8102210299Sed      unsigned RHS2 = MI->getOperand(4).getReg();
8103210299Sed      AddDefaultPred(BuildMI(BB, dl,
8104210299Sed                             TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8105210299Sed                     .addReg(LHS1).addReg(RHS1));
8106210299Sed      BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8107210299Sed        .addReg(LHS2).addReg(RHS2)
8108210299Sed        .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8109210299Sed    }
8110210299Sed
8111210299Sed    MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8112210299Sed    MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8113210299Sed    if (MI->getOperand(0).getImm() == ARMCC::NE)
8114210299Sed      std::swap(destMBB, exitMBB);
8115210299Sed
8116210299Sed    BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8117210299Sed      .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8118226633Sdim    if (isThumb2)
8119226633Sdim      AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8120226633Sdim    else
8121226633Sdim      BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8122210299Sed
8123210299Sed    MI->eraseFromParent();   // The pseudo instruction is gone now.
8124210299Sed    return BB;
8125210299Sed  }
8126226633Sdim
8127234353Sdim  case ARM::Int_eh_sjlj_setjmp:
8128234353Sdim  case ARM::Int_eh_sjlj_setjmp_nofp:
8129234353Sdim  case ARM::tInt_eh_sjlj_setjmp:
8130234353Sdim  case ARM::t2Int_eh_sjlj_setjmp:
8131234353Sdim  case ARM::t2Int_eh_sjlj_setjmp_nofp:
8132296417Sdim    return BB;
8133296417Sdim
8134296417Sdim  case ARM::Int_eh_sjlj_setup_dispatch:
8135234353Sdim    EmitSjLjDispatchBlock(MI, BB);
8136234353Sdim    return BB;
8137234353Sdim
8138226633Sdim  case ARM::ABS:
8139226633Sdim  case ARM::t2ABS: {
8140226633Sdim    // To insert an ABS instruction, we have to insert the
8141226633Sdim    // diamond control-flow pattern.  The incoming instruction knows the
8142226633Sdim    // source vreg to test against 0, the destination vreg to set,
8143226633Sdim    // the condition code register to branch on, the
8144234353Sdim    // true/false values to select between, and a branch opcode to use.
8145226633Sdim    // It transforms
8146226633Sdim    //     V1 = ABS V0
8147226633Sdim    // into
8148226633Sdim    //     V2 = MOVS V0
8149226633Sdim    //     BCC                      (branch to SinkBB if V0 >= 0)
8150226633Sdim    //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8151234353Sdim    //     SinkBB: V1 = PHI(V2, V3)
8152226633Sdim    const BasicBlock *LLVM_BB = BB->getBasicBlock();
8153296417Sdim    MachineFunction::iterator BBI = ++BB->getIterator();
8154226633Sdim    MachineFunction *Fn = BB->getParent();
8155226633Sdim    MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8156226633Sdim    MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8157226633Sdim    Fn->insert(BBI, RSBBB);
8158226633Sdim    Fn->insert(BBI, SinkBB);
8159226633Sdim
8160226633Sdim    unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8161226633Sdim    unsigned int ABSDstReg = MI->getOperand(0).getReg();
8162288943Sdim    bool ABSSrcKIll = MI->getOperand(1).isKill();
8163226633Sdim    bool isThumb2 = Subtarget->isThumb2();
8164226633Sdim    MachineRegisterInfo &MRI = Fn->getRegInfo();
8165226633Sdim    // In Thumb mode S must not be specified if source register is the SP or
8166226633Sdim    // PC and if destination register is the SP, so restrict register class
8167280031Sdim    unsigned NewRsbDstReg =
8168280031Sdim      MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8169226633Sdim
8170226633Sdim    // Transfer the remainder of BB and its successor edges to sinkMBB.
8171226633Sdim    SinkBB->splice(SinkBB->begin(), BB,
8172276479Sdim                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8173226633Sdim    SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8174226633Sdim
8175226633Sdim    BB->addSuccessor(RSBBB);
8176226633Sdim    BB->addSuccessor(SinkBB);
8177226633Sdim
8178226633Sdim    // fall through to SinkMBB
8179226633Sdim    RSBBB->addSuccessor(SinkBB);
8180226633Sdim
8181239462Sdim    // insert a cmp at the end of BB
8182239462Sdim    AddDefaultPred(BuildMI(BB, dl,
8183239462Sdim                           TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8184239462Sdim                   .addReg(ABSSrcReg).addImm(0));
8185226633Sdim
8186226633Sdim    // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8187234353Sdim    BuildMI(BB, dl,
8188226633Sdim      TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8189226633Sdim      .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8190226633Sdim
8191226633Sdim    // insert rsbri in RSBBB
8192226633Sdim    // Note: BCC and rsbri will be converted into predicated rsbmi
8193226633Sdim    // by if-conversion pass
8194234353Sdim    BuildMI(*RSBBB, RSBBB->begin(), dl,
8195226633Sdim      TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8196288943Sdim      .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8197226633Sdim      .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8198226633Sdim
8199234353Sdim    // insert PHI in SinkBB,
8200226633Sdim    // reuse ABSDstReg to not change uses of ABS instruction
8201226633Sdim    BuildMI(*SinkBB, SinkBB->begin(), dl,
8202226633Sdim      TII->get(ARM::PHI), ABSDstReg)
8203226633Sdim      .addReg(NewRsbDstReg).addMBB(RSBBB)
8204239462Sdim      .addReg(ABSSrcReg).addMBB(BB);
8205226633Sdim
8206226633Sdim    // remove ABS instruction
8207234353Sdim    MI->eraseFromParent();
8208226633Sdim
8209226633Sdim    // return last added BB
8210226633Sdim    return SinkBB;
8211193323Sed  }
8212239462Sdim  case ARM::COPY_STRUCT_BYVAL_I32:
8213239462Sdim    ++NumLoopByVals;
8214239462Sdim    return EmitStructByval(MI, BB);
8215276479Sdim  case ARM::WIN__CHKSTK:
8216276479Sdim    return EmitLowered__chkstk(MI, BB);
8217296417Sdim  case ARM::WIN__DBZCHK:
8218296417Sdim    return EmitLowered__dbzchk(MI, BB);
8219226633Sdim  }
8220193323Sed}
8221193323Sed
8222296417Sdim/// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8223296417Sdim/// when it is expanded into LDM/STM. This is done as a post-isel lowering
8224296417Sdim/// instead of as a custom inserter because we need the use list from the SDNode.
8225296417Sdimstatic void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8226296417Sdim                                   MachineInstr *MI, const SDNode *Node) {
8227296417Sdim  bool isThumb1 = Subtarget->isThumb1Only();
8228296417Sdim
8229296417Sdim  DebugLoc DL = MI->getDebugLoc();
8230296417Sdim  MachineFunction *MF = MI->getParent()->getParent();
8231296417Sdim  MachineRegisterInfo &MRI = MF->getRegInfo();
8232296417Sdim  MachineInstrBuilder MIB(*MF, MI);
8233296417Sdim
8234296417Sdim  // If the new dst/src is unused mark it as dead.
8235296417Sdim  if (!Node->hasAnyUseOfValue(0)) {
8236296417Sdim    MI->getOperand(0).setIsDead(true);
8237296417Sdim  }
8238296417Sdim  if (!Node->hasAnyUseOfValue(1)) {
8239296417Sdim    MI->getOperand(1).setIsDead(true);
8240296417Sdim  }
8241296417Sdim
8242296417Sdim  // The MEMCPY both defines and kills the scratch registers.
8243296417Sdim  for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8244296417Sdim    unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8245296417Sdim                                                         : &ARM::GPRRegClass);
8246296417Sdim    MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8247296417Sdim  }
8248296417Sdim}
8249296417Sdim
8250226633Sdimvoid ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8251226633Sdim                                                      SDNode *Node) const {
8252296417Sdim  if (MI->getOpcode() == ARM::MEMCPY) {
8253296417Sdim    attachMEMCPYScratchRegs(Subtarget, MI, Node);
8254296417Sdim    return;
8255296417Sdim  }
8256296417Sdim
8257234353Sdim  const MCInstrDesc *MCID = &MI->getDesc();
8258226633Sdim  // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8259226633Sdim  // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8260226633Sdim  // operand is still set to noreg. If needed, set the optional operand's
8261226633Sdim  // register to CPSR, and remove the redundant implicit def.
8262226633Sdim  //
8263234353Sdim  // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8264226633Sdim
8265226633Sdim  // Rename pseudo opcodes.
8266226633Sdim  unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8267226633Sdim  if (NewOpc) {
8268288943Sdim    const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8269234353Sdim    MCID = &TII->get(NewOpc);
8270234353Sdim
8271234353Sdim    assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8272234353Sdim           "converted opcode should be the same except for cc_out");
8273234353Sdim
8274234353Sdim    MI->setDesc(*MCID);
8275234353Sdim
8276234353Sdim    // Add the optional cc_out operand
8277234353Sdim    MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8278226633Sdim  }
8279234353Sdim  unsigned ccOutIdx = MCID->getNumOperands() - 1;
8280226633Sdim
8281226633Sdim  // Any ARM instruction that sets the 's' bit should specify an optional
8282226633Sdim  // "cc_out" operand in the last operand position.
8283234353Sdim  if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8284226633Sdim    assert(!NewOpc && "Optional cc_out operand required");
8285226633Sdim    return;
8286226633Sdim  }
8287226633Sdim  // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8288226633Sdim  // since we already have an optional CPSR def.
8289226633Sdim  bool definesCPSR = false;
8290226633Sdim  bool deadCPSR = false;
8291234353Sdim  for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8292226633Sdim       i != e; ++i) {
8293226633Sdim    const MachineOperand &MO = MI->getOperand(i);
8294226633Sdim    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8295226633Sdim      definesCPSR = true;
8296226633Sdim      if (MO.isDead())
8297226633Sdim        deadCPSR = true;
8298226633Sdim      MI->RemoveOperand(i);
8299226633Sdim      break;
8300226633Sdim    }
8301226633Sdim  }
8302226633Sdim  if (!definesCPSR) {
8303226633Sdim    assert(!NewOpc && "Optional cc_out operand required");
8304226633Sdim    return;
8305226633Sdim  }
8306226633Sdim  assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8307226633Sdim  if (deadCPSR) {
8308226633Sdim    assert(!MI->getOperand(ccOutIdx).getReg() &&
8309226633Sdim           "expect uninitialized optional cc_out operand");
8310226633Sdim    return;
8311226633Sdim  }
8312226633Sdim
8313226633Sdim  // If this instruction was defined with an optional CPSR def and its dag node
8314226633Sdim  // had a live implicit CPSR def, then activate the optional CPSR def.
8315226633Sdim  MachineOperand &MO = MI->getOperand(ccOutIdx);
8316226633Sdim  MO.setReg(ARM::CPSR);
8317226633Sdim  MO.setIsDef(true);
8318226633Sdim}
8319226633Sdim
8320193323Sed//===----------------------------------------------------------------------===//
8321193323Sed//                           ARM Optimization Hooks
8322193323Sed//===----------------------------------------------------------------------===//
8323193323Sed
8324239462Sdim// Helper function that checks if N is a null or all ones constant.
8325239462Sdimstatic inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8326296417Sdim  return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8327239462Sdim}
8328239462Sdim
8329243830Sdim// Return true if N is conditionally 0 or all ones.
8330243830Sdim// Detects these expressions where cc is an i1 value:
8331243830Sdim//
8332243830Sdim//   (select cc 0, y)   [AllOnes=0]
8333243830Sdim//   (select cc y, 0)   [AllOnes=0]
8334243830Sdim//   (zext cc)          [AllOnes=0]
8335243830Sdim//   (sext cc)          [AllOnes=0/1]
8336243830Sdim//   (select cc -1, y)  [AllOnes=1]
8337243830Sdim//   (select cc y, -1)  [AllOnes=1]
8338243830Sdim//
8339243830Sdim// Invert is set when N is the null/all ones constant when CC is false.
8340243830Sdim// OtherOp is set to the alternative value of N.
8341243830Sdimstatic bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8342243830Sdim                                       SDValue &CC, bool &Invert,
8343243830Sdim                                       SDValue &OtherOp,
8344243830Sdim                                       SelectionDAG &DAG) {
8345243830Sdim  switch (N->getOpcode()) {
8346243830Sdim  default: return false;
8347243830Sdim  case ISD::SELECT: {
8348243830Sdim    CC = N->getOperand(0);
8349243830Sdim    SDValue N1 = N->getOperand(1);
8350243830Sdim    SDValue N2 = N->getOperand(2);
8351243830Sdim    if (isZeroOrAllOnes(N1, AllOnes)) {
8352243830Sdim      Invert = false;
8353243830Sdim      OtherOp = N2;
8354243830Sdim      return true;
8355243830Sdim    }
8356243830Sdim    if (isZeroOrAllOnes(N2, AllOnes)) {
8357243830Sdim      Invert = true;
8358243830Sdim      OtherOp = N1;
8359243830Sdim      return true;
8360243830Sdim    }
8361243830Sdim    return false;
8362243830Sdim  }
8363243830Sdim  case ISD::ZERO_EXTEND:
8364243830Sdim    // (zext cc) can never be the all ones value.
8365243830Sdim    if (AllOnes)
8366243830Sdim      return false;
8367243830Sdim    // Fall through.
8368243830Sdim  case ISD::SIGN_EXTEND: {
8369288943Sdim    SDLoc dl(N);
8370243830Sdim    EVT VT = N->getValueType(0);
8371243830Sdim    CC = N->getOperand(0);
8372243830Sdim    if (CC.getValueType() != MVT::i1)
8373243830Sdim      return false;
8374243830Sdim    Invert = !AllOnes;
8375243830Sdim    if (AllOnes)
8376243830Sdim      // When looking for an AllOnes constant, N is an sext, and the 'other'
8377243830Sdim      // value is 0.
8378288943Sdim      OtherOp = DAG.getConstant(0, dl, VT);
8379243830Sdim    else if (N->getOpcode() == ISD::ZERO_EXTEND)
8380243830Sdim      // When looking for a 0 constant, N can be zext or sext.
8381288943Sdim      OtherOp = DAG.getConstant(1, dl, VT);
8382243830Sdim    else
8383288943Sdim      OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8384288943Sdim                                VT);
8385243830Sdim    return true;
8386243830Sdim  }
8387243830Sdim  }
8388243830Sdim}
8389243830Sdim
8390239462Sdim// Combine a constant select operand into its use:
8391239462Sdim//
8392243830Sdim//   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8393243830Sdim//   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8394243830Sdim//   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8395243830Sdim//   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8396243830Sdim//   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8397239462Sdim//
8398239462Sdim// The transform is rejected if the select doesn't have a constant operand that
8399243830Sdim// is null, or all ones when AllOnes is set.
8400239462Sdim//
8401243830Sdim// Also recognize sext/zext from i1:
8402243830Sdim//
8403243830Sdim//   (add (zext cc), x) -> (select cc (add x, 1), x)
8404243830Sdim//   (add (sext cc), x) -> (select cc (add x, -1), x)
8405243830Sdim//
8406243830Sdim// These transformations eventually create predicated instructions.
8407243830Sdim//
8408239462Sdim// @param N       The node to transform.
8409239462Sdim// @param Slct    The N operand that is a select.
8410239462Sdim// @param OtherOp The other N operand (x above).
8411239462Sdim// @param DCI     Context.
8412243830Sdim// @param AllOnes Require the select constant to be all ones instead of null.
8413239462Sdim// @returns The new node, or SDValue() on failure.
8414193323Sedstatic
8415193323SedSDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8416243830Sdim                            TargetLowering::DAGCombinerInfo &DCI,
8417243830Sdim                            bool AllOnes = false) {
8418193323Sed  SelectionDAG &DAG = DCI.DAG;
8419198090Srdivacky  EVT VT = N->getValueType(0);
8420243830Sdim  SDValue NonConstantVal;
8421243830Sdim  SDValue CCOp;
8422243830Sdim  bool SwapSelectOps;
8423243830Sdim  if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8424243830Sdim                                  NonConstantVal, DAG))
8425243830Sdim    return SDValue();
8426193323Sed
8427243830Sdim  // Slct is now know to be the desired identity constant when CC is true.
8428243830Sdim  SDValue TrueVal = OtherOp;
8429261991Sdim  SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8430243830Sdim                                 OtherOp, NonConstantVal);
8431243830Sdim  // Unless SwapSelectOps says CC should be false.
8432243830Sdim  if (SwapSelectOps)
8433243830Sdim    std::swap(TrueVal, FalseVal);
8434193323Sed
8435261991Sdim  return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8436243830Sdim                     CCOp, TrueVal, FalseVal);
8437243830Sdim}
8438193323Sed
8439243830Sdim// Attempt combineSelectAndUse on each operand of a commutative operator N.
8440243830Sdimstatic
8441243830SdimSDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8442243830Sdim                                       TargetLowering::DAGCombinerInfo &DCI) {
8443243830Sdim  SDValue N0 = N->getOperand(0);
8444243830Sdim  SDValue N1 = N->getOperand(1);
8445243830Sdim  if (N0.getNode()->hasOneUse()) {
8446243830Sdim    SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8447243830Sdim    if (Result.getNode())
8448243830Sdim      return Result;
8449193323Sed  }
8450243830Sdim  if (N1.getNode()->hasOneUse()) {
8451243830Sdim    SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8452243830Sdim    if (Result.getNode())
8453243830Sdim      return Result;
8454243830Sdim  }
8455243830Sdim  return SDValue();
8456193323Sed}
8457193323Sed
8458224145Sdim// AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8459224145Sdim// (only after legalization).
8460224145Sdimstatic SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8461224145Sdim                                 TargetLowering::DAGCombinerInfo &DCI,
8462224145Sdim                                 const ARMSubtarget *Subtarget) {
8463224145Sdim
8464224145Sdim  // Only perform optimization if after legalize, and if NEON is available. We
8465224145Sdim  // also expected both operands to be BUILD_VECTORs.
8466224145Sdim  if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8467224145Sdim      || N0.getOpcode() != ISD::BUILD_VECTOR
8468224145Sdim      || N1.getOpcode() != ISD::BUILD_VECTOR)
8469224145Sdim    return SDValue();
8470224145Sdim
8471224145Sdim  // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8472224145Sdim  EVT VT = N->getValueType(0);
8473224145Sdim  if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8474224145Sdim    return SDValue();
8475224145Sdim
8476224145Sdim  // Check that the vector operands are of the right form.
8477224145Sdim  // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8478224145Sdim  // operands, where N is the size of the formed vector.
8479224145Sdim  // Each EXTRACT_VECTOR should have the same input vector and odd or even
8480224145Sdim  // index such that we have a pair wise add pattern.
8481224145Sdim
8482224145Sdim  // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8483224145Sdim  if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8484224145Sdim    return SDValue();
8485224145Sdim  SDValue Vec = N0->getOperand(0)->getOperand(0);
8486224145Sdim  SDNode *V = Vec.getNode();
8487224145Sdim  unsigned nextIndex = 0;
8488224145Sdim
8489224145Sdim  // For each operands to the ADD which are BUILD_VECTORs,
8490224145Sdim  // check to see if each of their operands are an EXTRACT_VECTOR with
8491224145Sdim  // the same vector and appropriate index.
8492224145Sdim  for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8493224145Sdim    if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8494224145Sdim        && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8495224145Sdim
8496224145Sdim      SDValue ExtVec0 = N0->getOperand(i);
8497224145Sdim      SDValue ExtVec1 = N1->getOperand(i);
8498224145Sdim
8499224145Sdim      // First operand is the vector, verify its the same.
8500224145Sdim      if (V != ExtVec0->getOperand(0).getNode() ||
8501224145Sdim          V != ExtVec1->getOperand(0).getNode())
8502224145Sdim        return SDValue();
8503224145Sdim
8504224145Sdim      // Second is the constant, verify its correct.
8505224145Sdim      ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8506224145Sdim      ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8507224145Sdim
8508224145Sdim      // For the constant, we want to see all the even or all the odd.
8509224145Sdim      if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8510224145Sdim          || C1->getZExtValue() != nextIndex+1)
8511224145Sdim        return SDValue();
8512224145Sdim
8513224145Sdim      // Increment index.
8514224145Sdim      nextIndex+=2;
8515224145Sdim    } else
8516224145Sdim      return SDValue();
8517224145Sdim  }
8518224145Sdim
8519224145Sdim  // Create VPADDL node.
8520224145Sdim  SelectionDAG &DAG = DCI.DAG;
8521224145Sdim  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8522224145Sdim
8523288943Sdim  SDLoc dl(N);
8524288943Sdim
8525224145Sdim  // Build operand list.
8526224145Sdim  SmallVector<SDValue, 8> Ops;
8527288943Sdim  Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8528288943Sdim                                TLI.getPointerTy(DAG.getDataLayout())));
8529224145Sdim
8530224145Sdim  // Input is the vector.
8531224145Sdim  Ops.push_back(Vec);
8532224145Sdim
8533224145Sdim  // Get widened type and narrowed type.
8534224145Sdim  MVT widenType;
8535224145Sdim  unsigned numElem = VT.getVectorNumElements();
8536276479Sdim
8537276479Sdim  EVT inputLaneType = Vec.getValueType().getVectorElementType();
8538276479Sdim  switch (inputLaneType.getSimpleVT().SimpleTy) {
8539224145Sdim    case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8540224145Sdim    case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8541224145Sdim    case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8542224145Sdim    default:
8543234353Sdim      llvm_unreachable("Invalid vector element type for padd optimization.");
8544224145Sdim  }
8545224145Sdim
8546288943Sdim  SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8547276479Sdim  unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8548288943Sdim  return DAG.getNode(ExtOp, dl, VT, tmp);
8549224145Sdim}
8550224145Sdim
8551243830Sdimstatic SDValue findMUL_LOHI(SDValue V) {
8552243830Sdim  if (V->getOpcode() == ISD::UMUL_LOHI ||
8553243830Sdim      V->getOpcode() == ISD::SMUL_LOHI)
8554243830Sdim    return V;
8555243830Sdim  return SDValue();
8556243830Sdim}
8557243830Sdim
8558243830Sdimstatic SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8559243830Sdim                                     TargetLowering::DAGCombinerInfo &DCI,
8560243830Sdim                                     const ARMSubtarget *Subtarget) {
8561243830Sdim
8562243830Sdim  if (Subtarget->isThumb1Only()) return SDValue();
8563243830Sdim
8564243830Sdim  // Only perform the checks after legalize when the pattern is available.
8565243830Sdim  if (DCI.isBeforeLegalize()) return SDValue();
8566243830Sdim
8567243830Sdim  // Look for multiply add opportunities.
8568243830Sdim  // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8569243830Sdim  // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8570243830Sdim  // a glue link from the first add to the second add.
8571243830Sdim  // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8572243830Sdim  // a S/UMLAL instruction.
8573288943Sdim  //                  UMUL_LOHI
8574288943Sdim  //                 / :lo    \ :hi
8575288943Sdim  //                /          \          [no multiline comment]
8576288943Sdim  //    loAdd ->  ADDE         |
8577288943Sdim  //                 \ :glue  /
8578288943Sdim  //                  \      /
8579288943Sdim  //                    ADDC   <- hiAdd
8580243830Sdim  //
8581243830Sdim  assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8582243830Sdim  SDValue AddcOp0 = AddcNode->getOperand(0);
8583243830Sdim  SDValue AddcOp1 = AddcNode->getOperand(1);
8584243830Sdim
8585243830Sdim  // Check if the two operands are from the same mul_lohi node.
8586243830Sdim  if (AddcOp0.getNode() == AddcOp1.getNode())
8587243830Sdim    return SDValue();
8588243830Sdim
8589243830Sdim  assert(AddcNode->getNumValues() == 2 &&
8590243830Sdim         AddcNode->getValueType(0) == MVT::i32 &&
8591261991Sdim         "Expect ADDC with two result values. First: i32");
8592243830Sdim
8593261991Sdim  // Check that we have a glued ADDC node.
8594261991Sdim  if (AddcNode->getValueType(1) != MVT::Glue)
8595261991Sdim    return SDValue();
8596261991Sdim
8597243830Sdim  // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8598243830Sdim  if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8599243830Sdim      AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8600243830Sdim      AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8601243830Sdim      AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8602243830Sdim    return SDValue();
8603243830Sdim
8604243830Sdim  // Look for the glued ADDE.
8605243830Sdim  SDNode* AddeNode = AddcNode->getGluedUser();
8606276479Sdim  if (!AddeNode)
8607243830Sdim    return SDValue();
8608243830Sdim
8609243830Sdim  // Make sure it is really an ADDE.
8610243830Sdim  if (AddeNode->getOpcode() != ISD::ADDE)
8611243830Sdim    return SDValue();
8612243830Sdim
8613243830Sdim  assert(AddeNode->getNumOperands() == 3 &&
8614243830Sdim         AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8615243830Sdim         "ADDE node has the wrong inputs");
8616243830Sdim
8617243830Sdim  // Check for the triangle shape.
8618243830Sdim  SDValue AddeOp0 = AddeNode->getOperand(0);
8619243830Sdim  SDValue AddeOp1 = AddeNode->getOperand(1);
8620243830Sdim
8621243830Sdim  // Make sure that the ADDE operands are not coming from the same node.
8622243830Sdim  if (AddeOp0.getNode() == AddeOp1.getNode())
8623243830Sdim    return SDValue();
8624243830Sdim
8625243830Sdim  // Find the MUL_LOHI node walking up ADDE's operands.
8626243830Sdim  bool IsLeftOperandMUL = false;
8627243830Sdim  SDValue MULOp = findMUL_LOHI(AddeOp0);
8628243830Sdim  if (MULOp == SDValue())
8629243830Sdim   MULOp = findMUL_LOHI(AddeOp1);
8630243830Sdim  else
8631243830Sdim    IsLeftOperandMUL = true;
8632243830Sdim  if (MULOp == SDValue())
8633288943Sdim    return SDValue();
8634243830Sdim
8635243830Sdim  // Figure out the right opcode.
8636243830Sdim  unsigned Opc = MULOp->getOpcode();
8637243830Sdim  unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8638243830Sdim
8639243830Sdim  // Figure out the high and low input values to the MLAL node.
8640276479Sdim  SDValue* HiAdd = nullptr;
8641276479Sdim  SDValue* LoMul = nullptr;
8642276479Sdim  SDValue* LowAdd = nullptr;
8643243830Sdim
8644288943Sdim  // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8645288943Sdim  if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8646288943Sdim    return SDValue();
8647288943Sdim
8648243830Sdim  if (IsLeftOperandMUL)
8649243830Sdim    HiAdd = &AddeOp1;
8650243830Sdim  else
8651243830Sdim    HiAdd = &AddeOp0;
8652243830Sdim
8653243830Sdim
8654288943Sdim  // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8655288943Sdim  // whose low result is fed to the ADDC we are checking.
8656288943Sdim
8657288943Sdim  if (AddcOp0 == MULOp.getValue(0)) {
8658243830Sdim    LoMul = &AddcOp0;
8659243830Sdim    LowAdd = &AddcOp1;
8660243830Sdim  }
8661288943Sdim  if (AddcOp1 == MULOp.getValue(0)) {
8662243830Sdim    LoMul = &AddcOp1;
8663243830Sdim    LowAdd = &AddcOp0;
8664243830Sdim  }
8665243830Sdim
8666276479Sdim  if (!LoMul)
8667243830Sdim    return SDValue();
8668243830Sdim
8669243830Sdim  // Create the merged node.
8670243830Sdim  SelectionDAG &DAG = DCI.DAG;
8671243830Sdim
8672243830Sdim  // Build operand list.
8673243830Sdim  SmallVector<SDValue, 8> Ops;
8674243830Sdim  Ops.push_back(LoMul->getOperand(0));
8675243830Sdim  Ops.push_back(LoMul->getOperand(1));
8676243830Sdim  Ops.push_back(*LowAdd);
8677243830Sdim  Ops.push_back(*HiAdd);
8678243830Sdim
8679261991Sdim  SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8680276479Sdim                                 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8681243830Sdim
8682243830Sdim  // Replace the ADDs' nodes uses by the MLA node's values.
8683243830Sdim  SDValue HiMLALResult(MLALNode.getNode(), 1);
8684243830Sdim  DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8685243830Sdim
8686243830Sdim  SDValue LoMLALResult(MLALNode.getNode(), 0);
8687243830Sdim  DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8688243830Sdim
8689243830Sdim  // Return original node to notify the driver to stop replacing.
8690243830Sdim  SDValue resNode(AddcNode, 0);
8691243830Sdim  return resNode;
8692243830Sdim}
8693243830Sdim
8694243830Sdim/// PerformADDCCombine - Target-specific dag combine transform from
8695243830Sdim/// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8696243830Sdimstatic SDValue PerformADDCCombine(SDNode *N,
8697243830Sdim                                 TargetLowering::DAGCombinerInfo &DCI,
8698243830Sdim                                 const ARMSubtarget *Subtarget) {
8699243830Sdim
8700243830Sdim  return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8701243830Sdim
8702243830Sdim}
8703243830Sdim
8704212904Sdim/// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8705212904Sdim/// operands N0 and N1.  This is a helper for PerformADDCombine that is
8706212904Sdim/// called with the default operands, and if that fails, with commuted
8707212904Sdim/// operands.
8708212904Sdimstatic SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8709224145Sdim                                          TargetLowering::DAGCombinerInfo &DCI,
8710224145Sdim                                          const ARMSubtarget *Subtarget){
8711224145Sdim
8712224145Sdim  // Attempt to create vpaddl for this add.
8713224145Sdim  SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8714224145Sdim  if (Result.getNode())
8715224145Sdim    return Result;
8716224145Sdim
8717193323Sed  // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8718243830Sdim  if (N0.getNode()->hasOneUse()) {
8719193323Sed    SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8720193323Sed    if (Result.getNode()) return Result;
8721193323Sed  }
8722193323Sed  return SDValue();
8723193323Sed}
8724193323Sed
8725212904Sdim/// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8726212904Sdim///
8727212904Sdimstatic SDValue PerformADDCombine(SDNode *N,
8728224145Sdim                                 TargetLowering::DAGCombinerInfo &DCI,
8729224145Sdim                                 const ARMSubtarget *Subtarget) {
8730212904Sdim  SDValue N0 = N->getOperand(0);
8731212904Sdim  SDValue N1 = N->getOperand(1);
8732212904Sdim
8733212904Sdim  // First try with the default operand order.
8734224145Sdim  SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8735212904Sdim  if (Result.getNode())
8736212904Sdim    return Result;
8737212904Sdim
8738212904Sdim  // If that didn't work, try again with the operands commuted.
8739224145Sdim  return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8740212904Sdim}
8741212904Sdim
8742193323Sed/// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8743212904Sdim///
8744193323Sedstatic SDValue PerformSUBCombine(SDNode *N,
8745193323Sed                                 TargetLowering::DAGCombinerInfo &DCI) {
8746212904Sdim  SDValue N0 = N->getOperand(0);
8747212904Sdim  SDValue N1 = N->getOperand(1);
8748193323Sed
8749193323Sed  // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8750243830Sdim  if (N1.getNode()->hasOneUse()) {
8751193323Sed    SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8752193323Sed    if (Result.getNode()) return Result;
8753193323Sed  }
8754193323Sed
8755193323Sed  return SDValue();
8756193323Sed}
8757193323Sed
8758221345Sdim/// PerformVMULCombine
8759221345Sdim/// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8760221345Sdim/// special multiplier accumulator forwarding.
8761221345Sdim///   vmul d3, d0, d2
8762221345Sdim///   vmla d3, d1, d2
8763221345Sdim/// is faster than
8764221345Sdim///   vadd d3, d0, d1
8765221345Sdim///   vmul d3, d3, d2
8766261991Sdim//  However, for (A + B) * (A + B),
8767261991Sdim//    vadd d2, d0, d1
8768261991Sdim//    vmul d3, d0, d2
8769261991Sdim//    vmla d3, d1, d2
8770261991Sdim//  is slower than
8771261991Sdim//    vadd d2, d0, d1
8772261991Sdim//    vmul d3, d2, d2
8773221345Sdimstatic SDValue PerformVMULCombine(SDNode *N,
8774221345Sdim                                  TargetLowering::DAGCombinerInfo &DCI,
8775221345Sdim                                  const ARMSubtarget *Subtarget) {
8776221345Sdim  if (!Subtarget->hasVMLxForwarding())
8777221345Sdim    return SDValue();
8778221345Sdim
8779221345Sdim  SelectionDAG &DAG = DCI.DAG;
8780221345Sdim  SDValue N0 = N->getOperand(0);
8781221345Sdim  SDValue N1 = N->getOperand(1);
8782221345Sdim  unsigned Opcode = N0.getOpcode();
8783221345Sdim  if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8784221345Sdim      Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8785224145Sdim    Opcode = N1.getOpcode();
8786221345Sdim    if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8787221345Sdim        Opcode != ISD::FADD && Opcode != ISD::FSUB)
8788221345Sdim      return SDValue();
8789221345Sdim    std::swap(N0, N1);
8790221345Sdim  }
8791221345Sdim
8792261991Sdim  if (N0 == N1)
8793261991Sdim    return SDValue();
8794261991Sdim
8795221345Sdim  EVT VT = N->getValueType(0);
8796261991Sdim  SDLoc DL(N);
8797221345Sdim  SDValue N00 = N0->getOperand(0);
8798221345Sdim  SDValue N01 = N0->getOperand(1);
8799221345Sdim  return DAG.getNode(Opcode, DL, VT,
8800221345Sdim                     DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8801221345Sdim                     DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8802221345Sdim}
8803221345Sdim
8804208599Srdivackystatic SDValue PerformMULCombine(SDNode *N,
8805208599Srdivacky                                 TargetLowering::DAGCombinerInfo &DCI,
8806208599Srdivacky                                 const ARMSubtarget *Subtarget) {
8807208599Srdivacky  SelectionDAG &DAG = DCI.DAG;
8808208599Srdivacky
8809208599Srdivacky  if (Subtarget->isThumb1Only())
8810208599Srdivacky    return SDValue();
8811208599Srdivacky
8812208599Srdivacky  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8813208599Srdivacky    return SDValue();
8814208599Srdivacky
8815208599Srdivacky  EVT VT = N->getValueType(0);
8816221345Sdim  if (VT.is64BitVector() || VT.is128BitVector())
8817221345Sdim    return PerformVMULCombine(N, DCI, Subtarget);
8818208599Srdivacky  if (VT != MVT::i32)
8819208599Srdivacky    return SDValue();
8820208599Srdivacky
8821208599Srdivacky  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8822208599Srdivacky  if (!C)
8823208599Srdivacky    return SDValue();
8824208599Srdivacky
8825234353Sdim  int64_t MulAmt = C->getSExtValue();
8826261991Sdim  unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8827234353Sdim
8828208599Srdivacky  ShiftAmt = ShiftAmt & (32 - 1);
8829208599Srdivacky  SDValue V = N->getOperand(0);
8830261991Sdim  SDLoc DL(N);
8831208599Srdivacky
8832208599Srdivacky  SDValue Res;
8833208599Srdivacky  MulAmt >>= ShiftAmt;
8834208599Srdivacky
8835234353Sdim  if (MulAmt >= 0) {
8836234353Sdim    if (isPowerOf2_32(MulAmt - 1)) {
8837234353Sdim      // (mul x, 2^N + 1) => (add (shl x, N), x)
8838234353Sdim      Res = DAG.getNode(ISD::ADD, DL, VT,
8839234353Sdim                        V,
8840234353Sdim                        DAG.getNode(ISD::SHL, DL, VT,
8841234353Sdim                                    V,
8842288943Sdim                                    DAG.getConstant(Log2_32(MulAmt - 1), DL,
8843234353Sdim                                                    MVT::i32)));
8844234353Sdim    } else if (isPowerOf2_32(MulAmt + 1)) {
8845234353Sdim      // (mul x, 2^N - 1) => (sub (shl x, N), x)
8846234353Sdim      Res = DAG.getNode(ISD::SUB, DL, VT,
8847234353Sdim                        DAG.getNode(ISD::SHL, DL, VT,
8848234353Sdim                                    V,
8849288943Sdim                                    DAG.getConstant(Log2_32(MulAmt + 1), DL,
8850234353Sdim                                                    MVT::i32)),
8851234353Sdim                        V);
8852234353Sdim    } else
8853234353Sdim      return SDValue();
8854234353Sdim  } else {
8855234353Sdim    uint64_t MulAmtAbs = -MulAmt;
8856234353Sdim    if (isPowerOf2_32(MulAmtAbs + 1)) {
8857234353Sdim      // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8858234353Sdim      Res = DAG.getNode(ISD::SUB, DL, VT,
8859234353Sdim                        V,
8860234353Sdim                        DAG.getNode(ISD::SHL, DL, VT,
8861234353Sdim                                    V,
8862288943Sdim                                    DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8863234353Sdim                                                    MVT::i32)));
8864234353Sdim    } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8865234353Sdim      // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8866234353Sdim      Res = DAG.getNode(ISD::ADD, DL, VT,
8867234353Sdim                        V,
8868234353Sdim                        DAG.getNode(ISD::SHL, DL, VT,
8869234353Sdim                                    V,
8870288943Sdim                                    DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8871234353Sdim                                                    MVT::i32)));
8872234353Sdim      Res = DAG.getNode(ISD::SUB, DL, VT,
8873288943Sdim                        DAG.getConstant(0, DL, MVT::i32), Res);
8874234353Sdim
8875234353Sdim    } else
8876234353Sdim      return SDValue();
8877234353Sdim  }
8878234353Sdim
8879208599Srdivacky  if (ShiftAmt != 0)
8880234353Sdim    Res = DAG.getNode(ISD::SHL, DL, VT,
8881288943Sdim                      Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8882208599Srdivacky
8883208599Srdivacky  // Do not add new nodes to DAG combiner worklist.
8884208599Srdivacky  DCI.CombineTo(N, Res, false);
8885208599Srdivacky  return SDValue();
8886208599Srdivacky}
8887208599Srdivacky
8888218893Sdimstatic SDValue PerformANDCombine(SDNode *N,
8889234353Sdim                                 TargetLowering::DAGCombinerInfo &DCI,
8890234353Sdim                                 const ARMSubtarget *Subtarget) {
8891221345Sdim
8892218893Sdim  // Attempt to use immediate-form VBIC
8893218893Sdim  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8894261991Sdim  SDLoc dl(N);
8895218893Sdim  EVT VT = N->getValueType(0);
8896218893Sdim  SelectionDAG &DAG = DCI.DAG;
8897218893Sdim
8898221345Sdim  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8899221345Sdim    return SDValue();
8900221345Sdim
8901218893Sdim  APInt SplatBits, SplatUndef;
8902218893Sdim  unsigned SplatBitSize;
8903218893Sdim  bool HasAnyUndefs;
8904218893Sdim  if (BVN &&
8905218893Sdim      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8906218893Sdim    if (SplatBitSize <= 64) {
8907218893Sdim      EVT VbicVT;
8908218893Sdim      SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8909218893Sdim                                      SplatUndef.getZExtValue(), SplatBitSize,
8910288943Sdim                                      DAG, dl, VbicVT, VT.is128BitVector(),
8911218893Sdim                                      OtherModImm);
8912218893Sdim      if (Val.getNode()) {
8913218893Sdim        SDValue Input =
8914218893Sdim          DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8915218893Sdim        SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8916218893Sdim        return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8917218893Sdim      }
8918218893Sdim    }
8919218893Sdim  }
8920218893Sdim
8921234353Sdim  if (!Subtarget->isThumb1Only()) {
8922243830Sdim    // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8923243830Sdim    SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8924243830Sdim    if (Result.getNode())
8925243830Sdim      return Result;
8926234353Sdim  }
8927234353Sdim
8928218893Sdim  return SDValue();
8929218893Sdim}
8930218893Sdim
8931212904Sdim/// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8932212904Sdimstatic SDValue PerformORCombine(SDNode *N,
8933212904Sdim                                TargetLowering::DAGCombinerInfo &DCI,
8934212904Sdim                                const ARMSubtarget *Subtarget) {
8935218893Sdim  // Attempt to use immediate-form VORR
8936218893Sdim  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8937261991Sdim  SDLoc dl(N);
8938218893Sdim  EVT VT = N->getValueType(0);
8939218893Sdim  SelectionDAG &DAG = DCI.DAG;
8940218893Sdim
8941221345Sdim  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8942221345Sdim    return SDValue();
8943221345Sdim
8944218893Sdim  APInt SplatBits, SplatUndef;
8945218893Sdim  unsigned SplatBitSize;
8946218893Sdim  bool HasAnyUndefs;
8947218893Sdim  if (BVN && Subtarget->hasNEON() &&
8948218893Sdim      BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8949218893Sdim    if (SplatBitSize <= 64) {
8950218893Sdim      EVT VorrVT;
8951218893Sdim      SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8952218893Sdim                                      SplatUndef.getZExtValue(), SplatBitSize,
8953288943Sdim                                      DAG, dl, VorrVT, VT.is128BitVector(),
8954218893Sdim                                      OtherModImm);
8955218893Sdim      if (Val.getNode()) {
8956218893Sdim        SDValue Input =
8957218893Sdim          DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8958218893Sdim        SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8959218893Sdim        return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8960218893Sdim      }
8961218893Sdim    }
8962218893Sdim  }
8963218893Sdim
8964234353Sdim  if (!Subtarget->isThumb1Only()) {
8965243830Sdim    // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8966243830Sdim    SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8967243830Sdim    if (Result.getNode())
8968243830Sdim      return Result;
8969234353Sdim  }
8970234353Sdim
8971239462Sdim  // The code below optimizes (or (and X, Y), Z).
8972239462Sdim  // The AND operand needs to have a single user to make these optimizations
8973239462Sdim  // profitable.
8974221345Sdim  SDValue N0 = N->getOperand(0);
8975239462Sdim  if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8976221345Sdim    return SDValue();
8977221345Sdim  SDValue N1 = N->getOperand(1);
8978221345Sdim
8979221345Sdim  // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8980221345Sdim  if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8981221345Sdim      DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8982221345Sdim    APInt SplatUndef;
8983221345Sdim    unsigned SplatBitSize;
8984221345Sdim    bool HasAnyUndefs;
8985221345Sdim
8986261991Sdim    APInt SplatBits0, SplatBits1;
8987221345Sdim    BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8988261991Sdim    BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8989261991Sdim    // Ensure that the second operand of both ands are constants
8990221345Sdim    if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8991261991Sdim                                      HasAnyUndefs) && !HasAnyUndefs) {
8992261991Sdim        if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8993261991Sdim                                          HasAnyUndefs) && !HasAnyUndefs) {
8994261991Sdim            // Ensure that the bit width of the constants are the same and that
8995261991Sdim            // the splat arguments are logical inverses as per the pattern we
8996261991Sdim            // are trying to simplify.
8997261991Sdim            if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8998261991Sdim                SplatBits0 == ~SplatBits1) {
8999261991Sdim                // Canonicalize the vector type to make instruction selection
9000261991Sdim                // simpler.
9001261991Sdim                EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9002261991Sdim                SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9003261991Sdim                                             N0->getOperand(1),
9004261991Sdim                                             N0->getOperand(0),
9005261991Sdim                                             N1->getOperand(0));
9006261991Sdim                return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9007261991Sdim            }
9008261991Sdim        }
9009221345Sdim    }
9010221345Sdim  }
9011221345Sdim
9012212904Sdim  // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9013212904Sdim  // reasonable.
9014212904Sdim
9015212904Sdim  // BFI is only available on V6T2+
9016212904Sdim  if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9017212904Sdim    return SDValue();
9018212904Sdim
9019261991Sdim  SDLoc DL(N);
9020212904Sdim  // 1) or (and A, mask), val => ARMbfi A, val, mask
9021212904Sdim  //      iff (val & mask) == val
9022212904Sdim  //
9023212904Sdim  // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9024212904Sdim  //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9025221345Sdim  //          && mask == ~mask2
9026212904Sdim  //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9027221345Sdim  //          && ~mask == mask2
9028212904Sdim  //  (i.e., copy a bitfield value into another bitfield of the same width)
9029212904Sdim
9030212904Sdim  if (VT != MVT::i32)
9031212904Sdim    return SDValue();
9032212904Sdim
9033218893Sdim  SDValue N00 = N0.getOperand(0);
9034212904Sdim
9035212904Sdim  // The value and the mask need to be constants so we can verify this is
9036212904Sdim  // actually a bitfield set. If the mask is 0xffff, we can do better
9037212904Sdim  // via a movt instruction, so don't use BFI in that case.
9038218893Sdim  SDValue MaskOp = N0.getOperand(1);
9039218893Sdim  ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9040218893Sdim  if (!MaskC)
9041212904Sdim    return SDValue();
9042218893Sdim  unsigned Mask = MaskC->getZExtValue();
9043212904Sdim  if (Mask == 0xffff)
9044212904Sdim    return SDValue();
9045212904Sdim  SDValue Res;
9046212904Sdim  // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9047218893Sdim  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9048218893Sdim  if (N1C) {
9049218893Sdim    unsigned Val = N1C->getZExtValue();
9050218893Sdim    if ((Val & ~Mask) != Val)
9051212904Sdim      return SDValue();
9052212904Sdim
9053218893Sdim    if (ARM::isBitFieldInvertedMask(Mask)) {
9054261991Sdim      Val >>= countTrailingZeros(~Mask);
9055212904Sdim
9056218893Sdim      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9057288943Sdim                        DAG.getConstant(Val, DL, MVT::i32),
9058288943Sdim                        DAG.getConstant(Mask, DL, MVT::i32));
9059218893Sdim
9060218893Sdim      // Do not add new nodes to DAG combiner worklist.
9061218893Sdim      DCI.CombineTo(N, Res, false);
9062218893Sdim      return SDValue();
9063218893Sdim    }
9064212904Sdim  } else if (N1.getOpcode() == ISD::AND) {
9065212904Sdim    // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9066218893Sdim    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9067218893Sdim    if (!N11C)
9068212904Sdim      return SDValue();
9069218893Sdim    unsigned Mask2 = N11C->getZExtValue();
9070212904Sdim
9071221345Sdim    // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9072221345Sdim    // as is to match.
9073212904Sdim    if (ARM::isBitFieldInvertedMask(Mask) &&
9074221345Sdim        (Mask == ~Mask2)) {
9075212904Sdim      // The pack halfword instruction works better for masks that fit it,
9076212904Sdim      // so use that when it's available.
9077212904Sdim      if (Subtarget->hasT2ExtractPack() &&
9078212904Sdim          (Mask == 0xffff || Mask == 0xffff0000))
9079212904Sdim        return SDValue();
9080212904Sdim      // 2a
9081261991Sdim      unsigned amt = countTrailingZeros(Mask2);
9082212904Sdim      Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9083288943Sdim                        DAG.getConstant(amt, DL, MVT::i32));
9084218893Sdim      Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9085288943Sdim                        DAG.getConstant(Mask, DL, MVT::i32));
9086212904Sdim      // Do not add new nodes to DAG combiner worklist.
9087212904Sdim      DCI.CombineTo(N, Res, false);
9088218893Sdim      return SDValue();
9089212904Sdim    } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9090221345Sdim               (~Mask == Mask2)) {
9091212904Sdim      // The pack halfword instruction works better for masks that fit it,
9092212904Sdim      // so use that when it's available.
9093212904Sdim      if (Subtarget->hasT2ExtractPack() &&
9094212904Sdim          (Mask2 == 0xffff || Mask2 == 0xffff0000))
9095212904Sdim        return SDValue();
9096212904Sdim      // 2b
9097261991Sdim      unsigned lsb = countTrailingZeros(Mask);
9098218893Sdim      Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9099288943Sdim                        DAG.getConstant(lsb, DL, MVT::i32));
9100212904Sdim      Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9101288943Sdim                        DAG.getConstant(Mask2, DL, MVT::i32));
9102212904Sdim      // Do not add new nodes to DAG combiner worklist.
9103212904Sdim      DCI.CombineTo(N, Res, false);
9104218893Sdim      return SDValue();
9105212904Sdim    }
9106212904Sdim  }
9107212904Sdim
9108218893Sdim  if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9109218893Sdim      N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9110218893Sdim      ARM::isBitFieldInvertedMask(~Mask)) {
9111218893Sdim    // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9112218893Sdim    // where lsb(mask) == #shamt and masked bits of B are known zero.
9113218893Sdim    SDValue ShAmt = N00.getOperand(1);
9114218893Sdim    unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9115261991Sdim    unsigned LSB = countTrailingZeros(Mask);
9116218893Sdim    if (ShAmtC != LSB)
9117218893Sdim      return SDValue();
9118218893Sdim
9119218893Sdim    Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9120288943Sdim                      DAG.getConstant(~Mask, DL, MVT::i32));
9121218893Sdim
9122218893Sdim    // Do not add new nodes to DAG combiner worklist.
9123218893Sdim    DCI.CombineTo(N, Res, false);
9124218893Sdim  }
9125218893Sdim
9126212904Sdim  return SDValue();
9127212904Sdim}
9128212904Sdim
9129234353Sdimstatic SDValue PerformXORCombine(SDNode *N,
9130234353Sdim                                 TargetLowering::DAGCombinerInfo &DCI,
9131234353Sdim                                 const ARMSubtarget *Subtarget) {
9132234353Sdim  EVT VT = N->getValueType(0);
9133234353Sdim  SelectionDAG &DAG = DCI.DAG;
9134234353Sdim
9135234353Sdim  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9136234353Sdim    return SDValue();
9137234353Sdim
9138234353Sdim  if (!Subtarget->isThumb1Only()) {
9139243830Sdim    // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9140243830Sdim    SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9141243830Sdim    if (Result.getNode())
9142243830Sdim      return Result;
9143234353Sdim  }
9144234353Sdim
9145234353Sdim  return SDValue();
9146234353Sdim}
9147234353Sdim
9148296417Sdim// ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9149296417Sdim// and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9150296417Sdim// their position in "to" (Rd).
9151296417Sdimstatic SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9152296417Sdim  assert(N->getOpcode() == ARMISD::BFI);
9153296417Sdim
9154296417Sdim  SDValue From = N->getOperand(1);
9155296417Sdim  ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9156296417Sdim  FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9157296417Sdim
9158296417Sdim  // If the Base came from a SHR #C, we can deduce that it is really testing bit
9159296417Sdim  // #C in the base of the SHR.
9160296417Sdim  if (From->getOpcode() == ISD::SRL &&
9161296417Sdim      isa<ConstantSDNode>(From->getOperand(1))) {
9162296417Sdim    APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9163296417Sdim    assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9164296417Sdim    FromMask <<= Shift.getLimitedValue(31);
9165296417Sdim    From = From->getOperand(0);
9166296417Sdim  }
9167296417Sdim
9168296417Sdim  return From;
9169296417Sdim}
9170296417Sdim
9171296417Sdim// If A and B contain one contiguous set of bits, does A | B == A . B?
9172296417Sdim//
9173296417Sdim// Neither A nor B must be zero.
9174296417Sdimstatic bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9175296417Sdim  unsigned LastActiveBitInA =  A.countTrailingZeros();
9176296417Sdim  unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9177296417Sdim  return LastActiveBitInA - 1 == FirstActiveBitInB;
9178296417Sdim}
9179296417Sdim
9180296417Sdimstatic SDValue FindBFIToCombineWith(SDNode *N) {
9181296417Sdim  // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9182296417Sdim  // if one exists.
9183296417Sdim  APInt ToMask, FromMask;
9184296417Sdim  SDValue From = ParseBFI(N, ToMask, FromMask);
9185296417Sdim  SDValue To = N->getOperand(0);
9186296417Sdim
9187296417Sdim  // Now check for a compatible BFI to merge with. We can pass through BFIs that
9188296417Sdim  // aren't compatible, but not if they set the same bit in their destination as
9189296417Sdim  // we do (or that of any BFI we're going to combine with).
9190296417Sdim  SDValue V = To;
9191296417Sdim  APInt CombinedToMask = ToMask;
9192296417Sdim  while (V.getOpcode() == ARMISD::BFI) {
9193296417Sdim    APInt NewToMask, NewFromMask;
9194296417Sdim    SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9195296417Sdim    if (NewFrom != From) {
9196296417Sdim      // This BFI has a different base. Keep going.
9197296417Sdim      CombinedToMask |= NewToMask;
9198296417Sdim      V = V.getOperand(0);
9199296417Sdim      continue;
9200296417Sdim    }
9201296417Sdim
9202296417Sdim    // Do the written bits conflict with any we've seen so far?
9203296417Sdim    if ((NewToMask & CombinedToMask).getBoolValue())
9204296417Sdim      // Conflicting bits - bail out because going further is unsafe.
9205296417Sdim      return SDValue();
9206296417Sdim
9207296417Sdim    // Are the new bits contiguous when combined with the old bits?
9208296417Sdim    if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9209296417Sdim        BitsProperlyConcatenate(FromMask, NewFromMask))
9210296417Sdim      return V;
9211296417Sdim    if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9212296417Sdim        BitsProperlyConcatenate(NewFromMask, FromMask))
9213296417Sdim      return V;
9214296417Sdim
9215296417Sdim    // We've seen a write to some bits, so track it.
9216296417Sdim    CombinedToMask |= NewToMask;
9217296417Sdim    // Keep going...
9218296417Sdim    V = V.getOperand(0);
9219296417Sdim  }
9220296417Sdim
9221296417Sdim  return SDValue();
9222296417Sdim}
9223296417Sdim
9224218893Sdimstatic SDValue PerformBFICombine(SDNode *N,
9225218893Sdim                                 TargetLowering::DAGCombinerInfo &DCI) {
9226218893Sdim  SDValue N1 = N->getOperand(1);
9227218893Sdim  if (N1.getOpcode() == ISD::AND) {
9228296417Sdim    // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9229296417Sdim    // the bits being cleared by the AND are not demanded by the BFI.
9230218893Sdim    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9231218893Sdim    if (!N11C)
9232218893Sdim      return SDValue();
9233224145Sdim    unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9234261991Sdim    unsigned LSB = countTrailingZeros(~InvMask);
9235261991Sdim    unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9236280031Sdim    assert(Width <
9237280031Sdim               static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9238280031Sdim           "undefined behavior");
9239280031Sdim    unsigned Mask = (1u << Width) - 1;
9240218893Sdim    unsigned Mask2 = N11C->getZExtValue();
9241224145Sdim    if ((Mask & (~Mask2)) == 0)
9242261991Sdim      return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9243218893Sdim                             N->getOperand(0), N1.getOperand(0),
9244218893Sdim                             N->getOperand(2));
9245296417Sdim  } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9246296417Sdim    // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9247296417Sdim    // Keep track of any consecutive bits set that all come from the same base
9248296417Sdim    // value. We can combine these together into a single BFI.
9249296417Sdim    SDValue CombineBFI = FindBFIToCombineWith(N);
9250296417Sdim    if (CombineBFI == SDValue())
9251296417Sdim      return SDValue();
9252296417Sdim
9253296417Sdim    // We've found a BFI.
9254296417Sdim    APInt ToMask1, FromMask1;
9255296417Sdim    SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9256296417Sdim
9257296417Sdim    APInt ToMask2, FromMask2;
9258296417Sdim    SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9259296417Sdim    assert(From1 == From2);
9260296417Sdim    (void)From2;
9261296417Sdim
9262296417Sdim    // First, unlink CombineBFI.
9263296417Sdim    DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9264296417Sdim    // Then create a new BFI, combining the two together.
9265296417Sdim    APInt NewFromMask = FromMask1 | FromMask2;
9266296417Sdim    APInt NewToMask = ToMask1 | ToMask2;
9267296417Sdim
9268296417Sdim    EVT VT = N->getValueType(0);
9269296417Sdim    SDLoc dl(N);
9270296417Sdim
9271296417Sdim    if (NewFromMask[0] == 0)
9272296417Sdim      From1 = DCI.DAG.getNode(
9273296417Sdim        ISD::SRL, dl, VT, From1,
9274296417Sdim        DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9275296417Sdim    return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9276296417Sdim                           DCI.DAG.getConstant(~NewToMask, dl, VT));
9277218893Sdim  }
9278218893Sdim  return SDValue();
9279218893Sdim}
9280218893Sdim
9281202878Srdivacky/// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9282202878Srdivacky/// ARMISD::VMOVRRD.
9283199481Srdivackystatic SDValue PerformVMOVRRDCombine(SDNode *N,
9284280031Sdim                                     TargetLowering::DAGCombinerInfo &DCI,
9285280031Sdim                                     const ARMSubtarget *Subtarget) {
9286218893Sdim  // vmovrrd(vmovdrr x, y) -> x,y
9287193323Sed  SDValue InDouble = N->getOperand(0);
9288280031Sdim  if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9289193323Sed    return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9290221345Sdim
9291221345Sdim  // vmovrrd(load f64) -> (load i32), (load i32)
9292221345Sdim  SDNode *InNode = InDouble.getNode();
9293221345Sdim  if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9294221345Sdim      InNode->getValueType(0) == MVT::f64 &&
9295221345Sdim      InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9296221345Sdim      !cast<LoadSDNode>(InNode)->isVolatile()) {
9297221345Sdim    // TODO: Should this be done for non-FrameIndex operands?
9298221345Sdim    LoadSDNode *LD = cast<LoadSDNode>(InNode);
9299221345Sdim
9300221345Sdim    SelectionDAG &DAG = DCI.DAG;
9301261991Sdim    SDLoc DL(LD);
9302221345Sdim    SDValue BasePtr = LD->getBasePtr();
9303221345Sdim    SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9304221345Sdim                                 LD->getPointerInfo(), LD->isVolatile(),
9305234353Sdim                                 LD->isNonTemporal(), LD->isInvariant(),
9306234353Sdim                                 LD->getAlignment());
9307221345Sdim
9308221345Sdim    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9309288943Sdim                                    DAG.getConstant(4, DL, MVT::i32));
9310221345Sdim    SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9311221345Sdim                                 LD->getPointerInfo(), LD->isVolatile(),
9312234353Sdim                                 LD->isNonTemporal(), LD->isInvariant(),
9313221345Sdim                                 std::min(4U, LD->getAlignment() / 2));
9314221345Sdim
9315221345Sdim    DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9316288943Sdim    if (DCI.DAG.getDataLayout().isBigEndian())
9317276479Sdim      std::swap (NewLD1, NewLD2);
9318221345Sdim    SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9319221345Sdim    return Result;
9320221345Sdim  }
9321221345Sdim
9322193323Sed  return SDValue();
9323193323Sed}
9324193323Sed
9325218893Sdim/// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9326218893Sdim/// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9327218893Sdimstatic SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9328218893Sdim  // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9329218893Sdim  SDValue Op0 = N->getOperand(0);
9330218893Sdim  SDValue Op1 = N->getOperand(1);
9331218893Sdim  if (Op0.getOpcode() == ISD::BITCAST)
9332218893Sdim    Op0 = Op0.getOperand(0);
9333218893Sdim  if (Op1.getOpcode() == ISD::BITCAST)
9334218893Sdim    Op1 = Op1.getOperand(0);
9335218893Sdim  if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9336218893Sdim      Op0.getNode() == Op1.getNode() &&
9337218893Sdim      Op0.getResNo() == 0 && Op1.getResNo() == 1)
9338261991Sdim    return DAG.getNode(ISD::BITCAST, SDLoc(N),
9339218893Sdim                       N->getValueType(0), Op0.getOperand(0));
9340218893Sdim  return SDValue();
9341218893Sdim}
9342218893Sdim
9343218893Sdim/// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9344218893Sdim/// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9345218893Sdim/// i64 vector to have f64 elements, since the value can then be loaded
9346218893Sdim/// directly into a VFP register.
9347218893Sdimstatic bool hasNormalLoadOperand(SDNode *N) {
9348218893Sdim  unsigned NumElts = N->getValueType(0).getVectorNumElements();
9349218893Sdim  for (unsigned i = 0; i < NumElts; ++i) {
9350218893Sdim    SDNode *Elt = N->getOperand(i).getNode();
9351218893Sdim    if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9352218893Sdim      return true;
9353218893Sdim  }
9354218893Sdim  return false;
9355218893Sdim}
9356218893Sdim
9357218893Sdim/// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9358218893Sdim/// ISD::BUILD_VECTOR.
9359218893Sdimstatic SDValue PerformBUILD_VECTORCombine(SDNode *N,
9360280031Sdim                                          TargetLowering::DAGCombinerInfo &DCI,
9361280031Sdim                                          const ARMSubtarget *Subtarget) {
9362218893Sdim  // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9363218893Sdim  // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9364218893Sdim  // into a pair of GPRs, which is fine when the value is used as a scalar,
9365218893Sdim  // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9366218893Sdim  SelectionDAG &DAG = DCI.DAG;
9367218893Sdim  if (N->getNumOperands() == 2) {
9368218893Sdim    SDValue RV = PerformVMOVDRRCombine(N, DAG);
9369218893Sdim    if (RV.getNode())
9370218893Sdim      return RV;
9371218893Sdim  }
9372218893Sdim
9373218893Sdim  // Load i64 elements as f64 values so that type legalization does not split
9374218893Sdim  // them up into i32 values.
9375218893Sdim  EVT VT = N->getValueType(0);
9376218893Sdim  if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9377218893Sdim    return SDValue();
9378261991Sdim  SDLoc dl(N);
9379218893Sdim  SmallVector<SDValue, 8> Ops;
9380218893Sdim  unsigned NumElts = VT.getVectorNumElements();
9381218893Sdim  for (unsigned i = 0; i < NumElts; ++i) {
9382218893Sdim    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9383218893Sdim    Ops.push_back(V);
9384218893Sdim    // Make the DAGCombiner fold the bitcast.
9385218893Sdim    DCI.AddToWorklist(V.getNode());
9386218893Sdim  }
9387218893Sdim  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9388276479Sdim  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9389218893Sdim  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9390218893Sdim}
9391218893Sdim
9392261991Sdim/// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9393261991Sdimstatic SDValue
9394261991SdimPerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9395261991Sdim  // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9396261991Sdim  // At that time, we may have inserted bitcasts from integer to float.
9397261991Sdim  // If these bitcasts have survived DAGCombine, change the lowering of this
9398261991Sdim  // BUILD_VECTOR in something more vector friendly, i.e., that does not
9399261991Sdim  // force to use floating point types.
9400261991Sdim
9401261991Sdim  // Make sure we can change the type of the vector.
9402261991Sdim  // This is possible iff:
9403261991Sdim  // 1. The vector is only used in a bitcast to a integer type. I.e.,
9404261991Sdim  //    1.1. Vector is used only once.
9405261991Sdim  //    1.2. Use is a bit convert to an integer type.
9406261991Sdim  // 2. The size of its operands are 32-bits (64-bits are not legal).
9407261991Sdim  EVT VT = N->getValueType(0);
9408261991Sdim  EVT EltVT = VT.getVectorElementType();
9409261991Sdim
9410261991Sdim  // Check 1.1. and 2.
9411261991Sdim  if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9412261991Sdim    return SDValue();
9413261991Sdim
9414261991Sdim  // By construction, the input type must be float.
9415261991Sdim  assert(EltVT == MVT::f32 && "Unexpected type!");
9416261991Sdim
9417261991Sdim  // Check 1.2.
9418261991Sdim  SDNode *Use = *N->use_begin();
9419261991Sdim  if (Use->getOpcode() != ISD::BITCAST ||
9420261991Sdim      Use->getValueType(0).isFloatingPoint())
9421261991Sdim    return SDValue();
9422261991Sdim
9423261991Sdim  // Check profitability.
9424261991Sdim  // Model is, if more than half of the relevant operands are bitcast from
9425261991Sdim  // i32, turn the build_vector into a sequence of insert_vector_elt.
9426261991Sdim  // Relevant operands are everything that is not statically
9427261991Sdim  // (i.e., at compile time) bitcasted.
9428261991Sdim  unsigned NumOfBitCastedElts = 0;
9429261991Sdim  unsigned NumElts = VT.getVectorNumElements();
9430261991Sdim  unsigned NumOfRelevantElts = NumElts;
9431261991Sdim  for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9432261991Sdim    SDValue Elt = N->getOperand(Idx);
9433261991Sdim    if (Elt->getOpcode() == ISD::BITCAST) {
9434261991Sdim      // Assume only bit cast to i32 will go away.
9435261991Sdim      if (Elt->getOperand(0).getValueType() == MVT::i32)
9436261991Sdim        ++NumOfBitCastedElts;
9437261991Sdim    } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9438261991Sdim      // Constants are statically casted, thus do not count them as
9439261991Sdim      // relevant operands.
9440261991Sdim      --NumOfRelevantElts;
9441261991Sdim  }
9442261991Sdim
9443261991Sdim  // Check if more than half of the elements require a non-free bitcast.
9444261991Sdim  if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9445261991Sdim    return SDValue();
9446261991Sdim
9447261991Sdim  SelectionDAG &DAG = DCI.DAG;
9448261991Sdim  // Create the new vector type.
9449261991Sdim  EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9450261991Sdim  // Check if the type is legal.
9451261991Sdim  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9452261991Sdim  if (!TLI.isTypeLegal(VecVT))
9453261991Sdim    return SDValue();
9454261991Sdim
9455261991Sdim  // Combine:
9456261991Sdim  // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9457261991Sdim  // => BITCAST INSERT_VECTOR_ELT
9458261991Sdim  //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9459261991Sdim  //                      (BITCAST EN), N.
9460261991Sdim  SDValue Vec = DAG.getUNDEF(VecVT);
9461261991Sdim  SDLoc dl(N);
9462261991Sdim  for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9463261991Sdim    SDValue V = N->getOperand(Idx);
9464261991Sdim    if (V.getOpcode() == ISD::UNDEF)
9465261991Sdim      continue;
9466261991Sdim    if (V.getOpcode() == ISD::BITCAST &&
9467261991Sdim        V->getOperand(0).getValueType() == MVT::i32)
9468261991Sdim      // Fold obvious case.
9469261991Sdim      V = V.getOperand(0);
9470261991Sdim    else {
9471276479Sdim      V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9472261991Sdim      // Make the DAGCombiner fold the bitcasts.
9473261991Sdim      DCI.AddToWorklist(V.getNode());
9474261991Sdim    }
9475288943Sdim    SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9476261991Sdim    Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9477261991Sdim  }
9478261991Sdim  Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9479261991Sdim  // Make the DAGCombiner fold the bitcasts.
9480261991Sdim  DCI.AddToWorklist(Vec.getNode());
9481261991Sdim  return Vec;
9482261991Sdim}
9483261991Sdim
9484218893Sdim/// PerformInsertEltCombine - Target-specific dag combine xforms for
9485218893Sdim/// ISD::INSERT_VECTOR_ELT.
9486218893Sdimstatic SDValue PerformInsertEltCombine(SDNode *N,
9487218893Sdim                                       TargetLowering::DAGCombinerInfo &DCI) {
9488218893Sdim  // Bitcast an i64 load inserted into a vector to f64.
9489218893Sdim  // Otherwise, the i64 value will be legalized to a pair of i32 values.
9490218893Sdim  EVT VT = N->getValueType(0);
9491218893Sdim  SDNode *Elt = N->getOperand(1).getNode();
9492218893Sdim  if (VT.getVectorElementType() != MVT::i64 ||
9493218893Sdim      !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9494218893Sdim    return SDValue();
9495218893Sdim
9496218893Sdim  SelectionDAG &DAG = DCI.DAG;
9497261991Sdim  SDLoc dl(N);
9498218893Sdim  EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9499218893Sdim                                 VT.getVectorNumElements());
9500218893Sdim  SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9501218893Sdim  SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9502218893Sdim  // Make the DAGCombiner fold the bitcasts.
9503218893Sdim  DCI.AddToWorklist(Vec.getNode());
9504218893Sdim  DCI.AddToWorklist(V.getNode());
9505218893Sdim  SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9506218893Sdim                               Vec, V, N->getOperand(2));
9507218893Sdim  return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9508218893Sdim}
9509218893Sdim
9510218893Sdim/// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9511218893Sdim/// ISD::VECTOR_SHUFFLE.
9512218893Sdimstatic SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9513218893Sdim  // The LLVM shufflevector instruction does not require the shuffle mask
9514218893Sdim  // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9515218893Sdim  // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9516218893Sdim  // operands do not match the mask length, they are extended by concatenating
9517218893Sdim  // them with undef vectors.  That is probably the right thing for other
9518218893Sdim  // targets, but for NEON it is better to concatenate two double-register
9519218893Sdim  // size vector operands into a single quad-register size vector.  Do that
9520218893Sdim  // transformation here:
9521218893Sdim  //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9522218893Sdim  //   shuffle(concat(v1, v2), undef)
9523218893Sdim  SDValue Op0 = N->getOperand(0);
9524218893Sdim  SDValue Op1 = N->getOperand(1);
9525218893Sdim  if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9526218893Sdim      Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9527218893Sdim      Op0.getNumOperands() != 2 ||
9528218893Sdim      Op1.getNumOperands() != 2)
9529218893Sdim    return SDValue();
9530218893Sdim  SDValue Concat0Op1 = Op0.getOperand(1);
9531218893Sdim  SDValue Concat1Op1 = Op1.getOperand(1);
9532218893Sdim  if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9533218893Sdim      Concat1Op1.getOpcode() != ISD::UNDEF)
9534218893Sdim    return SDValue();
9535218893Sdim  // Skip the transformation if any of the types are illegal.
9536218893Sdim  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9537218893Sdim  EVT VT = N->getValueType(0);
9538218893Sdim  if (!TLI.isTypeLegal(VT) ||
9539218893Sdim      !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9540218893Sdim      !TLI.isTypeLegal(Concat1Op1.getValueType()))
9541218893Sdim    return SDValue();
9542218893Sdim
9543261991Sdim  SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9544218893Sdim                                  Op0.getOperand(0), Op1.getOperand(0));
9545218893Sdim  // Translate the shuffle mask.
9546218893Sdim  SmallVector<int, 16> NewMask;
9547218893Sdim  unsigned NumElts = VT.getVectorNumElements();
9548218893Sdim  unsigned HalfElts = NumElts/2;
9549218893Sdim  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9550218893Sdim  for (unsigned n = 0; n < NumElts; ++n) {
9551218893Sdim    int MaskElt = SVN->getMaskElt(n);
9552218893Sdim    int NewElt = -1;
9553218893Sdim    if (MaskElt < (int)HalfElts)
9554218893Sdim      NewElt = MaskElt;
9555218893Sdim    else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9556218893Sdim      NewElt = HalfElts + MaskElt - NumElts;
9557218893Sdim    NewMask.push_back(NewElt);
9558218893Sdim  }
9559261991Sdim  return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9560218893Sdim                              DAG.getUNDEF(VT), NewMask.data());
9561218893Sdim}
9562218893Sdim
9563288943Sdim/// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9564288943Sdim/// NEON load/store intrinsics, and generic vector load/stores, to merge
9565288943Sdim/// base address updates.
9566288943Sdim/// For generic load/stores, the memory type is assumed to be a vector.
9567288943Sdim/// The caller is assumed to have checked legality.
9568218893Sdimstatic SDValue CombineBaseUpdate(SDNode *N,
9569218893Sdim                                 TargetLowering::DAGCombinerInfo &DCI) {
9570218893Sdim  SelectionDAG &DAG = DCI.DAG;
9571288943Sdim  const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9572288943Sdim                            N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9573288943Sdim  const bool isStore = N->getOpcode() == ISD::STORE;
9574288943Sdim  const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9575218893Sdim  SDValue Addr = N->getOperand(AddrOpIdx);
9576288943Sdim  MemSDNode *MemN = cast<MemSDNode>(N);
9577288943Sdim  SDLoc dl(N);
9578218893Sdim
9579218893Sdim  // Search for a use of the address operand that is an increment.
9580218893Sdim  for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9581218893Sdim         UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9582218893Sdim    SDNode *User = *UI;
9583218893Sdim    if (User->getOpcode() != ISD::ADD ||
9584218893Sdim        UI.getUse().getResNo() != Addr.getResNo())
9585218893Sdim      continue;
9586218893Sdim
9587218893Sdim    // Check that the add is independent of the load/store.  Otherwise, folding
9588218893Sdim    // it would create a cycle.
9589218893Sdim    if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9590218893Sdim      continue;
9591218893Sdim
9592218893Sdim    // Find the new opcode for the updating load/store.
9593288943Sdim    bool isLoadOp = true;
9594218893Sdim    bool isLaneOp = false;
9595218893Sdim    unsigned NewOpc = 0;
9596218893Sdim    unsigned NumVecs = 0;
9597218893Sdim    if (isIntrinsic) {
9598218893Sdim      unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9599218893Sdim      switch (IntNo) {
9600234353Sdim      default: llvm_unreachable("unexpected intrinsic for Neon base update");
9601218893Sdim      case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9602218893Sdim        NumVecs = 1; break;
9603218893Sdim      case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9604218893Sdim        NumVecs = 2; break;
9605218893Sdim      case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9606218893Sdim        NumVecs = 3; break;
9607218893Sdim      case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9608218893Sdim        NumVecs = 4; break;
9609218893Sdim      case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9610218893Sdim        NumVecs = 2; isLaneOp = true; break;
9611218893Sdim      case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9612218893Sdim        NumVecs = 3; isLaneOp = true; break;
9613218893Sdim      case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9614218893Sdim        NumVecs = 4; isLaneOp = true; break;
9615218893Sdim      case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9616288943Sdim        NumVecs = 1; isLoadOp = false; break;
9617218893Sdim      case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9618288943Sdim        NumVecs = 2; isLoadOp = false; break;
9619218893Sdim      case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9620288943Sdim        NumVecs = 3; isLoadOp = false; break;
9621218893Sdim      case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9622288943Sdim        NumVecs = 4; isLoadOp = false; break;
9623218893Sdim      case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9624288943Sdim        NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9625218893Sdim      case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9626288943Sdim        NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9627218893Sdim      case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9628288943Sdim        NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9629218893Sdim      }
9630218893Sdim    } else {
9631218893Sdim      isLaneOp = true;
9632218893Sdim      switch (N->getOpcode()) {
9633234353Sdim      default: llvm_unreachable("unexpected opcode for Neon base update");
9634218893Sdim      case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9635218893Sdim      case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9636218893Sdim      case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9637288943Sdim      case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9638288943Sdim        NumVecs = 1; isLaneOp = false; break;
9639288943Sdim      case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9640288943Sdim        NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9641218893Sdim      }
9642218893Sdim    }
9643218893Sdim
9644218893Sdim    // Find the size of memory referenced by the load/store.
9645218893Sdim    EVT VecTy;
9646288943Sdim    if (isLoadOp) {
9647218893Sdim      VecTy = N->getValueType(0);
9648288943Sdim    } else if (isIntrinsic) {
9649218893Sdim      VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9650288943Sdim    } else {
9651288943Sdim      assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9652288943Sdim      VecTy = N->getOperand(1).getValueType();
9653288943Sdim    }
9654288943Sdim
9655218893Sdim    unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9656218893Sdim    if (isLaneOp)
9657218893Sdim      NumBytes /= VecTy.getVectorNumElements();
9658218893Sdim
9659218893Sdim    // If the increment is a constant, it must match the memory ref size.
9660218893Sdim    SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9661218893Sdim    if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9662218893Sdim      uint64_t IncVal = CInc->getZExtValue();
9663218893Sdim      if (IncVal != NumBytes)
9664218893Sdim        continue;
9665218893Sdim    } else if (NumBytes >= 3 * 16) {
9666218893Sdim      // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9667218893Sdim      // separate instructions that make it harder to use a non-constant update.
9668218893Sdim      continue;
9669218893Sdim    }
9670218893Sdim
9671288943Sdim    // OK, we found an ADD we can fold into the base update.
9672288943Sdim    // Now, create a _UPD node, taking care of not breaking alignment.
9673288943Sdim
9674288943Sdim    EVT AlignedVecTy = VecTy;
9675288943Sdim    unsigned Alignment = MemN->getAlignment();
9676288943Sdim
9677288943Sdim    // If this is a less-than-standard-aligned load/store, change the type to
9678288943Sdim    // match the standard alignment.
9679288943Sdim    // The alignment is overlooked when selecting _UPD variants; and it's
9680288943Sdim    // easier to introduce bitcasts here than fix that.
9681288943Sdim    // There are 3 ways to get to this base-update combine:
9682288943Sdim    // - intrinsics: they are assumed to be properly aligned (to the standard
9683288943Sdim    //   alignment of the memory type), so we don't need to do anything.
9684288943Sdim    // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9685288943Sdim    //   intrinsics, so, likewise, there's nothing to do.
9686288943Sdim    // - generic load/store instructions: the alignment is specified as an
9687288943Sdim    //   explicit operand, rather than implicitly as the standard alignment
9688288943Sdim    //   of the memory type (like the intrisics).  We need to change the
9689288943Sdim    //   memory type to match the explicit alignment.  That way, we don't
9690288943Sdim    //   generate non-standard-aligned ARMISD::VLDx nodes.
9691288943Sdim    if (isa<LSBaseSDNode>(N)) {
9692288943Sdim      if (Alignment == 0)
9693288943Sdim        Alignment = 1;
9694288943Sdim      if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9695288943Sdim        MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9696288943Sdim        assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9697288943Sdim        assert(!isLaneOp && "Unexpected generic load/store lane.");
9698288943Sdim        unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9699288943Sdim        AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9700288943Sdim      }
9701288943Sdim      // Don't set an explicit alignment on regular load/stores that we want
9702288943Sdim      // to transform to VLD/VST 1_UPD nodes.
9703288943Sdim      // This matches the behavior of regular load/stores, which only get an
9704288943Sdim      // explicit alignment if the MMO alignment is larger than the standard
9705288943Sdim      // alignment of the memory type.
9706288943Sdim      // Intrinsics, however, always get an explicit alignment, set to the
9707288943Sdim      // alignment of the MMO.
9708288943Sdim      Alignment = 1;
9709288943Sdim    }
9710288943Sdim
9711218893Sdim    // Create the new updating load/store node.
9712288943Sdim    // First, create an SDVTList for the new updating node's results.
9713218893Sdim    EVT Tys[6];
9714288943Sdim    unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9715218893Sdim    unsigned n;
9716218893Sdim    for (n = 0; n < NumResultVecs; ++n)
9717288943Sdim      Tys[n] = AlignedVecTy;
9718218893Sdim    Tys[n++] = MVT::i32;
9719218893Sdim    Tys[n] = MVT::Other;
9720280031Sdim    SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9721288943Sdim
9722288943Sdim    // Then, gather the new node's operands.
9723218893Sdim    SmallVector<SDValue, 8> Ops;
9724218893Sdim    Ops.push_back(N->getOperand(0)); // incoming chain
9725218893Sdim    Ops.push_back(N->getOperand(AddrOpIdx));
9726218893Sdim    Ops.push_back(Inc);
9727288943Sdim
9728288943Sdim    if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9729288943Sdim      // Try to match the intrinsic's signature
9730288943Sdim      Ops.push_back(StN->getValue());
9731288943Sdim    } else {
9732288943Sdim      // Loads (and of course intrinsics) match the intrinsics' signature,
9733288943Sdim      // so just add all but the alignment operand.
9734288943Sdim      for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9735288943Sdim        Ops.push_back(N->getOperand(i));
9736218893Sdim    }
9737218893Sdim
9738288943Sdim    // For all node types, the alignment operand is always the last one.
9739288943Sdim    Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9740288943Sdim
9741288943Sdim    // If this is a non-standard-aligned STORE, the penultimate operand is the
9742288943Sdim    // stored value.  Bitcast it to the aligned type.
9743288943Sdim    if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9744288943Sdim      SDValue &StVal = Ops[Ops.size()-2];
9745288943Sdim      StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9746288943Sdim    }
9747288943Sdim
9748288943Sdim    SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9749288943Sdim                                           Ops, AlignedVecTy,
9750288943Sdim                                           MemN->getMemOperand());
9751288943Sdim
9752218893Sdim    // Update the uses.
9753288943Sdim    SmallVector<SDValue, 5> NewResults;
9754288943Sdim    for (unsigned i = 0; i < NumResultVecs; ++i)
9755218893Sdim      NewResults.push_back(SDValue(UpdN.getNode(), i));
9756288943Sdim
9757288943Sdim    // If this is an non-standard-aligned LOAD, the first result is the loaded
9758288943Sdim    // value.  Bitcast it to the expected result type.
9759288943Sdim    if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9760288943Sdim      SDValue &LdVal = NewResults[0];
9761288943Sdim      LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9762218893Sdim    }
9763288943Sdim
9764218893Sdim    NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9765218893Sdim    DCI.CombineTo(N, NewResults);
9766218893Sdim    DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9767218893Sdim
9768218893Sdim    break;
9769221345Sdim  }
9770218893Sdim  return SDValue();
9771218893Sdim}
9772218893Sdim
9773288943Sdimstatic SDValue PerformVLDCombine(SDNode *N,
9774288943Sdim                                 TargetLowering::DAGCombinerInfo &DCI) {
9775288943Sdim  if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9776288943Sdim    return SDValue();
9777288943Sdim
9778288943Sdim  return CombineBaseUpdate(N, DCI);
9779288943Sdim}
9780288943Sdim
9781218893Sdim/// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9782218893Sdim/// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9783218893Sdim/// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9784218893Sdim/// return true.
9785218893Sdimstatic bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9786218893Sdim  SelectionDAG &DAG = DCI.DAG;
9787218893Sdim  EVT VT = N->getValueType(0);
9788218893Sdim  // vldN-dup instructions only support 64-bit vectors for N > 1.
9789218893Sdim  if (!VT.is64BitVector())
9790218893Sdim    return false;
9791218893Sdim
9792218893Sdim  // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9793218893Sdim  SDNode *VLD = N->getOperand(0).getNode();
9794218893Sdim  if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9795218893Sdim    return false;
9796218893Sdim  unsigned NumVecs = 0;
9797218893Sdim  unsigned NewOpc = 0;
9798218893Sdim  unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9799218893Sdim  if (IntNo == Intrinsic::arm_neon_vld2lane) {
9800218893Sdim    NumVecs = 2;
9801218893Sdim    NewOpc = ARMISD::VLD2DUP;
9802218893Sdim  } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9803218893Sdim    NumVecs = 3;
9804218893Sdim    NewOpc = ARMISD::VLD3DUP;
9805218893Sdim  } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9806218893Sdim    NumVecs = 4;
9807218893Sdim    NewOpc = ARMISD::VLD4DUP;
9808218893Sdim  } else {
9809218893Sdim    return false;
9810218893Sdim  }
9811218893Sdim
9812218893Sdim  // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9813218893Sdim  // numbers match the load.
9814218893Sdim  unsigned VLDLaneNo =
9815218893Sdim    cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9816218893Sdim  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9817218893Sdim       UI != UE; ++UI) {
9818218893Sdim    // Ignore uses of the chain result.
9819218893Sdim    if (UI.getUse().getResNo() == NumVecs)
9820218893Sdim      continue;
9821218893Sdim    SDNode *User = *UI;
9822218893Sdim    if (User->getOpcode() != ARMISD::VDUPLANE ||
9823218893Sdim        VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9824218893Sdim      return false;
9825218893Sdim  }
9826218893Sdim
9827218893Sdim  // Create the vldN-dup node.
9828218893Sdim  EVT Tys[5];
9829218893Sdim  unsigned n;
9830218893Sdim  for (n = 0; n < NumVecs; ++n)
9831218893Sdim    Tys[n] = VT;
9832218893Sdim  Tys[n] = MVT::Other;
9833280031Sdim  SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9834218893Sdim  SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9835218893Sdim  MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9836261991Sdim  SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9837276479Sdim                                           Ops, VLDMemInt->getMemoryVT(),
9838218893Sdim                                           VLDMemInt->getMemOperand());
9839218893Sdim
9840218893Sdim  // Update the uses.
9841218893Sdim  for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9842218893Sdim       UI != UE; ++UI) {
9843218893Sdim    unsigned ResNo = UI.getUse().getResNo();
9844218893Sdim    // Ignore uses of the chain result.
9845218893Sdim    if (ResNo == NumVecs)
9846218893Sdim      continue;
9847218893Sdim    SDNode *User = *UI;
9848218893Sdim    DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9849218893Sdim  }
9850218893Sdim
9851218893Sdim  // Now the vldN-lane intrinsic is dead except for its chain result.
9852218893Sdim  // Update uses of the chain.
9853218893Sdim  std::vector<SDValue> VLDDupResults;
9854218893Sdim  for (unsigned n = 0; n < NumVecs; ++n)
9855218893Sdim    VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9856218893Sdim  VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9857218893Sdim  DCI.CombineTo(VLD, VLDDupResults);
9858218893Sdim
9859218893Sdim  return true;
9860218893Sdim}
9861218893Sdim
9862210299Sed/// PerformVDUPLANECombine - Target-specific dag combine xforms for
9863210299Sed/// ARMISD::VDUPLANE.
9864210299Sedstatic SDValue PerformVDUPLANECombine(SDNode *N,
9865210299Sed                                      TargetLowering::DAGCombinerInfo &DCI) {
9866210299Sed  SDValue Op = N->getOperand(0);
9867210299Sed
9868218893Sdim  // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9869218893Sdim  // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9870218893Sdim  if (CombineVLDDUP(N, DCI))
9871218893Sdim    return SDValue(N, 0);
9872218893Sdim
9873218893Sdim  // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9874218893Sdim  // redundant.  Ignore bit_converts for now; element sizes are checked below.
9875218893Sdim  while (Op.getOpcode() == ISD::BITCAST)
9876210299Sed    Op = Op.getOperand(0);
9877210299Sed  if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9878210299Sed    return SDValue();
9879210299Sed
9880210299Sed  // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9881210299Sed  unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9882210299Sed  // The canonical VMOV for a zero vector uses a 32-bit element size.
9883210299Sed  unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9884210299Sed  unsigned EltBits;
9885210299Sed  if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9886210299Sed    EltSize = 8;
9887218893Sdim  EVT VT = N->getValueType(0);
9888210299Sed  if (EltSize > VT.getVectorElementType().getSizeInBits())
9889210299Sed    return SDValue();
9890210299Sed
9891261991Sdim  return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9892210299Sed}
9893210299Sed
9894288943Sdimstatic SDValue PerformLOADCombine(SDNode *N,
9895288943Sdim                                  TargetLowering::DAGCombinerInfo &DCI) {
9896288943Sdim  EVT VT = N->getValueType(0);
9897288943Sdim
9898288943Sdim  // If this is a legal vector load, try to combine it into a VLD1_UPD.
9899288943Sdim  if (ISD::isNormalLoad(N) && VT.isVector() &&
9900288943Sdim      DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9901288943Sdim    return CombineBaseUpdate(N, DCI);
9902288943Sdim
9903288943Sdim  return SDValue();
9904288943Sdim}
9905288943Sdim
9906280031Sdim/// PerformSTORECombine - Target-specific dag combine xforms for
9907280031Sdim/// ISD::STORE.
9908280031Sdimstatic SDValue PerformSTORECombine(SDNode *N,
9909280031Sdim                                   TargetLowering::DAGCombinerInfo &DCI) {
9910280031Sdim  StoreSDNode *St = cast<StoreSDNode>(N);
9911280031Sdim  if (St->isVolatile())
9912280031Sdim    return SDValue();
9913280031Sdim
9914280031Sdim  // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9915280031Sdim  // pack all of the elements in one place.  Next, store to memory in fewer
9916280031Sdim  // chunks.
9917280031Sdim  SDValue StVal = St->getValue();
9918280031Sdim  EVT VT = StVal.getValueType();
9919280031Sdim  if (St->isTruncatingStore() && VT.isVector()) {
9920280031Sdim    SelectionDAG &DAG = DCI.DAG;
9921280031Sdim    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9922280031Sdim    EVT StVT = St->getMemoryVT();
9923280031Sdim    unsigned NumElems = VT.getVectorNumElements();
9924280031Sdim    assert(StVT != VT && "Cannot truncate to the same type");
9925280031Sdim    unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9926280031Sdim    unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9927280031Sdim
9928280031Sdim    // From, To sizes and ElemCount must be pow of two
9929280031Sdim    if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9930280031Sdim
9931280031Sdim    // We are going to use the original vector elt for storing.
9932280031Sdim    // Accumulated smaller vector elements must be a multiple of the store size.
9933280031Sdim    if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9934280031Sdim
9935280031Sdim    unsigned SizeRatio  = FromEltSz / ToEltSz;
9936280031Sdim    assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9937280031Sdim
9938280031Sdim    // Create a type on which we perform the shuffle.
9939280031Sdim    EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9940280031Sdim                                     NumElems*SizeRatio);
9941280031Sdim    assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9942280031Sdim
9943280031Sdim    SDLoc DL(St);
9944280031Sdim    SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9945280031Sdim    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9946280031Sdim    for (unsigned i = 0; i < NumElems; ++i)
9947288943Sdim      ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9948288943Sdim                          ? (i + 1) * SizeRatio - 1
9949288943Sdim                          : i * SizeRatio;
9950280031Sdim
9951280031Sdim    // Can't shuffle using an illegal type.
9952280031Sdim    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9953280031Sdim
9954280031Sdim    SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9955280031Sdim                                DAG.getUNDEF(WideVec.getValueType()),
9956280031Sdim                                ShuffleVec.data());
9957280031Sdim    // At this point all of the data is stored at the bottom of the
9958280031Sdim    // register. We now need to save it to mem.
9959280031Sdim
9960280031Sdim    // Find the largest store unit
9961280031Sdim    MVT StoreType = MVT::i8;
9962280031Sdim    for (MVT Tp : MVT::integer_valuetypes()) {
9963280031Sdim      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9964280031Sdim        StoreType = Tp;
9965280031Sdim    }
9966280031Sdim    // Didn't find a legal store type.
9967280031Sdim    if (!TLI.isTypeLegal(StoreType))
9968280031Sdim      return SDValue();
9969280031Sdim
9970280031Sdim    // Bitcast the original vector into a vector of store-size units
9971280031Sdim    EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9972280031Sdim            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9973280031Sdim    assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9974280031Sdim    SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9975280031Sdim    SmallVector<SDValue, 8> Chains;
9976288943Sdim    SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9977288943Sdim                                        TLI.getPointerTy(DAG.getDataLayout()));
9978280031Sdim    SDValue BasePtr = St->getBasePtr();
9979280031Sdim
9980280031Sdim    // Perform one or more big stores into memory.
9981280031Sdim    unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9982280031Sdim    for (unsigned I = 0; I < E; I++) {
9983280031Sdim      SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9984280031Sdim                                   StoreType, ShuffWide,
9985288943Sdim                                   DAG.getIntPtrConstant(I, DL));
9986280031Sdim      SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9987280031Sdim                                St->getPointerInfo(), St->isVolatile(),
9988280031Sdim                                St->isNonTemporal(), St->getAlignment());
9989280031Sdim      BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9990280031Sdim                            Increment);
9991280031Sdim      Chains.push_back(Ch);
9992280031Sdim    }
9993280031Sdim    return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9994280031Sdim  }
9995280031Sdim
9996280031Sdim  if (!ISD::isNormalStore(St))
9997280031Sdim    return SDValue();
9998280031Sdim
9999280031Sdim  // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10000280031Sdim  // ARM stores of arguments in the same cache line.
10001280031Sdim  if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10002280031Sdim      StVal.getNode()->hasOneUse()) {
10003280031Sdim    SelectionDAG  &DAG = DCI.DAG;
10004288943Sdim    bool isBigEndian = DAG.getDataLayout().isBigEndian();
10005280031Sdim    SDLoc DL(St);
10006280031Sdim    SDValue BasePtr = St->getBasePtr();
10007280031Sdim    SDValue NewST1 = DAG.getStore(St->getChain(), DL,
10008280031Sdim                                  StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
10009280031Sdim                                  BasePtr, St->getPointerInfo(), St->isVolatile(),
10010280031Sdim                                  St->isNonTemporal(), St->getAlignment());
10011280031Sdim
10012280031Sdim    SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10013288943Sdim                                    DAG.getConstant(4, DL, MVT::i32));
10014280031Sdim    return DAG.getStore(NewST1.getValue(0), DL,
10015280031Sdim                        StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10016280031Sdim                        OffsetPtr, St->getPointerInfo(), St->isVolatile(),
10017280031Sdim                        St->isNonTemporal(),
10018280031Sdim                        std::min(4U, St->getAlignment() / 2));
10019280031Sdim  }
10020280031Sdim
10021280031Sdim  if (StVal.getValueType() == MVT::i64 &&
10022280031Sdim      StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10023280031Sdim
10024280031Sdim    // Bitcast an i64 store extracted from a vector to f64.
10025280031Sdim    // Otherwise, the i64 value will be legalized to a pair of i32 values.
10026280031Sdim    SelectionDAG &DAG = DCI.DAG;
10027280031Sdim    SDLoc dl(StVal);
10028280031Sdim    SDValue IntVec = StVal.getOperand(0);
10029280031Sdim    EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10030280031Sdim                                   IntVec.getValueType().getVectorNumElements());
10031280031Sdim    SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10032280031Sdim    SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10033280031Sdim                                 Vec, StVal.getOperand(1));
10034280031Sdim    dl = SDLoc(N);
10035280031Sdim    SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10036280031Sdim    // Make the DAGCombiner fold the bitcasts.
10037280031Sdim    DCI.AddToWorklist(Vec.getNode());
10038280031Sdim    DCI.AddToWorklist(ExtElt.getNode());
10039280031Sdim    DCI.AddToWorklist(V.getNode());
10040280031Sdim    return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10041280031Sdim                        St->getPointerInfo(), St->isVolatile(),
10042280031Sdim                        St->isNonTemporal(), St->getAlignment(),
10043280031Sdim                        St->getAAInfo());
10044280031Sdim  }
10045280031Sdim
10046288943Sdim  // If this is a legal vector store, try to combine it into a VST1_UPD.
10047288943Sdim  if (ISD::isNormalStore(N) && VT.isVector() &&
10048288943Sdim      DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10049288943Sdim    return CombineBaseUpdate(N, DCI);
10050288943Sdim
10051280031Sdim  return SDValue();
10052280031Sdim}
10053280031Sdim
10054224145Sdim/// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10055224145Sdim/// can replace combinations of VMUL and VCVT (floating-point to integer)
10056224145Sdim/// when the VMUL has a constant operand that is a power of 2.
10057224145Sdim///
10058224145Sdim/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10059224145Sdim///  vmul.f32        d16, d17, d16
10060224145Sdim///  vcvt.s32.f32    d16, d16
10061224145Sdim/// becomes:
10062224145Sdim///  vcvt.s32.f32    d16, d16, #3
10063296417Sdimstatic SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10064224145Sdim                                  const ARMSubtarget *Subtarget) {
10065296417Sdim  if (!Subtarget->hasNEON())
10066296417Sdim    return SDValue();
10067296417Sdim
10068224145Sdim  SDValue Op = N->getOperand(0);
10069296417Sdim  if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
10070224145Sdim    return SDValue();
10071224145Sdim
10072224145Sdim  SDValue ConstVec = Op->getOperand(1);
10073296417Sdim  if (!isa<BuildVectorSDNode>(ConstVec))
10074224145Sdim    return SDValue();
10075224145Sdim
10076261991Sdim  MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10077296417Sdim  uint32_t FloatBits = FloatTy.getSizeInBits();
10078261991Sdim  MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10079296417Sdim  uint32_t IntBits = IntTy.getSizeInBits();
10080280031Sdim  unsigned NumLanes = Op.getValueType().getVectorNumElements();
10081296417Sdim  if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10082261991Sdim    // These instructions only exist converting from f32 to i32. We can handle
10083261991Sdim    // smaller integers by generating an extra truncate, but larger ones would
10084280031Sdim    // be lossy. We also can't handle more then 4 lanes, since these intructions
10085280031Sdim    // only support v2i32/v4i32 types.
10086261991Sdim    return SDValue();
10087261991Sdim  }
10088261991Sdim
10089296417Sdim  BitVector UndefElements;
10090296417Sdim  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10091296417Sdim  int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10092296417Sdim  if (C == -1 || C == 0 || C > 32)
10093296417Sdim    return SDValue();
10094296417Sdim
10095288943Sdim  SDLoc dl(N);
10096296417Sdim  bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10097224145Sdim  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10098224145Sdim    Intrinsic::arm_neon_vcvtfp2fxu;
10099296417Sdim  SDValue FixConv = DAG.getNode(
10100296417Sdim      ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10101296417Sdim      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10102296417Sdim      DAG.getConstant(C, dl, MVT::i32));
10103261991Sdim
10104296417Sdim  if (IntBits < FloatBits)
10105288943Sdim    FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10106261991Sdim
10107261991Sdim  return FixConv;
10108224145Sdim}
10109224145Sdim
10110224145Sdim/// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10111224145Sdim/// can replace combinations of VCVT (integer to floating-point) and VDIV
10112224145Sdim/// when the VDIV has a constant operand that is a power of 2.
10113224145Sdim///
10114224145Sdim/// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10115224145Sdim///  vcvt.f32.s32    d16, d16
10116224145Sdim///  vdiv.f32        d16, d17, d16
10117224145Sdim/// becomes:
10118224145Sdim///  vcvt.f32.s32    d16, d16, #3
10119296417Sdimstatic SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10120224145Sdim                                  const ARMSubtarget *Subtarget) {
10121296417Sdim  if (!Subtarget->hasNEON())
10122296417Sdim    return SDValue();
10123296417Sdim
10124224145Sdim  SDValue Op = N->getOperand(0);
10125224145Sdim  unsigned OpOpcode = Op.getNode()->getOpcode();
10126296417Sdim  if (!N->getValueType(0).isVector() ||
10127224145Sdim      (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10128224145Sdim    return SDValue();
10129224145Sdim
10130224145Sdim  SDValue ConstVec = N->getOperand(1);
10131296417Sdim  if (!isa<BuildVectorSDNode>(ConstVec))
10132224145Sdim    return SDValue();
10133224145Sdim
10134261991Sdim  MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10135296417Sdim  uint32_t FloatBits = FloatTy.getSizeInBits();
10136261991Sdim  MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10137296417Sdim  uint32_t IntBits = IntTy.getSizeInBits();
10138296417Sdim  unsigned NumLanes = Op.getValueType().getVectorNumElements();
10139296417Sdim  if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10140261991Sdim    // These instructions only exist converting from i32 to f32. We can handle
10141261991Sdim    // smaller integers by generating an extra extend, but larger ones would
10142296417Sdim    // be lossy. We also can't handle more then 4 lanes, since these intructions
10143296417Sdim    // only support v2i32/v4i32 types.
10144261991Sdim    return SDValue();
10145261991Sdim  }
10146261991Sdim
10147296417Sdim  BitVector UndefElements;
10148296417Sdim  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10149296417Sdim  int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10150296417Sdim  if (C == -1 || C == 0 || C > 32)
10151296417Sdim    return SDValue();
10152296417Sdim
10153288943Sdim  SDLoc dl(N);
10154296417Sdim  bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10155261991Sdim  SDValue ConvInput = Op.getOperand(0);
10156296417Sdim  if (IntBits < FloatBits)
10157261991Sdim    ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10158288943Sdim                            dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10159261991Sdim                            ConvInput);
10160261991Sdim
10161224145Sdim  unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10162224145Sdim    Intrinsic::arm_neon_vcvtfxu2fp;
10163288943Sdim  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10164224145Sdim                     Op.getValueType(),
10165288943Sdim                     DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10166296417Sdim                     ConvInput, DAG.getConstant(C, dl, MVT::i32));
10167224145Sdim}
10168224145Sdim
10169224145Sdim/// Getvshiftimm - Check if this is a valid build_vector for the immediate
10170194710Sed/// operand of a vector shift operation, where all the elements of the
10171194710Sed/// build_vector must have the same constant integer value.
10172194710Sedstatic bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10173194710Sed  // Ignore bit_converts.
10174218893Sdim  while (Op.getOpcode() == ISD::BITCAST)
10175194710Sed    Op = Op.getOperand(0);
10176194710Sed  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10177194710Sed  APInt SplatBits, SplatUndef;
10178194710Sed  unsigned SplatBitSize;
10179194710Sed  bool HasAnyUndefs;
10180194710Sed  if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10181194710Sed                                      HasAnyUndefs, ElementBits) ||
10182194710Sed      SplatBitSize > ElementBits)
10183194710Sed    return false;
10184194710Sed  Cnt = SplatBits.getSExtValue();
10185194710Sed  return true;
10186194710Sed}
10187194710Sed
10188194710Sed/// isVShiftLImm - Check if this is a valid build_vector for the immediate
10189194710Sed/// operand of a vector shift left operation.  That value must be in the range:
10190194710Sed///   0 <= Value < ElementBits for a left shift; or
10191194710Sed///   0 <= Value <= ElementBits for a long left shift.
10192198090Srdivackystatic bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10193194710Sed  assert(VT.isVector() && "vector shift count is not a vector type");
10194296417Sdim  int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10195194710Sed  if (! getVShiftImm(Op, ElementBits, Cnt))
10196194710Sed    return false;
10197194710Sed  return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10198194710Sed}
10199194710Sed
10200194710Sed/// isVShiftRImm - Check if this is a valid build_vector for the immediate
10201194710Sed/// operand of a vector shift right operation.  For a shift opcode, the value
10202194710Sed/// is positive, but for an intrinsic the value count must be negative. The
10203194710Sed/// absolute value must be in the range:
10204194710Sed///   1 <= |Value| <= ElementBits for a right shift; or
10205194710Sed///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10206198090Srdivackystatic bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10207194710Sed                         int64_t &Cnt) {
10208194710Sed  assert(VT.isVector() && "vector shift count is not a vector type");
10209296417Sdim  int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10210194710Sed  if (! getVShiftImm(Op, ElementBits, Cnt))
10211194710Sed    return false;
10212296417Sdim  if (!isIntrinsic)
10213296417Sdim    return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10214296417Sdim  if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10215194710Sed    Cnt = -Cnt;
10216296417Sdim    return true;
10217296417Sdim  }
10218296417Sdim  return false;
10219194710Sed}
10220194710Sed
10221194710Sed/// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10222194710Sedstatic SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10223194710Sed  unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10224194710Sed  switch (IntNo) {
10225194710Sed  default:
10226194710Sed    // Don't do anything for most intrinsics.
10227194710Sed    break;
10228194710Sed
10229194710Sed  // Vector shifts: check for immediate versions and lower them.
10230194710Sed  // Note: This is done during DAG combining instead of DAG legalizing because
10231194710Sed  // the build_vectors for 64-bit vector element shift counts are generally
10232194710Sed  // not legal, and it is hard to see their values after they get legalized to
10233194710Sed  // loads from a constant pool.
10234194710Sed  case Intrinsic::arm_neon_vshifts:
10235194710Sed  case Intrinsic::arm_neon_vshiftu:
10236194710Sed  case Intrinsic::arm_neon_vrshifts:
10237194710Sed  case Intrinsic::arm_neon_vrshiftu:
10238194710Sed  case Intrinsic::arm_neon_vrshiftn:
10239194710Sed  case Intrinsic::arm_neon_vqshifts:
10240194710Sed  case Intrinsic::arm_neon_vqshiftu:
10241194710Sed  case Intrinsic::arm_neon_vqshiftsu:
10242194710Sed  case Intrinsic::arm_neon_vqshiftns:
10243194710Sed  case Intrinsic::arm_neon_vqshiftnu:
10244194710Sed  case Intrinsic::arm_neon_vqshiftnsu:
10245194710Sed  case Intrinsic::arm_neon_vqrshiftns:
10246194710Sed  case Intrinsic::arm_neon_vqrshiftnu:
10247194710Sed  case Intrinsic::arm_neon_vqrshiftnsu: {
10248198090Srdivacky    EVT VT = N->getOperand(1).getValueType();
10249194710Sed    int64_t Cnt;
10250194710Sed    unsigned VShiftOpc = 0;
10251194710Sed
10252194710Sed    switch (IntNo) {
10253194710Sed    case Intrinsic::arm_neon_vshifts:
10254194710Sed    case Intrinsic::arm_neon_vshiftu:
10255194710Sed      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10256194710Sed        VShiftOpc = ARMISD::VSHL;
10257194710Sed        break;
10258194710Sed      }
10259194710Sed      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10260194710Sed        VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10261194710Sed                     ARMISD::VSHRs : ARMISD::VSHRu);
10262194710Sed        break;
10263194710Sed      }
10264194710Sed      return SDValue();
10265194710Sed
10266194710Sed    case Intrinsic::arm_neon_vrshifts:
10267194710Sed    case Intrinsic::arm_neon_vrshiftu:
10268194710Sed      if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10269194710Sed        break;
10270194710Sed      return SDValue();
10271194710Sed
10272194710Sed    case Intrinsic::arm_neon_vqshifts:
10273194710Sed    case Intrinsic::arm_neon_vqshiftu:
10274194710Sed      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10275194710Sed        break;
10276194710Sed      return SDValue();
10277194710Sed
10278194710Sed    case Intrinsic::arm_neon_vqshiftsu:
10279194710Sed      if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10280194710Sed        break;
10281198090Srdivacky      llvm_unreachable("invalid shift count for vqshlu intrinsic");
10282194710Sed
10283194710Sed    case Intrinsic::arm_neon_vrshiftn:
10284194710Sed    case Intrinsic::arm_neon_vqshiftns:
10285194710Sed    case Intrinsic::arm_neon_vqshiftnu:
10286194710Sed    case Intrinsic::arm_neon_vqshiftnsu:
10287194710Sed    case Intrinsic::arm_neon_vqrshiftns:
10288194710Sed    case Intrinsic::arm_neon_vqrshiftnu:
10289194710Sed    case Intrinsic::arm_neon_vqrshiftnsu:
10290194710Sed      // Narrowing shifts require an immediate right shift.
10291194710Sed      if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10292194710Sed        break;
10293210299Sed      llvm_unreachable("invalid shift count for narrowing vector shift "
10294210299Sed                       "intrinsic");
10295194710Sed
10296194710Sed    default:
10297198090Srdivacky      llvm_unreachable("unhandled vector shift");
10298194710Sed    }
10299194710Sed
10300194710Sed    switch (IntNo) {
10301194710Sed    case Intrinsic::arm_neon_vshifts:
10302194710Sed    case Intrinsic::arm_neon_vshiftu:
10303194710Sed      // Opcode already set above.
10304194710Sed      break;
10305194710Sed    case Intrinsic::arm_neon_vrshifts:
10306194710Sed      VShiftOpc = ARMISD::VRSHRs; break;
10307194710Sed    case Intrinsic::arm_neon_vrshiftu:
10308194710Sed      VShiftOpc = ARMISD::VRSHRu; break;
10309194710Sed    case Intrinsic::arm_neon_vrshiftn:
10310194710Sed      VShiftOpc = ARMISD::VRSHRN; break;
10311194710Sed    case Intrinsic::arm_neon_vqshifts:
10312194710Sed      VShiftOpc = ARMISD::VQSHLs; break;
10313194710Sed    case Intrinsic::arm_neon_vqshiftu:
10314194710Sed      VShiftOpc = ARMISD::VQSHLu; break;
10315194710Sed    case Intrinsic::arm_neon_vqshiftsu:
10316194710Sed      VShiftOpc = ARMISD::VQSHLsu; break;
10317194710Sed    case Intrinsic::arm_neon_vqshiftns:
10318194710Sed      VShiftOpc = ARMISD::VQSHRNs; break;
10319194710Sed    case Intrinsic::arm_neon_vqshiftnu:
10320194710Sed      VShiftOpc = ARMISD::VQSHRNu; break;
10321194710Sed    case Intrinsic::arm_neon_vqshiftnsu:
10322194710Sed      VShiftOpc = ARMISD::VQSHRNsu; break;
10323194710Sed    case Intrinsic::arm_neon_vqrshiftns:
10324194710Sed      VShiftOpc = ARMISD::VQRSHRNs; break;
10325194710Sed    case Intrinsic::arm_neon_vqrshiftnu:
10326194710Sed      VShiftOpc = ARMISD::VQRSHRNu; break;
10327194710Sed    case Intrinsic::arm_neon_vqrshiftnsu:
10328194710Sed      VShiftOpc = ARMISD::VQRSHRNsu; break;
10329194710Sed    }
10330194710Sed
10331288943Sdim    SDLoc dl(N);
10332288943Sdim    return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10333288943Sdim                       N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10334194710Sed  }
10335194710Sed
10336194710Sed  case Intrinsic::arm_neon_vshiftins: {
10337198090Srdivacky    EVT VT = N->getOperand(1).getValueType();
10338194710Sed    int64_t Cnt;
10339194710Sed    unsigned VShiftOpc = 0;
10340194710Sed
10341194710Sed    if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10342194710Sed      VShiftOpc = ARMISD::VSLI;
10343194710Sed    else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10344194710Sed      VShiftOpc = ARMISD::VSRI;
10345194710Sed    else {
10346198090Srdivacky      llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10347194710Sed    }
10348194710Sed
10349288943Sdim    SDLoc dl(N);
10350288943Sdim    return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10351194710Sed                       N->getOperand(1), N->getOperand(2),
10352288943Sdim                       DAG.getConstant(Cnt, dl, MVT::i32));
10353194710Sed  }
10354194710Sed
10355194710Sed  case Intrinsic::arm_neon_vqrshifts:
10356194710Sed  case Intrinsic::arm_neon_vqrshiftu:
10357194710Sed    // No immediate versions of these to check for.
10358194710Sed    break;
10359194710Sed  }
10360194710Sed
10361194710Sed  return SDValue();
10362194710Sed}
10363194710Sed
10364194710Sed/// PerformShiftCombine - Checks for immediate versions of vector shifts and
10365194710Sed/// lowers them.  As with the vector shift intrinsics, this is done during DAG
10366194710Sed/// combining instead of DAG legalizing because the build_vectors for 64-bit
10367194710Sed/// vector element shift counts are generally not legal, and it is hard to see
10368194710Sed/// their values after they get legalized to loads from a constant pool.
10369194710Sedstatic SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10370194710Sed                                   const ARMSubtarget *ST) {
10371198090Srdivacky  EVT VT = N->getValueType(0);
10372234353Sdim  if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10373234353Sdim    // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10374234353Sdim    // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10375234353Sdim    SDValue N1 = N->getOperand(1);
10376234353Sdim    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10377234353Sdim      SDValue N0 = N->getOperand(0);
10378234353Sdim      if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10379234353Sdim          DAG.MaskedValueIsZero(N0.getOperand(0),
10380234353Sdim                                APInt::getHighBitsSet(32, 16)))
10381261991Sdim        return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10382234353Sdim    }
10383234353Sdim  }
10384194710Sed
10385194710Sed  // Nothing to be done for scalar shifts.
10386218893Sdim  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10387218893Sdim  if (!VT.isVector() || !TLI.isTypeLegal(VT))
10388194710Sed    return SDValue();
10389194710Sed
10390194710Sed  assert(ST->hasNEON() && "unexpected vector shift");
10391194710Sed  int64_t Cnt;
10392194710Sed
10393194710Sed  switch (N->getOpcode()) {
10394198090Srdivacky  default: llvm_unreachable("unexpected shift opcode");
10395194710Sed
10396194710Sed  case ISD::SHL:
10397288943Sdim    if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10398288943Sdim      SDLoc dl(N);
10399288943Sdim      return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10400288943Sdim                         DAG.getConstant(Cnt, dl, MVT::i32));
10401288943Sdim    }
10402194710Sed    break;
10403194710Sed
10404194710Sed  case ISD::SRA:
10405194710Sed  case ISD::SRL:
10406194710Sed    if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10407194710Sed      unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10408194710Sed                            ARMISD::VSHRs : ARMISD::VSHRu);
10409288943Sdim      SDLoc dl(N);
10410288943Sdim      return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10411288943Sdim                         DAG.getConstant(Cnt, dl, MVT::i32));
10412194710Sed    }
10413194710Sed  }
10414194710Sed  return SDValue();
10415194710Sed}
10416194710Sed
10417194710Sed/// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10418194710Sed/// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10419194710Sedstatic SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10420194710Sed                                    const ARMSubtarget *ST) {
10421194710Sed  SDValue N0 = N->getOperand(0);
10422194710Sed
10423194710Sed  // Check for sign- and zero-extensions of vector extract operations of 8-
10424194710Sed  // and 16-bit vector elements.  NEON supports these directly.  They are
10425194710Sed  // handled during DAG combining because type legalization will promote them
10426194710Sed  // to 32-bit types and it is messy to recognize the operations after that.
10427194710Sed  if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10428194710Sed    SDValue Vec = N0.getOperand(0);
10429194710Sed    SDValue Lane = N0.getOperand(1);
10430198090Srdivacky    EVT VT = N->getValueType(0);
10431198090Srdivacky    EVT EltVT = N0.getValueType();
10432194710Sed    const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10433194710Sed
10434194710Sed    if (VT == MVT::i32 &&
10435194710Sed        (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10436218893Sdim        TLI.isTypeLegal(Vec.getValueType()) &&
10437218893Sdim        isa<ConstantSDNode>(Lane)) {
10438194710Sed
10439194710Sed      unsigned Opc = 0;
10440194710Sed      switch (N->getOpcode()) {
10441198090Srdivacky      default: llvm_unreachable("unexpected opcode");
10442194710Sed      case ISD::SIGN_EXTEND:
10443194710Sed        Opc = ARMISD::VGETLANEs;
10444194710Sed        break;
10445194710Sed      case ISD::ZERO_EXTEND:
10446194710Sed      case ISD::ANY_EXTEND:
10447194710Sed        Opc = ARMISD::VGETLANEu;
10448194710Sed        break;
10449194710Sed      }
10450261991Sdim      return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10451194710Sed    }
10452194710Sed  }
10453194710Sed
10454194710Sed  return SDValue();
10455194710Sed}
10456194710Sed
10457296417Sdimstatic void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10458296417Sdim                             APInt &KnownOne) {
10459296417Sdim  if (Op.getOpcode() == ARMISD::BFI) {
10460296417Sdim    // Conservatively, we can recurse down the first operand
10461296417Sdim    // and just mask out all affected bits.
10462296417Sdim    computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10463204642Srdivacky
10464296417Sdim    // The operand to BFI is already a mask suitable for removing the bits it
10465296417Sdim    // sets.
10466296417Sdim    ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10467296417Sdim    APInt Mask = CI->getAPIntValue();
10468296417Sdim    KnownZero &= Mask;
10469296417Sdim    KnownOne &= Mask;
10470296417Sdim    return;
10471296417Sdim  }
10472296417Sdim  if (Op.getOpcode() == ARMISD::CMOV) {
10473296417Sdim    APInt KZ2(KnownZero.getBitWidth(), 0);
10474296417Sdim    APInt KO2(KnownOne.getBitWidth(), 0);
10475296417Sdim    computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10476296417Sdim    computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10477296417Sdim
10478296417Sdim    KnownZero &= KZ2;
10479296417Sdim    KnownOne &= KO2;
10480296417Sdim    return;
10481296417Sdim  }
10482296417Sdim  return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10483296417Sdim}
10484296417Sdim
10485296417SdimSDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10486296417Sdim  // If we have a CMOV, OR and AND combination such as:
10487296417Sdim  //   if (x & CN)
10488296417Sdim  //     y |= CM;
10489296417Sdim  //
10490296417Sdim  // And:
10491296417Sdim  //   * CN is a single bit;
10492296417Sdim  //   * All bits covered by CM are known zero in y
10493296417Sdim  //
10494296417Sdim  // Then we can convert this into a sequence of BFI instructions. This will
10495296417Sdim  // always be a win if CM is a single bit, will always be no worse than the
10496296417Sdim  // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10497296417Sdim  // three bits (due to the extra IT instruction).
10498296417Sdim
10499296417Sdim  SDValue Op0 = CMOV->getOperand(0);
10500296417Sdim  SDValue Op1 = CMOV->getOperand(1);
10501296417Sdim  auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10502296417Sdim  auto CC = CCNode->getAPIntValue().getLimitedValue();
10503296417Sdim  SDValue CmpZ = CMOV->getOperand(4);
10504296417Sdim
10505296417Sdim  // The compare must be against zero.
10506296417Sdim  if (!isNullConstant(CmpZ->getOperand(1)))
10507204642Srdivacky    return SDValue();
10508204642Srdivacky
10509296417Sdim  assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10510296417Sdim  SDValue And = CmpZ->getOperand(0);
10511296417Sdim  if (And->getOpcode() != ISD::AND)
10512296417Sdim    return SDValue();
10513296417Sdim  ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10514296417Sdim  if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10515296417Sdim    return SDValue();
10516296417Sdim  SDValue X = And->getOperand(0);
10517204642Srdivacky
10518296417Sdim  if (CC == ARMCC::EQ) {
10519296417Sdim    // We're performing an "equal to zero" compare. Swap the operands so we
10520296417Sdim    // canonicalize on a "not equal to zero" compare.
10521296417Sdim    std::swap(Op0, Op1);
10522204642Srdivacky  } else {
10523296417Sdim    assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10524296417Sdim  }
10525296417Sdim
10526296417Sdim  if (Op1->getOpcode() != ISD::OR)
10527204642Srdivacky    return SDValue();
10528204642Srdivacky
10529296417Sdim  ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10530296417Sdim  if (!OrC)
10531296417Sdim    return SDValue();
10532296417Sdim  SDValue Y = Op1->getOperand(0);
10533204642Srdivacky
10534296417Sdim  if (Op0 != Y)
10535296417Sdim    return SDValue();
10536296417Sdim
10537296417Sdim  // Now, is it profitable to continue?
10538296417Sdim  APInt OrCI = OrC->getAPIntValue();
10539296417Sdim  unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10540296417Sdim  if (OrCI.countPopulation() > Heuristic)
10541296417Sdim    return SDValue();
10542296417Sdim
10543296417Sdim  // Lastly, can we determine that the bits defined by OrCI
10544296417Sdim  // are zero in Y?
10545296417Sdim  APInt KnownZero, KnownOne;
10546296417Sdim  computeKnownBits(DAG, Y, KnownZero, KnownOne);
10547296417Sdim  if ((OrCI & KnownZero) != OrCI)
10548296417Sdim    return SDValue();
10549296417Sdim
10550296417Sdim  // OK, we can do the combine.
10551296417Sdim  SDValue V = Y;
10552296417Sdim  SDLoc dl(X);
10553296417Sdim  EVT VT = X.getValueType();
10554296417Sdim  unsigned BitInX = AndC->getAPIntValue().logBase2();
10555296417Sdim
10556296417Sdim  if (BitInX != 0) {
10557296417Sdim    // We must shift X first.
10558296417Sdim    X = DAG.getNode(ISD::SRL, dl, VT, X,
10559296417Sdim                    DAG.getConstant(BitInX, dl, VT));
10560204642Srdivacky  }
10561204642Srdivacky
10562296417Sdim  for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10563296417Sdim       BitInY < NumActiveBits; ++BitInY) {
10564296417Sdim    if (OrCI[BitInY] == 0)
10565296417Sdim      continue;
10566296417Sdim    APInt Mask(VT.getSizeInBits(), 0);
10567296417Sdim    Mask.setBit(BitInY);
10568296417Sdim    V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10569296417Sdim                    // Confusingly, the operand is an *inverted* mask.
10570296417Sdim                    DAG.getConstant(~Mask, dl, VT));
10571296417Sdim  }
10572296417Sdim
10573296417Sdim  return V;
10574204642Srdivacky}
10575204642Srdivacky
10576224145Sdim/// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10577224145SdimSDValue
10578224145SdimARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10579224145Sdim  SDValue Cmp = N->getOperand(4);
10580224145Sdim  if (Cmp.getOpcode() != ARMISD::CMPZ)
10581224145Sdim    // Only looking at EQ and NE cases.
10582224145Sdim    return SDValue();
10583224145Sdim
10584224145Sdim  EVT VT = N->getValueType(0);
10585261991Sdim  SDLoc dl(N);
10586224145Sdim  SDValue LHS = Cmp.getOperand(0);
10587224145Sdim  SDValue RHS = Cmp.getOperand(1);
10588224145Sdim  SDValue FalseVal = N->getOperand(0);
10589224145Sdim  SDValue TrueVal = N->getOperand(1);
10590224145Sdim  SDValue ARMcc = N->getOperand(2);
10591226633Sdim  ARMCC::CondCodes CC =
10592226633Sdim    (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10593224145Sdim
10594296417Sdim  // BFI is only available on V6T2+.
10595296417Sdim  if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10596296417Sdim    SDValue R = PerformCMOVToBFICombine(N, DAG);
10597296417Sdim    if (R)
10598296417Sdim      return R;
10599296417Sdim  }
10600296417Sdim
10601224145Sdim  // Simplify
10602224145Sdim  //   mov     r1, r0
10603224145Sdim  //   cmp     r1, x
10604224145Sdim  //   mov     r0, y
10605224145Sdim  //   moveq   r0, x
10606224145Sdim  // to
10607224145Sdim  //   cmp     r0, x
10608224145Sdim  //   movne   r0, y
10609224145Sdim  //
10610224145Sdim  //   mov     r1, r0
10611224145Sdim  //   cmp     r1, x
10612224145Sdim  //   mov     r0, x
10613224145Sdim  //   movne   r0, y
10614224145Sdim  // to
10615224145Sdim  //   cmp     r0, x
10616224145Sdim  //   movne   r0, y
10617224145Sdim  /// FIXME: Turn this into a target neutral optimization?
10618224145Sdim  SDValue Res;
10619226633Sdim  if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10620224145Sdim    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10621224145Sdim                      N->getOperand(3), Cmp);
10622224145Sdim  } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10623224145Sdim    SDValue ARMcc;
10624224145Sdim    SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10625224145Sdim    Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10626224145Sdim                      N->getOperand(3), NewCmp);
10627224145Sdim  }
10628224145Sdim
10629224145Sdim  if (Res.getNode()) {
10630224145Sdim    APInt KnownZero, KnownOne;
10631276479Sdim    DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10632224145Sdim    // Capture demanded bits information that would be otherwise lost.
10633224145Sdim    if (KnownZero == 0xfffffffe)
10634224145Sdim      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10635224145Sdim                        DAG.getValueType(MVT::i1));
10636224145Sdim    else if (KnownZero == 0xffffff00)
10637224145Sdim      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10638224145Sdim                        DAG.getValueType(MVT::i8));
10639224145Sdim    else if (KnownZero == 0xffff0000)
10640224145Sdim      Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10641224145Sdim                        DAG.getValueType(MVT::i16));
10642224145Sdim  }
10643224145Sdim
10644224145Sdim  return Res;
10645224145Sdim}
10646224145Sdim
10647193323SedSDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10648193323Sed                                             DAGCombinerInfo &DCI) const {
10649193323Sed  switch (N->getOpcode()) {
10650193323Sed  default: break;
10651243830Sdim  case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10652224145Sdim  case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10653204642Srdivacky  case ISD::SUB:        return PerformSUBCombine(N, DCI);
10654208599Srdivacky  case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10655212904Sdim  case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10656234353Sdim  case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10657234353Sdim  case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10658218893Sdim  case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10659280031Sdim  case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10660218893Sdim  case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10661218893Sdim  case ISD::STORE:      return PerformSTORECombine(N, DCI);
10662280031Sdim  case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10663218893Sdim  case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10664218893Sdim  case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10665210299Sed  case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10666224145Sdim  case ISD::FP_TO_SINT:
10667296417Sdim  case ISD::FP_TO_UINT:
10668296417Sdim    return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10669296417Sdim  case ISD::FDIV:
10670296417Sdim    return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10671204642Srdivacky  case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10672194710Sed  case ISD::SHL:
10673194710Sed  case ISD::SRA:
10674204642Srdivacky  case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10675194710Sed  case ISD::SIGN_EXTEND:
10676194710Sed  case ISD::ZERO_EXTEND:
10677204642Srdivacky  case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10678224145Sdim  case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10679288943Sdim  case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10680218893Sdim  case ARMISD::VLD2DUP:
10681218893Sdim  case ARMISD::VLD3DUP:
10682218893Sdim  case ARMISD::VLD4DUP:
10683288943Sdim    return PerformVLDCombine(N, DCI);
10684261991Sdim  case ARMISD::BUILD_VECTOR:
10685261991Sdim    return PerformARMBUILD_VECTORCombine(N, DCI);
10686218893Sdim  case ISD::INTRINSIC_VOID:
10687218893Sdim  case ISD::INTRINSIC_W_CHAIN:
10688218893Sdim    switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10689218893Sdim    case Intrinsic::arm_neon_vld1:
10690218893Sdim    case Intrinsic::arm_neon_vld2:
10691218893Sdim    case Intrinsic::arm_neon_vld3:
10692218893Sdim    case Intrinsic::arm_neon_vld4:
10693218893Sdim    case Intrinsic::arm_neon_vld2lane:
10694218893Sdim    case Intrinsic::arm_neon_vld3lane:
10695218893Sdim    case Intrinsic::arm_neon_vld4lane:
10696218893Sdim    case Intrinsic::arm_neon_vst1:
10697218893Sdim    case Intrinsic::arm_neon_vst2:
10698218893Sdim    case Intrinsic::arm_neon_vst3:
10699218893Sdim    case Intrinsic::arm_neon_vst4:
10700218893Sdim    case Intrinsic::arm_neon_vst2lane:
10701218893Sdim    case Intrinsic::arm_neon_vst3lane:
10702218893Sdim    case Intrinsic::arm_neon_vst4lane:
10703288943Sdim      return PerformVLDCombine(N, DCI);
10704218893Sdim    default: break;
10705218893Sdim    }
10706218893Sdim    break;
10707193323Sed  }
10708193323Sed  return SDValue();
10709193323Sed}
10710193323Sed
10711218893Sdimbool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10712218893Sdim                                                          EVT VT) const {
10713218893Sdim  return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10714218893Sdim}
10715218893Sdim
10716280031Sdimbool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10717280031Sdim                                                       unsigned,
10718280031Sdim                                                       unsigned,
10719280031Sdim                                                       bool *Fast) const {
10720243830Sdim  // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10721243830Sdim  bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10722198090Srdivacky
10723198090Srdivacky  switch (VT.getSimpleVT().SimpleTy) {
10724198090Srdivacky  default:
10725198090Srdivacky    return false;
10726198090Srdivacky  case MVT::i8:
10727198090Srdivacky  case MVT::i16:
10728249423Sdim  case MVT::i32: {
10729243830Sdim    // Unaligned access can use (for example) LRDB, LRDH, LDR
10730249423Sdim    if (AllowsUnaligned) {
10731249423Sdim      if (Fast)
10732249423Sdim        *Fast = Subtarget->hasV7Ops();
10733249423Sdim      return true;
10734249423Sdim    }
10735249423Sdim    return false;
10736249423Sdim  }
10737239462Sdim  case MVT::f64:
10738249423Sdim  case MVT::v2f64: {
10739243830Sdim    // For any little-endian targets with neon, we can support unaligned ld/st
10740243830Sdim    // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10741276479Sdim    // A big-endian target may also explicitly support unaligned accesses
10742288943Sdim    if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10743249423Sdim      if (Fast)
10744249423Sdim        *Fast = true;
10745249423Sdim      return true;
10746249423Sdim    }
10747249423Sdim    return false;
10748198090Srdivacky  }
10749249423Sdim  }
10750198090Srdivacky}
10751198090Srdivacky
10752234353Sdimstatic bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10753234353Sdim                       unsigned AlignCheck) {
10754234353Sdim  return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10755234353Sdim          (DstAlign == 0 || DstAlign % AlignCheck == 0));
10756234353Sdim}
10757234353Sdim
10758234353SdimEVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10759234353Sdim                                           unsigned DstAlign, unsigned SrcAlign,
10760249423Sdim                                           bool IsMemset, bool ZeroMemset,
10761234353Sdim                                           bool MemcpyStrSrc,
10762234353Sdim                                           MachineFunction &MF) const {
10763234353Sdim  const Function *F = MF.getFunction();
10764234353Sdim
10765234353Sdim  // See if we can use NEON instructions for this...
10766288943Sdim  if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10767288943Sdim      !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10768249423Sdim    bool Fast;
10769249423Sdim    if (Size >= 16 &&
10770249423Sdim        (memOpAlign(SrcAlign, DstAlign, 16) ||
10771280031Sdim         (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10772249423Sdim      return MVT::v2f64;
10773249423Sdim    } else if (Size >= 8 &&
10774249423Sdim               (memOpAlign(SrcAlign, DstAlign, 8) ||
10775280031Sdim                (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10776280031Sdim                 Fast))) {
10777249423Sdim      return MVT::f64;
10778234353Sdim    }
10779234353Sdim  }
10780234353Sdim
10781234353Sdim  // Lowering to i32/i16 if the size permits.
10782249423Sdim  if (Size >= 4)
10783234353Sdim    return MVT::i32;
10784249423Sdim  else if (Size >= 2)
10785234353Sdim    return MVT::i16;
10786234353Sdim
10787234353Sdim  // Let the target-independent logic figure it out.
10788234353Sdim  return MVT::Other;
10789234353Sdim}
10790234353Sdim
10791249423Sdimbool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10792249423Sdim  if (Val.getOpcode() != ISD::LOAD)
10793249423Sdim    return false;
10794249423Sdim
10795249423Sdim  EVT VT1 = Val.getValueType();
10796249423Sdim  if (!VT1.isSimple() || !VT1.isInteger() ||
10797249423Sdim      !VT2.isSimple() || !VT2.isInteger())
10798249423Sdim    return false;
10799249423Sdim
10800249423Sdim  switch (VT1.getSimpleVT().SimpleTy) {
10801249423Sdim  default: break;
10802249423Sdim  case MVT::i1:
10803249423Sdim  case MVT::i8:
10804249423Sdim  case MVT::i16:
10805249423Sdim    // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10806249423Sdim    return true;
10807249423Sdim  }
10808249423Sdim
10809249423Sdim  return false;
10810249423Sdim}
10811249423Sdim
10812288943Sdimbool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10813288943Sdim  EVT VT = ExtVal.getValueType();
10814288943Sdim
10815288943Sdim  if (!isTypeLegal(VT))
10816288943Sdim    return false;
10817288943Sdim
10818288943Sdim  // Don't create a loadext if we can fold the extension into a wide/long
10819288943Sdim  // instruction.
10820288943Sdim  // If there's more than one user instruction, the loadext is desirable no
10821288943Sdim  // matter what.  There can be two uses by the same instruction.
10822288943Sdim  if (ExtVal->use_empty() ||
10823288943Sdim      !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10824288943Sdim    return true;
10825288943Sdim
10826288943Sdim  SDNode *U = *ExtVal->use_begin();
10827288943Sdim  if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10828288943Sdim       U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10829288943Sdim    return false;
10830288943Sdim
10831288943Sdim  return true;
10832288943Sdim}
10833288943Sdim
10834261991Sdimbool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10835261991Sdim  if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10836261991Sdim    return false;
10837261991Sdim
10838261991Sdim  if (!isTypeLegal(EVT::getEVT(Ty1)))
10839261991Sdim    return false;
10840261991Sdim
10841261991Sdim  assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10842261991Sdim
10843261991Sdim  // Assuming the caller doesn't have a zeroext or signext return parameter,
10844261991Sdim  // truncation all the way down to i1 is valid.
10845261991Sdim  return true;
10846261991Sdim}
10847261991Sdim
10848261991Sdim
10849198090Srdivackystatic bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10850198090Srdivacky  if (V < 0)
10851198090Srdivacky    return false;
10852198090Srdivacky
10853198090Srdivacky  unsigned Scale = 1;
10854198090Srdivacky  switch (VT.getSimpleVT().SimpleTy) {
10855198090Srdivacky  default: return false;
10856198090Srdivacky  case MVT::i1:
10857198090Srdivacky  case MVT::i8:
10858198090Srdivacky    // Scale == 1;
10859198090Srdivacky    break;
10860198090Srdivacky  case MVT::i16:
10861198090Srdivacky    // Scale == 2;
10862198090Srdivacky    Scale = 2;
10863198090Srdivacky    break;
10864198090Srdivacky  case MVT::i32:
10865198090Srdivacky    // Scale == 4;
10866198090Srdivacky    Scale = 4;
10867198090Srdivacky    break;
10868198090Srdivacky  }
10869198090Srdivacky
10870198090Srdivacky  if ((V & (Scale - 1)) != 0)
10871198090Srdivacky    return false;
10872198090Srdivacky  V /= Scale;
10873198090Srdivacky  return V == (V & ((1LL << 5) - 1));
10874198090Srdivacky}
10875198090Srdivacky
10876198090Srdivackystatic bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10877198090Srdivacky                                      const ARMSubtarget *Subtarget) {
10878198090Srdivacky  bool isNeg = false;
10879198090Srdivacky  if (V < 0) {
10880198090Srdivacky    isNeg = true;
10881198090Srdivacky    V = - V;
10882198090Srdivacky  }
10883198090Srdivacky
10884198090Srdivacky  switch (VT.getSimpleVT().SimpleTy) {
10885198090Srdivacky  default: return false;
10886198090Srdivacky  case MVT::i1:
10887198090Srdivacky  case MVT::i8:
10888198090Srdivacky  case MVT::i16:
10889198090Srdivacky  case MVT::i32:
10890198090Srdivacky    // + imm12 or - imm8
10891198090Srdivacky    if (isNeg)
10892198090Srdivacky      return V == (V & ((1LL << 8) - 1));
10893198090Srdivacky    return V == (V & ((1LL << 12) - 1));
10894198090Srdivacky  case MVT::f32:
10895198090Srdivacky  case MVT::f64:
10896198090Srdivacky    // Same as ARM mode. FIXME: NEON?
10897198090Srdivacky    if (!Subtarget->hasVFP2())
10898198090Srdivacky      return false;
10899198090Srdivacky    if ((V & 3) != 0)
10900198090Srdivacky      return false;
10901198090Srdivacky    V >>= 2;
10902198090Srdivacky    return V == (V & ((1LL << 8) - 1));
10903198090Srdivacky  }
10904198090Srdivacky}
10905198090Srdivacky
10906193323Sed/// isLegalAddressImmediate - Return true if the integer value can be used
10907193323Sed/// as the offset of the target addressing mode for load / store of the
10908193323Sed/// given type.
10909198090Srdivackystatic bool isLegalAddressImmediate(int64_t V, EVT VT,
10910193323Sed                                    const ARMSubtarget *Subtarget) {
10911193323Sed  if (V == 0)
10912193323Sed    return true;
10913193323Sed
10914193323Sed  if (!VT.isSimple())
10915193323Sed    return false;
10916193323Sed
10917198090Srdivacky  if (Subtarget->isThumb1Only())
10918198090Srdivacky    return isLegalT1AddressImmediate(V, VT);
10919198090Srdivacky  else if (Subtarget->isThumb2())
10920198090Srdivacky    return isLegalT2AddressImmediate(V, VT, Subtarget);
10921193323Sed
10922198090Srdivacky  // ARM mode.
10923193323Sed  if (V < 0)
10924193323Sed    V = - V;
10925198090Srdivacky  switch (VT.getSimpleVT().SimpleTy) {
10926193323Sed  default: return false;
10927193323Sed  case MVT::i1:
10928193323Sed  case MVT::i8:
10929193323Sed  case MVT::i32:
10930193323Sed    // +- imm12
10931193323Sed    return V == (V & ((1LL << 12) - 1));
10932193323Sed  case MVT::i16:
10933193323Sed    // +- imm8
10934193323Sed    return V == (V & ((1LL << 8) - 1));
10935193323Sed  case MVT::f32:
10936193323Sed  case MVT::f64:
10937198090Srdivacky    if (!Subtarget->hasVFP2()) // FIXME: NEON?
10938193323Sed      return false;
10939193323Sed    if ((V & 3) != 0)
10940193323Sed      return false;
10941193323Sed    V >>= 2;
10942193323Sed    return V == (V & ((1LL << 8) - 1));
10943193323Sed  }
10944193323Sed}
10945193323Sed
10946198090Srdivackybool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10947198090Srdivacky                                                      EVT VT) const {
10948198090Srdivacky  int Scale = AM.Scale;
10949198090Srdivacky  if (Scale < 0)
10950198090Srdivacky    return false;
10951198090Srdivacky
10952198090Srdivacky  switch (VT.getSimpleVT().SimpleTy) {
10953198090Srdivacky  default: return false;
10954198090Srdivacky  case MVT::i1:
10955198090Srdivacky  case MVT::i8:
10956198090Srdivacky  case MVT::i16:
10957198090Srdivacky  case MVT::i32:
10958198090Srdivacky    if (Scale == 1)
10959198090Srdivacky      return true;
10960198090Srdivacky    // r + r << imm
10961198090Srdivacky    Scale = Scale & ~1;
10962198090Srdivacky    return Scale == 2 || Scale == 4 || Scale == 8;
10963198090Srdivacky  case MVT::i64:
10964198090Srdivacky    // r + r
10965198090Srdivacky    if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10966198090Srdivacky      return true;
10967198090Srdivacky    return false;
10968198090Srdivacky  case MVT::isVoid:
10969198090Srdivacky    // Note, we allow "void" uses (basically, uses that aren't loads or
10970198090Srdivacky    // stores), because arm allows folding a scale into many arithmetic
10971198090Srdivacky    // operations.  This should be made more precise and revisited later.
10972198090Srdivacky
10973198090Srdivacky    // Allow r << imm, but the imm has to be a multiple of two.
10974198090Srdivacky    if (Scale & 1) return false;
10975198090Srdivacky    return isPowerOf2_32(Scale);
10976198090Srdivacky  }
10977198090Srdivacky}
10978198090Srdivacky
10979193323Sed/// isLegalAddressingMode - Return true if the addressing mode represented
10980193323Sed/// by AM is legal for this target, for a load/store of the specified type.
10981288943Sdimbool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10982288943Sdim                                              const AddrMode &AM, Type *Ty,
10983288943Sdim                                              unsigned AS) const {
10984288943Sdim  EVT VT = getValueType(DL, Ty, true);
10985193323Sed  if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10986193323Sed    return false;
10987193323Sed
10988193323Sed  // Can never fold addr of global into load/store.
10989193323Sed  if (AM.BaseGV)
10990193323Sed    return false;
10991193323Sed
10992193323Sed  switch (AM.Scale) {
10993193323Sed  case 0:  // no scale reg, must be "r+i" or "r", or "i".
10994193323Sed    break;
10995193323Sed  case 1:
10996198090Srdivacky    if (Subtarget->isThumb1Only())
10997193323Sed      return false;
10998193323Sed    // FALL THROUGH.
10999193323Sed  default:
11000193323Sed    // ARM doesn't support any R+R*scale+imm addr modes.
11001193323Sed    if (AM.BaseOffs)
11002193323Sed      return false;
11003193323Sed
11004193323Sed    if (!VT.isSimple())
11005193323Sed      return false;
11006193323Sed
11007198090Srdivacky    if (Subtarget->isThumb2())
11008198090Srdivacky      return isLegalT2ScaledAddressingMode(AM, VT);
11009198090Srdivacky
11010193323Sed    int Scale = AM.Scale;
11011198090Srdivacky    switch (VT.getSimpleVT().SimpleTy) {
11012193323Sed    default: return false;
11013193323Sed    case MVT::i1:
11014193323Sed    case MVT::i8:
11015193323Sed    case MVT::i32:
11016193323Sed      if (Scale < 0) Scale = -Scale;
11017193323Sed      if (Scale == 1)
11018193323Sed        return true;
11019193323Sed      // r + r << imm
11020193323Sed      return isPowerOf2_32(Scale & ~1);
11021193323Sed    case MVT::i16:
11022198090Srdivacky    case MVT::i64:
11023193323Sed      // r + r
11024193323Sed      if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11025193323Sed        return true;
11026193323Sed      return false;
11027193323Sed
11028193323Sed    case MVT::isVoid:
11029193323Sed      // Note, we allow "void" uses (basically, uses that aren't loads or
11030193323Sed      // stores), because arm allows folding a scale into many arithmetic
11031193323Sed      // operations.  This should be made more precise and revisited later.
11032193323Sed
11033193323Sed      // Allow r << imm, but the imm has to be a multiple of two.
11034198090Srdivacky      if (Scale & 1) return false;
11035198090Srdivacky      return isPowerOf2_32(Scale);
11036193323Sed    }
11037193323Sed  }
11038193323Sed  return true;
11039193323Sed}
11040193323Sed
11041199481Srdivacky/// isLegalICmpImmediate - Return true if the specified immediate is legal
11042199481Srdivacky/// icmp immediate, that is the target has icmp instructions which can compare
11043199481Srdivacky/// a register against the immediate without having to materialize the
11044199481Srdivacky/// immediate into a register.
11045199481Srdivackybool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11046234353Sdim  // Thumb2 and ARM modes can use cmn for negative immediates.
11047199481Srdivacky  if (!Subtarget->isThumb())
11048288943Sdim    return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11049199481Srdivacky  if (Subtarget->isThumb2())
11050288943Sdim    return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11051234353Sdim  // Thumb1 doesn't have cmn, and only 8-bit immediates.
11052199481Srdivacky  return Imm >= 0 && Imm <= 255;
11053199481Srdivacky}
11054199481Srdivacky
11055239462Sdim/// isLegalAddImmediate - Return true if the specified immediate is a legal add
11056239462Sdim/// *or sub* immediate, that is the target has add or sub instructions which can
11057239462Sdim/// add a register with the immediate without having to materialize the
11058223017Sdim/// immediate into a register.
11059223017Sdimbool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11060239462Sdim  // Same encoding for add/sub, just flip the sign.
11061288943Sdim  int64_t AbsImm = std::abs(Imm);
11062239462Sdim  if (!Subtarget->isThumb())
11063239462Sdim    return ARM_AM::getSOImmVal(AbsImm) != -1;
11064239462Sdim  if (Subtarget->isThumb2())
11065239462Sdim    return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11066239462Sdim  // Thumb1 only has 8-bit unsigned immediate.
11067239462Sdim  return AbsImm >= 0 && AbsImm <= 255;
11068223017Sdim}
11069223017Sdim
11070198090Srdivackystatic bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11071195340Sed                                      bool isSEXTLoad, SDValue &Base,
11072195340Sed                                      SDValue &Offset, bool &isInc,
11073195340Sed                                      SelectionDAG &DAG) {
11074193323Sed  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11075193323Sed    return false;
11076193323Sed
11077193323Sed  if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11078193323Sed    // AddressingMode 3
11079193323Sed    Base = Ptr->getOperand(0);
11080193323Sed    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11081193323Sed      int RHSC = (int)RHS->getZExtValue();
11082193323Sed      if (RHSC < 0 && RHSC > -256) {
11083195340Sed        assert(Ptr->getOpcode() == ISD::ADD);
11084193323Sed        isInc = false;
11085288943Sdim        Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11086193323Sed        return true;
11087193323Sed      }
11088193323Sed    }
11089193323Sed    isInc = (Ptr->getOpcode() == ISD::ADD);
11090193323Sed    Offset = Ptr->getOperand(1);
11091193323Sed    return true;
11092193323Sed  } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11093193323Sed    // AddressingMode 2
11094193323Sed    if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11095193323Sed      int RHSC = (int)RHS->getZExtValue();
11096193323Sed      if (RHSC < 0 && RHSC > -0x1000) {
11097195340Sed        assert(Ptr->getOpcode() == ISD::ADD);
11098193323Sed        isInc = false;
11099288943Sdim        Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11100193323Sed        Base = Ptr->getOperand(0);
11101193323Sed        return true;
11102193323Sed      }
11103193323Sed    }
11104193323Sed
11105193323Sed    if (Ptr->getOpcode() == ISD::ADD) {
11106193323Sed      isInc = true;
11107226633Sdim      ARM_AM::ShiftOpc ShOpcVal=
11108226633Sdim        ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11109193323Sed      if (ShOpcVal != ARM_AM::no_shift) {
11110193323Sed        Base = Ptr->getOperand(1);
11111193323Sed        Offset = Ptr->getOperand(0);
11112193323Sed      } else {
11113193323Sed        Base = Ptr->getOperand(0);
11114193323Sed        Offset = Ptr->getOperand(1);
11115193323Sed      }
11116193323Sed      return true;
11117193323Sed    }
11118193323Sed
11119193323Sed    isInc = (Ptr->getOpcode() == ISD::ADD);
11120193323Sed    Base = Ptr->getOperand(0);
11121193323Sed    Offset = Ptr->getOperand(1);
11122193323Sed    return true;
11123193323Sed  }
11124193323Sed
11125199481Srdivacky  // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11126193323Sed  return false;
11127193323Sed}
11128193323Sed
11129198090Srdivackystatic bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11130195340Sed                                     bool isSEXTLoad, SDValue &Base,
11131195340Sed                                     SDValue &Offset, bool &isInc,
11132195340Sed                                     SelectionDAG &DAG) {
11133195340Sed  if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11134195340Sed    return false;
11135195340Sed
11136195340Sed  Base = Ptr->getOperand(0);
11137195340Sed  if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11138195340Sed    int RHSC = (int)RHS->getZExtValue();
11139195340Sed    if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11140195340Sed      assert(Ptr->getOpcode() == ISD::ADD);
11141195340Sed      isInc = false;
11142288943Sdim      Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11143195340Sed      return true;
11144195340Sed    } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11145195340Sed      isInc = Ptr->getOpcode() == ISD::ADD;
11146288943Sdim      Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11147195340Sed      return true;
11148195340Sed    }
11149195340Sed  }
11150195340Sed
11151195340Sed  return false;
11152195340Sed}
11153195340Sed
11154193323Sed/// getPreIndexedAddressParts - returns true by value, base pointer and
11155193323Sed/// offset pointer and addressing mode by reference if the node's address
11156193323Sed/// can be legally represented as pre-indexed load / store address.
11157193323Sedbool
11158193323SedARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11159193323Sed                                             SDValue &Offset,
11160193323Sed                                             ISD::MemIndexedMode &AM,
11161193323Sed                                             SelectionDAG &DAG) const {
11162195340Sed  if (Subtarget->isThumb1Only())
11163193323Sed    return false;
11164193323Sed
11165198090Srdivacky  EVT VT;
11166193323Sed  SDValue Ptr;
11167193323Sed  bool isSEXTLoad = false;
11168193323Sed  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11169193323Sed    Ptr = LD->getBasePtr();
11170193323Sed    VT  = LD->getMemoryVT();
11171193323Sed    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11172193323Sed  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11173193323Sed    Ptr = ST->getBasePtr();
11174193323Sed    VT  = ST->getMemoryVT();
11175193323Sed  } else
11176193323Sed    return false;
11177193323Sed
11178193323Sed  bool isInc;
11179195340Sed  bool isLegal = false;
11180195340Sed  if (Subtarget->isThumb2())
11181195340Sed    isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11182195340Sed                                       Offset, isInc, DAG);
11183198090Srdivacky  else
11184195340Sed    isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11185195340Sed                                        Offset, isInc, DAG);
11186195340Sed  if (!isLegal)
11187195340Sed    return false;
11188195340Sed
11189195340Sed  AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11190195340Sed  return true;
11191193323Sed}
11192193323Sed
11193193323Sed/// getPostIndexedAddressParts - returns true by value, base pointer and
11194193323Sed/// offset pointer and addressing mode by reference if this node can be
11195193323Sed/// combined with a load / store to form a post-indexed load / store.
11196193323Sedbool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11197193323Sed                                                   SDValue &Base,
11198193323Sed                                                   SDValue &Offset,
11199193323Sed                                                   ISD::MemIndexedMode &AM,
11200193323Sed                                                   SelectionDAG &DAG) const {
11201195340Sed  if (Subtarget->isThumb1Only())
11202193323Sed    return false;
11203193323Sed
11204198090Srdivacky  EVT VT;
11205193323Sed  SDValue Ptr;
11206193323Sed  bool isSEXTLoad = false;
11207193323Sed  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11208193323Sed    VT  = LD->getMemoryVT();
11209208599Srdivacky    Ptr = LD->getBasePtr();
11210193323Sed    isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11211193323Sed  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11212193323Sed    VT  = ST->getMemoryVT();
11213208599Srdivacky    Ptr = ST->getBasePtr();
11214193323Sed  } else
11215193323Sed    return false;
11216193323Sed
11217193323Sed  bool isInc;
11218195340Sed  bool isLegal = false;
11219195340Sed  if (Subtarget->isThumb2())
11220195340Sed    isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11221208599Srdivacky                                       isInc, DAG);
11222198090Srdivacky  else
11223195340Sed    isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11224195340Sed                                        isInc, DAG);
11225195340Sed  if (!isLegal)
11226195340Sed    return false;
11227195340Sed
11228208599Srdivacky  if (Ptr != Base) {
11229208599Srdivacky    // Swap base ptr and offset to catch more post-index load / store when
11230208599Srdivacky    // it's legal. In Thumb2 mode, offset must be an immediate.
11231208599Srdivacky    if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11232208599Srdivacky        !Subtarget->isThumb2())
11233208599Srdivacky      std::swap(Base, Offset);
11234208599Srdivacky
11235208599Srdivacky    // Post-indexed load / store update the base pointer.
11236208599Srdivacky    if (Ptr != Base)
11237208599Srdivacky      return false;
11238208599Srdivacky  }
11239208599Srdivacky
11240195340Sed  AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11241195340Sed  return true;
11242193323Sed}
11243193323Sed
11244276479Sdimvoid ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11245276479Sdim                                                      APInt &KnownZero,
11246276479Sdim                                                      APInt &KnownOne,
11247276479Sdim                                                      const SelectionDAG &DAG,
11248276479Sdim                                                      unsigned Depth) const {
11249261991Sdim  unsigned BitWidth = KnownOne.getBitWidth();
11250261991Sdim  KnownZero = KnownOne = APInt(BitWidth, 0);
11251193323Sed  switch (Op.getOpcode()) {
11252193323Sed  default: break;
11253261991Sdim  case ARMISD::ADDC:
11254261991Sdim  case ARMISD::ADDE:
11255261991Sdim  case ARMISD::SUBC:
11256261991Sdim  case ARMISD::SUBE:
11257261991Sdim    // These nodes' second result is a boolean
11258261991Sdim    if (Op.getResNo() == 0)
11259261991Sdim      break;
11260261991Sdim    KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11261261991Sdim    break;
11262193323Sed  case ARMISD::CMOV: {
11263193323Sed    // Bits are known zero/one if known on the LHS and RHS.
11264276479Sdim    DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11265193323Sed    if (KnownZero == 0 && KnownOne == 0) return;
11266193323Sed
11267193323Sed    APInt KnownZeroRHS, KnownOneRHS;
11268276479Sdim    DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11269193323Sed    KnownZero &= KnownZeroRHS;
11270193323Sed    KnownOne  &= KnownOneRHS;
11271193323Sed    return;
11272193323Sed  }
11273276479Sdim  case ISD::INTRINSIC_W_CHAIN: {
11274276479Sdim    ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11275276479Sdim    Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11276276479Sdim    switch (IntID) {
11277276479Sdim    default: return;
11278276479Sdim    case Intrinsic::arm_ldaex:
11279276479Sdim    case Intrinsic::arm_ldrex: {
11280276479Sdim      EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11281276479Sdim      unsigned MemBits = VT.getScalarType().getSizeInBits();
11282276479Sdim      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11283276479Sdim      return;
11284276479Sdim    }
11285276479Sdim    }
11286193323Sed  }
11287276479Sdim  }
11288193323Sed}
11289193323Sed
11290193323Sed//===----------------------------------------------------------------------===//
11291193323Sed//                           ARM Inline Assembly Support
11292193323Sed//===----------------------------------------------------------------------===//
11293193323Sed
11294218893Sdimbool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11295218893Sdim  // Looking for "rev" which is V6+.
11296218893Sdim  if (!Subtarget->hasV6Ops())
11297218893Sdim    return false;
11298218893Sdim
11299218893Sdim  InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11300218893Sdim  std::string AsmStr = IA->getAsmString();
11301218893Sdim  SmallVector<StringRef, 4> AsmPieces;
11302218893Sdim  SplitString(AsmStr, AsmPieces, ";\n");
11303218893Sdim
11304218893Sdim  switch (AsmPieces.size()) {
11305218893Sdim  default: return false;
11306218893Sdim  case 1:
11307218893Sdim    AsmStr = AsmPieces[0];
11308218893Sdim    AsmPieces.clear();
11309218893Sdim    SplitString(AsmStr, AsmPieces, " \t,");
11310218893Sdim
11311218893Sdim    // rev $0, $1
11312218893Sdim    if (AsmPieces.size() == 3 &&
11313218893Sdim        AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11314218893Sdim        IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11315226633Sdim      IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11316218893Sdim      if (Ty && Ty->getBitWidth() == 32)
11317218893Sdim        return IntrinsicLowering::LowerToByteSwap(CI);
11318218893Sdim    }
11319218893Sdim    break;
11320218893Sdim  }
11321218893Sdim
11322218893Sdim  return false;
11323218893Sdim}
11324218893Sdim
11325193323Sed/// getConstraintType - Given a constraint letter, return the type of
11326193323Sed/// constraint it is for this target.
11327193323SedARMTargetLowering::ConstraintType
11328288943SdimARMTargetLowering::getConstraintType(StringRef Constraint) const {
11329193323Sed  if (Constraint.size() == 1) {
11330193323Sed    switch (Constraint[0]) {
11331193323Sed    default:  break;
11332193323Sed    case 'l': return C_RegisterClass;
11333193323Sed    case 'w': return C_RegisterClass;
11334224145Sdim    case 'h': return C_RegisterClass;
11335224145Sdim    case 'x': return C_RegisterClass;
11336224145Sdim    case 't': return C_RegisterClass;
11337224145Sdim    case 'j': return C_Other; // Constant for movw.
11338226633Sdim      // An address with a single base register. Due to the way we
11339226633Sdim      // currently handle addresses it is the same as an 'r' memory constraint.
11340226633Sdim    case 'Q': return C_Memory;
11341193323Sed    }
11342224145Sdim  } else if (Constraint.size() == 2) {
11343224145Sdim    switch (Constraint[0]) {
11344224145Sdim    default: break;
11345224145Sdim    // All 'U+' constraints are addresses.
11346224145Sdim    case 'U': return C_Memory;
11347224145Sdim    }
11348193323Sed  }
11349193323Sed  return TargetLowering::getConstraintType(Constraint);
11350193323Sed}
11351193323Sed
11352218893Sdim/// Examine constraint type and operand type and determine a weight value.
11353218893Sdim/// This object must already have been set up with the operand type
11354218893Sdim/// and the current alternative constraint selected.
11355218893SdimTargetLowering::ConstraintWeight
11356218893SdimARMTargetLowering::getSingleConstraintMatchWeight(
11357218893Sdim    AsmOperandInfo &info, const char *constraint) const {
11358218893Sdim  ConstraintWeight weight = CW_Invalid;
11359218893Sdim  Value *CallOperandVal = info.CallOperandVal;
11360218893Sdim    // If we don't have a value, we can't do a match,
11361218893Sdim    // but allow it at the lowest weight.
11362276479Sdim  if (!CallOperandVal)
11363218893Sdim    return CW_Default;
11364226633Sdim  Type *type = CallOperandVal->getType();
11365218893Sdim  // Look at the constraint type.
11366218893Sdim  switch (*constraint) {
11367218893Sdim  default:
11368218893Sdim    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11369218893Sdim    break;
11370218893Sdim  case 'l':
11371218893Sdim    if (type->isIntegerTy()) {
11372218893Sdim      if (Subtarget->isThumb())
11373218893Sdim        weight = CW_SpecificReg;
11374218893Sdim      else
11375218893Sdim        weight = CW_Register;
11376218893Sdim    }
11377218893Sdim    break;
11378218893Sdim  case 'w':
11379218893Sdim    if (type->isFloatingPointTy())
11380218893Sdim      weight = CW_Register;
11381218893Sdim    break;
11382218893Sdim  }
11383218893Sdim  return weight;
11384218893Sdim}
11385218893Sdim
11386224145Sdimtypedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11387288943SdimRCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11388288943Sdim    const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11389193323Sed  if (Constraint.size() == 1) {
11390202375Srdivacky    // GCC ARM Constraint Letters
11391193323Sed    switch (Constraint[0]) {
11392224145Sdim    case 'l': // Low regs or general regs.
11393202375Srdivacky      if (Subtarget->isThumb())
11394239462Sdim        return RCPair(0U, &ARM::tGPRRegClass);
11395239462Sdim      return RCPair(0U, &ARM::GPRRegClass);
11396224145Sdim    case 'h': // High regs or no regs.
11397224145Sdim      if (Subtarget->isThumb())
11398239462Sdim        return RCPair(0U, &ARM::hGPRRegClass);
11399224145Sdim      break;
11400193323Sed    case 'r':
11401280031Sdim      if (Subtarget->isThumb1Only())
11402280031Sdim        return RCPair(0U, &ARM::tGPRRegClass);
11403239462Sdim      return RCPair(0U, &ARM::GPRRegClass);
11404193323Sed    case 'w':
11405261991Sdim      if (VT == MVT::Other)
11406261991Sdim        break;
11407193323Sed      if (VT == MVT::f32)
11408239462Sdim        return RCPair(0U, &ARM::SPRRegClass);
11409201360Srdivacky      if (VT.getSizeInBits() == 64)
11410239462Sdim        return RCPair(0U, &ARM::DPRRegClass);
11411200581Srdivacky      if (VT.getSizeInBits() == 128)
11412239462Sdim        return RCPair(0U, &ARM::QPRRegClass);
11413193323Sed      break;
11414224145Sdim    case 'x':
11415261991Sdim      if (VT == MVT::Other)
11416261991Sdim        break;
11417224145Sdim      if (VT == MVT::f32)
11418239462Sdim        return RCPair(0U, &ARM::SPR_8RegClass);
11419224145Sdim      if (VT.getSizeInBits() == 64)
11420239462Sdim        return RCPair(0U, &ARM::DPR_8RegClass);
11421224145Sdim      if (VT.getSizeInBits() == 128)
11422239462Sdim        return RCPair(0U, &ARM::QPR_8RegClass);
11423224145Sdim      break;
11424224145Sdim    case 't':
11425224145Sdim      if (VT == MVT::f32)
11426239462Sdim        return RCPair(0U, &ARM::SPRRegClass);
11427224145Sdim      break;
11428193323Sed    }
11429193323Sed  }
11430205218Srdivacky  if (StringRef("{cc}").equals_lower(Constraint))
11431239462Sdim    return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11432205218Srdivacky
11433288943Sdim  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11434193323Sed}
11435193323Sed
11436193323Sed/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11437193323Sed/// vector.  If it is invalid, don't add anything to Ops.
11438193323Sedvoid ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11439223017Sdim                                                     std::string &Constraint,
11440193323Sed                                                     std::vector<SDValue>&Ops,
11441193323Sed                                                     SelectionDAG &DAG) const {
11442276479Sdim  SDValue Result;
11443193323Sed
11444223017Sdim  // Currently only support length 1 constraints.
11445223017Sdim  if (Constraint.length() != 1) return;
11446223017Sdim
11447223017Sdim  char ConstraintLetter = Constraint[0];
11448223017Sdim  switch (ConstraintLetter) {
11449193323Sed  default: break;
11450224145Sdim  case 'j':
11451193323Sed  case 'I': case 'J': case 'K': case 'L':
11452193323Sed  case 'M': case 'N': case 'O':
11453193323Sed    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11454193323Sed    if (!C)
11455193323Sed      return;
11456193323Sed
11457193323Sed    int64_t CVal64 = C->getSExtValue();
11458193323Sed    int CVal = (int) CVal64;
11459193323Sed    // None of these constraints allow values larger than 32 bits.  Check
11460193323Sed    // that the value fits in an int.
11461193323Sed    if (CVal != CVal64)
11462193323Sed      return;
11463193323Sed
11464223017Sdim    switch (ConstraintLetter) {
11465224145Sdim      case 'j':
11466226633Sdim        // Constant suitable for movw, must be between 0 and
11467226633Sdim        // 65535.
11468226633Sdim        if (Subtarget->hasV6T2Ops())
11469226633Sdim          if (CVal >= 0 && CVal <= 65535)
11470226633Sdim            break;
11471226633Sdim        return;
11472193323Sed      case 'I':
11473198090Srdivacky        if (Subtarget->isThumb1Only()) {
11474198090Srdivacky          // This must be a constant between 0 and 255, for ADD
11475198090Srdivacky          // immediates.
11476193323Sed          if (CVal >= 0 && CVal <= 255)
11477193323Sed            break;
11478198090Srdivacky        } else if (Subtarget->isThumb2()) {
11479198090Srdivacky          // A constant that can be used as an immediate value in a
11480198090Srdivacky          // data-processing instruction.
11481198090Srdivacky          if (ARM_AM::getT2SOImmVal(CVal) != -1)
11482198090Srdivacky            break;
11483193323Sed        } else {
11484193323Sed          // A constant that can be used as an immediate value in a
11485193323Sed          // data-processing instruction.
11486193323Sed          if (ARM_AM::getSOImmVal(CVal) != -1)
11487193323Sed            break;
11488193323Sed        }
11489193323Sed        return;
11490193323Sed
11491193323Sed      case 'J':
11492296417Sdim        if (Subtarget->isThumb1Only()) {
11493193323Sed          // This must be a constant between -255 and -1, for negated ADD
11494193323Sed          // immediates. This can be used in GCC with an "n" modifier that
11495193323Sed          // prints the negated value, for use with SUB instructions. It is
11496193323Sed          // not useful otherwise but is implemented for compatibility.
11497193323Sed          if (CVal >= -255 && CVal <= -1)
11498193323Sed            break;
11499193323Sed        } else {
11500193323Sed          // This must be a constant between -4095 and 4095. It is not clear
11501193323Sed          // what this constraint is intended for. Implemented for
11502193323Sed          // compatibility with GCC.
11503193323Sed          if (CVal >= -4095 && CVal <= 4095)
11504193323Sed            break;
11505193323Sed        }
11506193323Sed        return;
11507193323Sed
11508193323Sed      case 'K':
11509198090Srdivacky        if (Subtarget->isThumb1Only()) {
11510193323Sed          // A 32-bit value where only one byte has a nonzero value. Exclude
11511193323Sed          // zero to match GCC. This constraint is used by GCC internally for
11512193323Sed          // constants that can be loaded with a move/shift combination.
11513193323Sed          // It is not useful otherwise but is implemented for compatibility.
11514193323Sed          if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11515193323Sed            break;
11516198090Srdivacky        } else if (Subtarget->isThumb2()) {
11517198090Srdivacky          // A constant whose bitwise inverse can be used as an immediate
11518198090Srdivacky          // value in a data-processing instruction. This can be used in GCC
11519198090Srdivacky          // with a "B" modifier that prints the inverted value, for use with
11520198090Srdivacky          // BIC and MVN instructions. It is not useful otherwise but is
11521198090Srdivacky          // implemented for compatibility.
11522198090Srdivacky          if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11523198090Srdivacky            break;
11524193323Sed        } else {
11525193323Sed          // A constant whose bitwise inverse can be used as an immediate
11526193323Sed          // value in a data-processing instruction. This can be used in GCC
11527193323Sed          // with a "B" modifier that prints the inverted value, for use with
11528193323Sed          // BIC and MVN instructions. It is not useful otherwise but is
11529193323Sed          // implemented for compatibility.
11530193323Sed          if (ARM_AM::getSOImmVal(~CVal) != -1)
11531193323Sed            break;
11532193323Sed        }
11533193323Sed        return;
11534193323Sed
11535193323Sed      case 'L':
11536198090Srdivacky        if (Subtarget->isThumb1Only()) {
11537193323Sed          // This must be a constant between -7 and 7,
11538193323Sed          // for 3-operand ADD/SUB immediate instructions.
11539193323Sed          if (CVal >= -7 && CVal < 7)
11540193323Sed            break;
11541198090Srdivacky        } else if (Subtarget->isThumb2()) {
11542198090Srdivacky          // A constant whose negation can be used as an immediate value in a
11543198090Srdivacky          // data-processing instruction. This can be used in GCC with an "n"
11544198090Srdivacky          // modifier that prints the negated value, for use with SUB
11545198090Srdivacky          // instructions. It is not useful otherwise but is implemented for
11546198090Srdivacky          // compatibility.
11547198090Srdivacky          if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11548198090Srdivacky            break;
11549193323Sed        } else {
11550193323Sed          // A constant whose negation can be used as an immediate value in a
11551193323Sed          // data-processing instruction. This can be used in GCC with an "n"
11552193323Sed          // modifier that prints the negated value, for use with SUB
11553193323Sed          // instructions. It is not useful otherwise but is implemented for
11554193323Sed          // compatibility.
11555193323Sed          if (ARM_AM::getSOImmVal(-CVal) != -1)
11556193323Sed            break;
11557193323Sed        }
11558193323Sed        return;
11559193323Sed
11560193323Sed      case 'M':
11561296417Sdim        if (Subtarget->isThumb1Only()) {
11562193323Sed          // This must be a multiple of 4 between 0 and 1020, for
11563193323Sed          // ADD sp + immediate.
11564193323Sed          if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11565193323Sed            break;
11566193323Sed        } else {
11567193323Sed          // A power of two or a constant between 0 and 32.  This is used in
11568193323Sed          // GCC for the shift amount on shifted register operands, but it is
11569193323Sed          // useful in general for any shift amounts.
11570193323Sed          if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11571193323Sed            break;
11572193323Sed        }
11573193323Sed        return;
11574193323Sed
11575193323Sed      case 'N':
11576198090Srdivacky        if (Subtarget->isThumb()) {  // FIXME thumb2
11577193323Sed          // This must be a constant between 0 and 31, for shift amounts.
11578193323Sed          if (CVal >= 0 && CVal <= 31)
11579193323Sed            break;
11580193323Sed        }
11581193323Sed        return;
11582193323Sed
11583193323Sed      case 'O':
11584198090Srdivacky        if (Subtarget->isThumb()) {  // FIXME thumb2
11585193323Sed          // This must be a multiple of 4 between -508 and 508, for
11586193323Sed          // ADD/SUB sp = sp + immediate.
11587193323Sed          if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11588193323Sed            break;
11589193323Sed        }
11590193323Sed        return;
11591193323Sed    }
11592288943Sdim    Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11593193323Sed    break;
11594193323Sed  }
11595193323Sed
11596193323Sed  if (Result.getNode()) {
11597193323Sed    Ops.push_back(Result);
11598193323Sed    return;
11599193323Sed  }
11600210299Sed  return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11601193323Sed}
11602198090Srdivacky
11603296417Sdimstatic RTLIB::Libcall getDivRemLibcall(
11604296417Sdim    const SDNode *N, MVT::SimpleValueType SVT) {
11605296417Sdim  assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11606296417Sdim          N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11607296417Sdim         "Unhandled Opcode in getDivRemLibcall");
11608296417Sdim  bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11609296417Sdim                  N->getOpcode() == ISD::SREM;
11610261991Sdim  RTLIB::Libcall LC;
11611296417Sdim  switch (SVT) {
11612261991Sdim  default: llvm_unreachable("Unexpected request for libcall!");
11613280031Sdim  case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11614280031Sdim  case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11615280031Sdim  case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11616280031Sdim  case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11617261991Sdim  }
11618296417Sdim  return LC;
11619296417Sdim}
11620261991Sdim
11621296417Sdimstatic TargetLowering::ArgListTy getDivRemArgList(
11622296417Sdim    const SDNode *N, LLVMContext *Context) {
11623296417Sdim  assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11624296417Sdim          N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11625296417Sdim         "Unhandled Opcode in getDivRemArgList");
11626296417Sdim  bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11627296417Sdim                  N->getOpcode() == ISD::SREM;
11628261991Sdim  TargetLowering::ArgListTy Args;
11629261991Sdim  TargetLowering::ArgListEntry Entry;
11630296417Sdim  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11631296417Sdim    EVT ArgVT = N->getOperand(i).getValueType();
11632296417Sdim    Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11633296417Sdim    Entry.Node = N->getOperand(i);
11634261991Sdim    Entry.Ty = ArgTy;
11635261991Sdim    Entry.isSExt = isSigned;
11636261991Sdim    Entry.isZExt = !isSigned;
11637261991Sdim    Args.push_back(Entry);
11638261991Sdim  }
11639296417Sdim  return Args;
11640296417Sdim}
11641261991Sdim
11642296417SdimSDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11643296417Sdim  assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11644296417Sdim         "Register-based DivRem lowering only");
11645296417Sdim  unsigned Opcode = Op->getOpcode();
11646296417Sdim  assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11647296417Sdim         "Invalid opcode for Div/Rem lowering");
11648296417Sdim  bool isSigned = (Opcode == ISD::SDIVREM);
11649296417Sdim  EVT VT = Op->getValueType(0);
11650296417Sdim  Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11651296417Sdim
11652296417Sdim  RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11653296417Sdim                                       VT.getSimpleVT().SimpleTy);
11654296417Sdim  SDValue InChain = DAG.getEntryNode();
11655296417Sdim
11656296417Sdim  TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11657296417Sdim                                                    DAG.getContext());
11658296417Sdim
11659261991Sdim  SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11660288943Sdim                                         getPointerTy(DAG.getDataLayout()));
11661261991Sdim
11662280031Sdim  Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11663261991Sdim
11664261991Sdim  SDLoc dl(Op);
11665276479Sdim  TargetLowering::CallLoweringInfo CLI(DAG);
11666276479Sdim  CLI.setDebugLoc(dl).setChain(InChain)
11667276479Sdim    .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11668276479Sdim    .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11669276479Sdim
11670261991Sdim  std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11671261991Sdim  return CallInfo.first;
11672261991Sdim}
11673261991Sdim
11674296417Sdim// Lowers REM using divmod helpers
11675296417Sdim// see RTABI section 4.2/4.3
11676296417SdimSDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11677296417Sdim  // Build return types (div and rem)
11678296417Sdim  std::vector<Type*> RetTyParams;
11679296417Sdim  Type *RetTyElement;
11680296417Sdim
11681296417Sdim  switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11682296417Sdim  default: llvm_unreachable("Unexpected request for libcall!");
11683296417Sdim  case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11684296417Sdim  case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11685296417Sdim  case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11686296417Sdim  case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11687296417Sdim  }
11688296417Sdim
11689296417Sdim  RetTyParams.push_back(RetTyElement);
11690296417Sdim  RetTyParams.push_back(RetTyElement);
11691296417Sdim  ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11692296417Sdim  Type *RetTy = StructType::get(*DAG.getContext(), ret);
11693296417Sdim
11694296417Sdim  RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11695296417Sdim                                                             SimpleTy);
11696296417Sdim  SDValue InChain = DAG.getEntryNode();
11697296417Sdim  TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11698296417Sdim  bool isSigned = N->getOpcode() == ISD::SREM;
11699296417Sdim  SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11700296417Sdim                                         getPointerTy(DAG.getDataLayout()));
11701296417Sdim
11702296417Sdim  // Lower call
11703296417Sdim  CallLoweringInfo CLI(DAG);
11704296417Sdim  CLI.setChain(InChain)
11705296417Sdim     .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11706296417Sdim     .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11707296417Sdim  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11708296417Sdim
11709296417Sdim  // Return second (rem) result operand (first contains div)
11710296417Sdim  SDNode *ResNode = CallResult.first.getNode();
11711296417Sdim  assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11712296417Sdim  return ResNode->getOperand(1);
11713296417Sdim}
11714296417Sdim
11715276479SdimSDValue
11716276479SdimARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11717276479Sdim  assert(Subtarget->isTargetWindows() && "unsupported target platform");
11718276479Sdim  SDLoc DL(Op);
11719276479Sdim
11720276479Sdim  // Get the inputs.
11721276479Sdim  SDValue Chain = Op.getOperand(0);
11722276479Sdim  SDValue Size  = Op.getOperand(1);
11723276479Sdim
11724276479Sdim  SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11725288943Sdim                              DAG.getConstant(2, DL, MVT::i32));
11726276479Sdim
11727276479Sdim  SDValue Flag;
11728276479Sdim  Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11729276479Sdim  Flag = Chain.getValue(1);
11730276479Sdim
11731276479Sdim  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11732276479Sdim  Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11733276479Sdim
11734276479Sdim  SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11735276479Sdim  Chain = NewSP.getValue(1);
11736276479Sdim
11737276479Sdim  SDValue Ops[2] = { NewSP, Chain };
11738276479Sdim  return DAG.getMergeValues(Ops, DL);
11739276479Sdim}
11740276479Sdim
11741280031SdimSDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11742280031Sdim  assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11743280031Sdim         "Unexpected type for custom-lowering FP_EXTEND");
11744280031Sdim
11745280031Sdim  RTLIB::Libcall LC;
11746280031Sdim  LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11747280031Sdim
11748280031Sdim  SDValue SrcVal = Op.getOperand(0);
11749296417Sdim  return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11750296417Sdim                     SDLoc(Op)).first;
11751280031Sdim}
11752280031Sdim
11753280031SdimSDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11754280031Sdim  assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11755280031Sdim         Subtarget->isFPOnlySP() &&
11756280031Sdim         "Unexpected type for custom-lowering FP_ROUND");
11757280031Sdim
11758280031Sdim  RTLIB::Libcall LC;
11759280031Sdim  LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11760280031Sdim
11761280031Sdim  SDValue SrcVal = Op.getOperand(0);
11762296417Sdim  return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11763296417Sdim                     SDLoc(Op)).first;
11764280031Sdim}
11765280031Sdim
11766198090Srdivackybool
11767198090SrdivackyARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11768198090Srdivacky  // The ARM target isn't yet aware of offsets.
11769198090Srdivacky  return false;
11770198090Srdivacky}
11771198892Srdivacky
11772212904Sdimbool ARM::isBitFieldInvertedMask(unsigned v) {
11773212904Sdim  if (v == 0xffffffff)
11774261991Sdim    return false;
11775261991Sdim
11776212904Sdim  // there can be 1's on either or both "outsides", all the "inside"
11777212904Sdim  // bits must be 0's
11778288943Sdim  return isShiftedMask_32(~v);
11779212904Sdim}
11780212904Sdim
11781198892Srdivacky/// isFPImmLegal - Returns true if the target can instruction select the
11782198892Srdivacky/// specified FP immediate natively. If false, the legalizer will
11783198892Srdivacky/// materialize the FP immediate as a load from a constant pool.
11784198892Srdivackybool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11785198892Srdivacky  if (!Subtarget->hasVFP3())
11786198892Srdivacky    return false;
11787198892Srdivacky  if (VT == MVT::f32)
11788226633Sdim    return ARM_AM::getFP32Imm(Imm) != -1;
11789280031Sdim  if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11790226633Sdim    return ARM_AM::getFP64Imm(Imm) != -1;
11791198892Srdivacky  return false;
11792198892Srdivacky}
11793218893Sdim
11794218893Sdim/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11795218893Sdim/// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11796218893Sdim/// specified in the intrinsic calls.
11797218893Sdimbool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11798218893Sdim                                           const CallInst &I,
11799218893Sdim                                           unsigned Intrinsic) const {
11800218893Sdim  switch (Intrinsic) {
11801218893Sdim  case Intrinsic::arm_neon_vld1:
11802218893Sdim  case Intrinsic::arm_neon_vld2:
11803218893Sdim  case Intrinsic::arm_neon_vld3:
11804218893Sdim  case Intrinsic::arm_neon_vld4:
11805218893Sdim  case Intrinsic::arm_neon_vld2lane:
11806218893Sdim  case Intrinsic::arm_neon_vld3lane:
11807218893Sdim  case Intrinsic::arm_neon_vld4lane: {
11808218893Sdim    Info.opc = ISD::INTRINSIC_W_CHAIN;
11809218893Sdim    // Conservatively set memVT to the entire set of vectors loaded.
11810288943Sdim    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11811296417Sdim    uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11812218893Sdim    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11813218893Sdim    Info.ptrVal = I.getArgOperand(0);
11814218893Sdim    Info.offset = 0;
11815218893Sdim    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11816218893Sdim    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11817218893Sdim    Info.vol = false; // volatile loads with NEON intrinsics not supported
11818218893Sdim    Info.readMem = true;
11819218893Sdim    Info.writeMem = false;
11820218893Sdim    return true;
11821218893Sdim  }
11822218893Sdim  case Intrinsic::arm_neon_vst1:
11823218893Sdim  case Intrinsic::arm_neon_vst2:
11824218893Sdim  case Intrinsic::arm_neon_vst3:
11825218893Sdim  case Intrinsic::arm_neon_vst4:
11826218893Sdim  case Intrinsic::arm_neon_vst2lane:
11827218893Sdim  case Intrinsic::arm_neon_vst3lane:
11828218893Sdim  case Intrinsic::arm_neon_vst4lane: {
11829218893Sdim    Info.opc = ISD::INTRINSIC_VOID;
11830218893Sdim    // Conservatively set memVT to the entire set of vectors stored.
11831288943Sdim    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11832218893Sdim    unsigned NumElts = 0;
11833218893Sdim    for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11834226633Sdim      Type *ArgTy = I.getArgOperand(ArgI)->getType();
11835218893Sdim      if (!ArgTy->isVectorTy())
11836218893Sdim        break;
11837296417Sdim      NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11838218893Sdim    }
11839218893Sdim    Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11840218893Sdim    Info.ptrVal = I.getArgOperand(0);
11841218893Sdim    Info.offset = 0;
11842218893Sdim    Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11843218893Sdim    Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11844218893Sdim    Info.vol = false; // volatile stores with NEON intrinsics not supported
11845218893Sdim    Info.readMem = false;
11846218893Sdim    Info.writeMem = true;
11847218893Sdim    return true;
11848218893Sdim  }
11849276479Sdim  case Intrinsic::arm_ldaex:
11850261991Sdim  case Intrinsic::arm_ldrex: {
11851288943Sdim    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11852261991Sdim    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11853261991Sdim    Info.opc = ISD::INTRINSIC_W_CHAIN;
11854261991Sdim    Info.memVT = MVT::getVT(PtrTy->getElementType());
11855261991Sdim    Info.ptrVal = I.getArgOperand(0);
11856261991Sdim    Info.offset = 0;
11857288943Sdim    Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11858261991Sdim    Info.vol = true;
11859261991Sdim    Info.readMem = true;
11860261991Sdim    Info.writeMem = false;
11861261991Sdim    return true;
11862261991Sdim  }
11863276479Sdim  case Intrinsic::arm_stlex:
11864261991Sdim  case Intrinsic::arm_strex: {
11865288943Sdim    auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11866261991Sdim    PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11867261991Sdim    Info.opc = ISD::INTRINSIC_W_CHAIN;
11868261991Sdim    Info.memVT = MVT::getVT(PtrTy->getElementType());
11869261991Sdim    Info.ptrVal = I.getArgOperand(1);
11870261991Sdim    Info.offset = 0;
11871288943Sdim    Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11872261991Sdim    Info.vol = true;
11873261991Sdim    Info.readMem = false;
11874261991Sdim    Info.writeMem = true;
11875261991Sdim    return true;
11876261991Sdim  }
11877276479Sdim  case Intrinsic::arm_stlexd:
11878223017Sdim  case Intrinsic::arm_strexd: {
11879223017Sdim    Info.opc = ISD::INTRINSIC_W_CHAIN;
11880223017Sdim    Info.memVT = MVT::i64;
11881223017Sdim    Info.ptrVal = I.getArgOperand(2);
11882223017Sdim    Info.offset = 0;
11883223017Sdim    Info.align = 8;
11884224145Sdim    Info.vol = true;
11885223017Sdim    Info.readMem = false;
11886223017Sdim    Info.writeMem = true;
11887223017Sdim    return true;
11888223017Sdim  }
11889276479Sdim  case Intrinsic::arm_ldaexd:
11890223017Sdim  case Intrinsic::arm_ldrexd: {
11891223017Sdim    Info.opc = ISD::INTRINSIC_W_CHAIN;
11892223017Sdim    Info.memVT = MVT::i64;
11893223017Sdim    Info.ptrVal = I.getArgOperand(0);
11894223017Sdim    Info.offset = 0;
11895223017Sdim    Info.align = 8;
11896224145Sdim    Info.vol = true;
11897223017Sdim    Info.readMem = true;
11898223017Sdim    Info.writeMem = false;
11899223017Sdim    return true;
11900223017Sdim  }
11901218893Sdim  default:
11902218893Sdim    break;
11903218893Sdim  }
11904218893Sdim
11905218893Sdim  return false;
11906218893Sdim}
11907276479Sdim
11908276479Sdim/// \brief Returns true if it is beneficial to convert a load of a constant
11909276479Sdim/// to just the constant itself.
11910276479Sdimbool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11911276479Sdim                                                          Type *Ty) const {
11912276479Sdim  assert(Ty->isIntegerTy());
11913276479Sdim
11914276479Sdim  unsigned Bits = Ty->getPrimitiveSizeInBits();
11915276479Sdim  if (Bits == 0 || Bits > 32)
11916276479Sdim    return false;
11917276479Sdim  return true;
11918276479Sdim}
11919276479Sdim
11920280031SdimInstruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11921280031Sdim                                        ARM_MB::MemBOpt Domain) const {
11922280031Sdim  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11923280031Sdim
11924280031Sdim  // First, if the target has no DMB, see what fallback we can use.
11925280031Sdim  if (!Subtarget->hasDataBarrier()) {
11926280031Sdim    // Some ARMv6 cpus can support data barriers with an mcr instruction.
11927280031Sdim    // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11928280031Sdim    // here.
11929280031Sdim    if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11930280031Sdim      Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11931280031Sdim      Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11932280031Sdim                        Builder.getInt32(0), Builder.getInt32(7),
11933280031Sdim                        Builder.getInt32(10), Builder.getInt32(5)};
11934280031Sdim      return Builder.CreateCall(MCR, args);
11935280031Sdim    } else {
11936280031Sdim      // Instead of using barriers, atomic accesses on these subtargets use
11937280031Sdim      // libcalls.
11938280031Sdim      llvm_unreachable("makeDMB on a target so old that it has no barriers");
11939280031Sdim    }
11940280031Sdim  } else {
11941280031Sdim    Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11942280031Sdim    // Only a full system barrier exists in the M-class architectures.
11943280031Sdim    Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11944280031Sdim    Constant *CDomain = Builder.getInt32(Domain);
11945280031Sdim    return Builder.CreateCall(DMB, CDomain);
11946276479Sdim  }
11947280031Sdim}
11948276479Sdim
11949280031Sdim// Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11950280031SdimInstruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11951280031Sdim                                         AtomicOrdering Ord, bool IsStore,
11952280031Sdim                                         bool IsLoad) const {
11953280031Sdim  if (!getInsertFencesForAtomic())
11954280031Sdim    return nullptr;
11955280031Sdim
11956280031Sdim  switch (Ord) {
11957280031Sdim  case NotAtomic:
11958280031Sdim  case Unordered:
11959280031Sdim    llvm_unreachable("Invalid fence: unordered/non-atomic");
11960280031Sdim  case Monotonic:
11961280031Sdim  case Acquire:
11962280031Sdim    return nullptr; // Nothing to do
11963280031Sdim  case SequentiallyConsistent:
11964280031Sdim    if (!IsStore)
11965280031Sdim      return nullptr; // Nothing to do
11966280031Sdim    /*FALLTHROUGH*/
11967280031Sdim  case Release:
11968280031Sdim  case AcquireRelease:
11969280031Sdim    if (Subtarget->isSwift())
11970280031Sdim      return makeDMB(Builder, ARM_MB::ISHST);
11971280031Sdim    // FIXME: add a comment with a link to documentation justifying this.
11972280031Sdim    else
11973280031Sdim      return makeDMB(Builder, ARM_MB::ISH);
11974280031Sdim  }
11975280031Sdim  llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11976276479Sdim}
11977276479Sdim
11978280031SdimInstruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11979280031Sdim                                          AtomicOrdering Ord, bool IsStore,
11980280031Sdim                                          bool IsLoad) const {
11981280031Sdim  if (!getInsertFencesForAtomic())
11982280031Sdim    return nullptr;
11983280031Sdim
11984280031Sdim  switch (Ord) {
11985280031Sdim  case NotAtomic:
11986280031Sdim  case Unordered:
11987280031Sdim    llvm_unreachable("Invalid fence: unordered/not-atomic");
11988280031Sdim  case Monotonic:
11989280031Sdim  case Release:
11990280031Sdim    return nullptr; // Nothing to do
11991280031Sdim  case Acquire:
11992280031Sdim  case AcquireRelease:
11993280031Sdim  case SequentiallyConsistent:
11994280031Sdim    return makeDMB(Builder, ARM_MB::ISH);
11995280031Sdim  }
11996280031Sdim  llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11997280031Sdim}
11998280031Sdim
11999280031Sdim// Loads and stores less than 64-bits are already atomic; ones above that
12000280031Sdim// are doomed anyway, so defer to the default libcall and blame the OS when
12001280031Sdim// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12002280031Sdim// anything for those.
12003280031Sdimbool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12004280031Sdim  unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12005280031Sdim  return (Size == 64) && !Subtarget->isMClass();
12006280031Sdim}
12007280031Sdim
12008280031Sdim// Loads and stores less than 64-bits are already atomic; ones above that
12009280031Sdim// are doomed anyway, so defer to the default libcall and blame the OS when
12010280031Sdim// things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12011280031Sdim// anything for those.
12012280031Sdim// FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12013280031Sdim// guarantee, see DDI0406C ARM architecture reference manual,
12014280031Sdim// sections A8.8.72-74 LDRD)
12015296417SdimTargetLowering::AtomicExpansionKind
12016296417SdimARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12017280031Sdim  unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12018296417Sdim  return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12019296417Sdim                                                  : AtomicExpansionKind::None;
12020280031Sdim}
12021280031Sdim
12022280031Sdim// For the real atomic operations, we have ldrex/strex up to 32 bits,
12023280031Sdim// and up to 64 bits on the non-M profiles
12024296417SdimTargetLowering::AtomicExpansionKind
12025288943SdimARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12026280031Sdim  unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12027288943Sdim  return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12028296417Sdim             ? AtomicExpansionKind::LLSC
12029296417Sdim             : AtomicExpansionKind::None;
12030280031Sdim}
12031280031Sdim
12032296417Sdimbool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12033296417Sdim    AtomicCmpXchgInst *AI) const {
12034296417Sdim  return true;
12035296417Sdim}
12036296417Sdim
12037280031Sdim// This has so far only been implemented for MachO.
12038280031Sdimbool ARMTargetLowering::useLoadStackGuardNode() const {
12039280031Sdim  return Subtarget->isTargetMachO();
12040280031Sdim}
12041280031Sdim
12042280031Sdimbool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12043280031Sdim                                                  unsigned &Cost) const {
12044280031Sdim  // If we do not have NEON, vector types are not natively supported.
12045280031Sdim  if (!Subtarget->hasNEON())
12046280031Sdim    return false;
12047280031Sdim
12048280031Sdim  // Floating point values and vector values map to the same register file.
12049296417Sdim  // Therefore, although we could do a store extract of a vector type, this is
12050280031Sdim  // better to leave at float as we have more freedom in the addressing mode for
12051280031Sdim  // those.
12052280031Sdim  if (VectorTy->isFPOrFPVectorTy())
12053280031Sdim    return false;
12054280031Sdim
12055280031Sdim  // If the index is unknown at compile time, this is very expensive to lower
12056280031Sdim  // and it is not possible to combine the store with the extract.
12057280031Sdim  if (!isa<ConstantInt>(Idx))
12058280031Sdim    return false;
12059280031Sdim
12060280031Sdim  assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12061280031Sdim  unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12062280031Sdim  // We can do a store + vector extract on any vector that fits perfectly in a D
12063280031Sdim  // or Q register.
12064280031Sdim  if (BitWidth == 64 || BitWidth == 128) {
12065280031Sdim    Cost = 0;
12066280031Sdim    return true;
12067280031Sdim  }
12068280031Sdim  return false;
12069280031Sdim}
12070280031Sdim
12071296417Sdimbool ARMTargetLowering::isCheapToSpeculateCttz() const {
12072296417Sdim  return Subtarget->hasV6T2Ops();
12073296417Sdim}
12074296417Sdim
12075296417Sdimbool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12076296417Sdim  return Subtarget->hasV6T2Ops();
12077296417Sdim}
12078296417Sdim
12079276479SdimValue *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12080276479Sdim                                         AtomicOrdering Ord) const {
12081276479Sdim  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12082276479Sdim  Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12083280031Sdim  bool IsAcquire = isAtLeastAcquire(Ord);
12084276479Sdim
12085276479Sdim  // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12086276479Sdim  // intrinsic must return {i32, i32} and we have to recombine them into a
12087276479Sdim  // single i64 here.
12088276479Sdim  if (ValTy->getPrimitiveSizeInBits() == 64) {
12089276479Sdim    Intrinsic::ID Int =
12090276479Sdim        IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12091276479Sdim    Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12092276479Sdim
12093276479Sdim    Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12094276479Sdim    Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12095276479Sdim
12096276479Sdim    Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12097276479Sdim    Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12098276479Sdim    if (!Subtarget->isLittle())
12099276479Sdim      std::swap (Lo, Hi);
12100276479Sdim    Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12101276479Sdim    Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12102276479Sdim    return Builder.CreateOr(
12103276479Sdim        Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12104276479Sdim  }
12105276479Sdim
12106276479Sdim  Type *Tys[] = { Addr->getType() };
12107276479Sdim  Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12108276479Sdim  Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12109276479Sdim
12110276479Sdim  return Builder.CreateTruncOrBitCast(
12111276479Sdim      Builder.CreateCall(Ldrex, Addr),
12112276479Sdim      cast<PointerType>(Addr->getType())->getElementType());
12113276479Sdim}
12114276479Sdim
12115296417Sdimvoid ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12116296417Sdim    IRBuilder<> &Builder) const {
12117296417Sdim  if (!Subtarget->hasV7Ops())
12118296417Sdim    return;
12119296417Sdim  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12120296417Sdim  Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12121296417Sdim}
12122296417Sdim
12123276479SdimValue *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12124276479Sdim                                               Value *Addr,
12125276479Sdim                                               AtomicOrdering Ord) const {
12126276479Sdim  Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12127280031Sdim  bool IsRelease = isAtLeastRelease(Ord);
12128276479Sdim
12129276479Sdim  // Since the intrinsics must have legal type, the i64 intrinsics take two
12130276479Sdim  // parameters: "i32, i32". We must marshal Val into the appropriate form
12131276479Sdim  // before the call.
12132276479Sdim  if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12133276479Sdim    Intrinsic::ID Int =
12134276479Sdim        IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12135276479Sdim    Function *Strex = Intrinsic::getDeclaration(M, Int);
12136276479Sdim    Type *Int32Ty = Type::getInt32Ty(M->getContext());
12137276479Sdim
12138276479Sdim    Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12139276479Sdim    Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12140276479Sdim    if (!Subtarget->isLittle())
12141276479Sdim      std::swap (Lo, Hi);
12142276479Sdim    Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12143288943Sdim    return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12144276479Sdim  }
12145276479Sdim
12146276479Sdim  Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12147276479Sdim  Type *Tys[] = { Addr->getType() };
12148276479Sdim  Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12149276479Sdim
12150288943Sdim  return Builder.CreateCall(
12151288943Sdim      Strex, {Builder.CreateZExtOrBitCast(
12152288943Sdim                  Val, Strex->getFunctionType()->getParamType(0)),
12153288943Sdim              Addr});
12154276479Sdim}
12155276479Sdim
12156288943Sdim/// \brief Lower an interleaved load into a vldN intrinsic.
12157288943Sdim///
12158288943Sdim/// E.g. Lower an interleaved load (Factor = 2):
12159288943Sdim///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12160288943Sdim///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12161288943Sdim///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12162288943Sdim///
12163288943Sdim///      Into:
12164288943Sdim///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12165288943Sdim///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12166288943Sdim///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12167288943Sdimbool ARMTargetLowering::lowerInterleavedLoad(
12168288943Sdim    LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12169288943Sdim    ArrayRef<unsigned> Indices, unsigned Factor) const {
12170288943Sdim  assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12171288943Sdim         "Invalid interleave factor");
12172288943Sdim  assert(!Shuffles.empty() && "Empty shufflevector input");
12173288943Sdim  assert(Shuffles.size() == Indices.size() &&
12174288943Sdim         "Unmatched number of shufflevectors and indices");
12175288943Sdim
12176288943Sdim  VectorType *VecTy = Shuffles[0]->getType();
12177288943Sdim  Type *EltTy = VecTy->getVectorElementType();
12178288943Sdim
12179288943Sdim  const DataLayout &DL = LI->getModule()->getDataLayout();
12180296417Sdim  unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12181296417Sdim  bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12182288943Sdim
12183296417Sdim  // Skip if we do not have NEON and skip illegal vector types and vector types
12184296417Sdim  // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12185296417Sdim  if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12186288943Sdim    return false;
12187288943Sdim
12188288943Sdim  // A pointer vector can not be the return type of the ldN intrinsics. Need to
12189288943Sdim  // load integer vectors first and then convert to pointer vectors.
12190288943Sdim  if (EltTy->isPointerTy())
12191288943Sdim    VecTy =
12192288943Sdim        VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12193288943Sdim
12194288943Sdim  static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12195288943Sdim                                            Intrinsic::arm_neon_vld3,
12196288943Sdim                                            Intrinsic::arm_neon_vld4};
12197288943Sdim
12198288943Sdim  IRBuilder<> Builder(LI);
12199288943Sdim  SmallVector<Value *, 2> Ops;
12200288943Sdim
12201288943Sdim  Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12202288943Sdim  Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12203288943Sdim  Ops.push_back(Builder.getInt32(LI->getAlignment()));
12204288943Sdim
12205296417Sdim  Type *Tys[] = { VecTy, Int8Ptr };
12206296417Sdim  Function *VldnFunc =
12207296417Sdim      Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12208288943Sdim  CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12209288943Sdim
12210288943Sdim  // Replace uses of each shufflevector with the corresponding vector loaded
12211288943Sdim  // by ldN.
12212288943Sdim  for (unsigned i = 0; i < Shuffles.size(); i++) {
12213288943Sdim    ShuffleVectorInst *SV = Shuffles[i];
12214288943Sdim    unsigned Index = Indices[i];
12215288943Sdim
12216288943Sdim    Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12217288943Sdim
12218288943Sdim    // Convert the integer vector to pointer vector if the element is pointer.
12219288943Sdim    if (EltTy->isPointerTy())
12220288943Sdim      SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12221288943Sdim
12222288943Sdim    SV->replaceAllUsesWith(SubVec);
12223288943Sdim  }
12224288943Sdim
12225288943Sdim  return true;
12226288943Sdim}
12227288943Sdim
12228288943Sdim/// \brief Get a mask consisting of sequential integers starting from \p Start.
12229288943Sdim///
12230288943Sdim/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12231288943Sdimstatic Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12232288943Sdim                                   unsigned NumElts) {
12233288943Sdim  SmallVector<Constant *, 16> Mask;
12234288943Sdim  for (unsigned i = 0; i < NumElts; i++)
12235288943Sdim    Mask.push_back(Builder.getInt32(Start + i));
12236288943Sdim
12237288943Sdim  return ConstantVector::get(Mask);
12238288943Sdim}
12239288943Sdim
12240288943Sdim/// \brief Lower an interleaved store into a vstN intrinsic.
12241288943Sdim///
12242288943Sdim/// E.g. Lower an interleaved store (Factor = 3):
12243288943Sdim///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12244288943Sdim///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12245288943Sdim///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12246288943Sdim///
12247288943Sdim///      Into:
12248288943Sdim///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12249288943Sdim///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12250288943Sdim///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12251288943Sdim///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12252288943Sdim///
12253288943Sdim/// Note that the new shufflevectors will be removed and we'll only generate one
12254288943Sdim/// vst3 instruction in CodeGen.
12255288943Sdimbool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12256288943Sdim                                              ShuffleVectorInst *SVI,
12257288943Sdim                                              unsigned Factor) const {
12258288943Sdim  assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12259288943Sdim         "Invalid interleave factor");
12260288943Sdim
12261288943Sdim  VectorType *VecTy = SVI->getType();
12262288943Sdim  assert(VecTy->getVectorNumElements() % Factor == 0 &&
12263288943Sdim         "Invalid interleaved store");
12264288943Sdim
12265288943Sdim  unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12266288943Sdim  Type *EltTy = VecTy->getVectorElementType();
12267288943Sdim  VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12268288943Sdim
12269288943Sdim  const DataLayout &DL = SI->getModule()->getDataLayout();
12270296417Sdim  unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12271296417Sdim  bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12272288943Sdim
12273296417Sdim  // Skip if we do not have NEON and skip illegal vector types and vector types
12274296417Sdim  // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12275296417Sdim  if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12276296417Sdim      EltIs64Bits)
12277288943Sdim    return false;
12278288943Sdim
12279288943Sdim  Value *Op0 = SVI->getOperand(0);
12280288943Sdim  Value *Op1 = SVI->getOperand(1);
12281288943Sdim  IRBuilder<> Builder(SI);
12282288943Sdim
12283288943Sdim  // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12284288943Sdim  // vectors to integer vectors.
12285288943Sdim  if (EltTy->isPointerTy()) {
12286288943Sdim    Type *IntTy = DL.getIntPtrType(EltTy);
12287288943Sdim
12288288943Sdim    // Convert to the corresponding integer vector.
12289288943Sdim    Type *IntVecTy =
12290288943Sdim        VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12291288943Sdim    Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12292288943Sdim    Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12293288943Sdim
12294288943Sdim    SubVecTy = VectorType::get(IntTy, NumSubElts);
12295288943Sdim  }
12296288943Sdim
12297296417Sdim  static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12298296417Sdim                                             Intrinsic::arm_neon_vst3,
12299296417Sdim                                             Intrinsic::arm_neon_vst4};
12300288943Sdim  SmallVector<Value *, 6> Ops;
12301288943Sdim
12302288943Sdim  Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12303288943Sdim  Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12304288943Sdim
12305296417Sdim  Type *Tys[] = { Int8Ptr, SubVecTy };
12306296417Sdim  Function *VstNFunc = Intrinsic::getDeclaration(
12307296417Sdim      SI->getModule(), StoreInts[Factor - 2], Tys);
12308296417Sdim
12309288943Sdim  // Split the shufflevector operands into sub vectors for the new vstN call.
12310288943Sdim  for (unsigned i = 0; i < Factor; i++)
12311288943Sdim    Ops.push_back(Builder.CreateShuffleVector(
12312288943Sdim        Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12313288943Sdim
12314288943Sdim  Ops.push_back(Builder.getInt32(SI->getAlignment()));
12315288943Sdim  Builder.CreateCall(VstNFunc, Ops);
12316288943Sdim  return true;
12317288943Sdim}
12318288943Sdim
12319276479Sdimenum HABaseType {
12320276479Sdim  HA_UNKNOWN = 0,
12321276479Sdim  HA_FLOAT,
12322276479Sdim  HA_DOUBLE,
12323276479Sdim  HA_VECT64,
12324276479Sdim  HA_VECT128
12325276479Sdim};
12326276479Sdim
12327276479Sdimstatic bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12328276479Sdim                                   uint64_t &Members) {
12329296417Sdim  if (auto *ST = dyn_cast<StructType>(Ty)) {
12330276479Sdim    for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12331276479Sdim      uint64_t SubMembers = 0;
12332276479Sdim      if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12333276479Sdim        return false;
12334276479Sdim      Members += SubMembers;
12335276479Sdim    }
12336296417Sdim  } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12337276479Sdim    uint64_t SubMembers = 0;
12338276479Sdim    if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12339276479Sdim      return false;
12340276479Sdim    Members += SubMembers * AT->getNumElements();
12341276479Sdim  } else if (Ty->isFloatTy()) {
12342276479Sdim    if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12343276479Sdim      return false;
12344276479Sdim    Members = 1;
12345276479Sdim    Base = HA_FLOAT;
12346276479Sdim  } else if (Ty->isDoubleTy()) {
12347276479Sdim    if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12348276479Sdim      return false;
12349276479Sdim    Members = 1;
12350276479Sdim    Base = HA_DOUBLE;
12351296417Sdim  } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12352276479Sdim    Members = 1;
12353276479Sdim    switch (Base) {
12354276479Sdim    case HA_FLOAT:
12355276479Sdim    case HA_DOUBLE:
12356276479Sdim      return false;
12357276479Sdim    case HA_VECT64:
12358276479Sdim      return VT->getBitWidth() == 64;
12359276479Sdim    case HA_VECT128:
12360276479Sdim      return VT->getBitWidth() == 128;
12361276479Sdim    case HA_UNKNOWN:
12362276479Sdim      switch (VT->getBitWidth()) {
12363276479Sdim      case 64:
12364276479Sdim        Base = HA_VECT64;
12365276479Sdim        return true;
12366276479Sdim      case 128:
12367276479Sdim        Base = HA_VECT128;
12368276479Sdim        return true;
12369276479Sdim      default:
12370276479Sdim        return false;
12371276479Sdim      }
12372276479Sdim    }
12373276479Sdim  }
12374276479Sdim
12375276479Sdim  return (Members > 0 && Members <= 4);
12376276479Sdim}
12377276479Sdim
12378280400Sdim/// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12379280400Sdim/// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12380280400Sdim/// passing according to AAPCS rules.
12381276479Sdimbool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12382276479Sdim    Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12383276479Sdim  if (getEffectiveCallingConv(CallConv, isVarArg) !=
12384276479Sdim      CallingConv::ARM_AAPCS_VFP)
12385276479Sdim    return false;
12386276479Sdim
12387276479Sdim  HABaseType Base = HA_UNKNOWN;
12388276479Sdim  uint64_t Members = 0;
12389280400Sdim  bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12390280400Sdim  DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12391280400Sdim
12392280400Sdim  bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12393280400Sdim  return IsHA || IsIntArray;
12394276479Sdim}
12395296417Sdim
12396296417Sdimunsigned ARMTargetLowering::getExceptionPointerRegister(
12397296417Sdim    const Constant *PersonalityFn) const {
12398296417Sdim  // Platforms which do not use SjLj EH may return values in these registers
12399296417Sdim  // via the personality function.
12400296417Sdim  return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12401296417Sdim}
12402296417Sdim
12403296417Sdimunsigned ARMTargetLowering::getExceptionSelectorRegister(
12404296417Sdim    const Constant *PersonalityFn) const {
12405296417Sdim  // Platforms which do not use SjLj EH may return values in these registers
12406296417Sdim  // via the personality function.
12407296417Sdim  return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12408296417Sdim}
12409296417Sdim
12410296417Sdimvoid ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12411296417Sdim  // Update IsSplitCSR in ARMFunctionInfo.
12412296417Sdim  ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12413296417Sdim  AFI->setIsSplitCSR(true);
12414296417Sdim}
12415296417Sdim
12416296417Sdimvoid ARMTargetLowering::insertCopiesSplitCSR(
12417296417Sdim    MachineBasicBlock *Entry,
12418296417Sdim    const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12419296417Sdim  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12420296417Sdim  const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12421296417Sdim  if (!IStart)
12422296417Sdim    return;
12423296417Sdim
12424296417Sdim  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12425296417Sdim  MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12426296417Sdim  MachineBasicBlock::iterator MBBI = Entry->begin();
12427296417Sdim  for (const MCPhysReg *I = IStart; *I; ++I) {
12428296417Sdim    const TargetRegisterClass *RC = nullptr;
12429296417Sdim    if (ARM::GPRRegClass.contains(*I))
12430296417Sdim      RC = &ARM::GPRRegClass;
12431296417Sdim    else if (ARM::DPRRegClass.contains(*I))
12432296417Sdim      RC = &ARM::DPRRegClass;
12433296417Sdim    else
12434296417Sdim      llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12435296417Sdim
12436296417Sdim    unsigned NewVR = MRI->createVirtualRegister(RC);
12437296417Sdim    // Create copy from CSR to a virtual register.
12438296417Sdim    // FIXME: this currently does not emit CFI pseudo-instructions, it works
12439296417Sdim    // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12440296417Sdim    // nounwind. If we want to generalize this later, we may need to emit
12441296417Sdim    // CFI pseudo-instructions.
12442296417Sdim    assert(Entry->getParent()->getFunction()->hasFnAttribute(
12443296417Sdim               Attribute::NoUnwind) &&
12444296417Sdim           "Function should be nounwind in insertCopiesSplitCSR!");
12445296417Sdim    Entry->addLiveIn(*I);
12446296417Sdim    BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12447296417Sdim        .addReg(*I);
12448296417Sdim
12449296417Sdim    // Insert the copy-back instructions right before the terminator.
12450296417Sdim    for (auto *Exit : Exits)
12451296417Sdim      BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12452296417Sdim              TII->get(TargetOpcode::COPY), *I)
12453296417Sdim          .addReg(NewVR);
12454296417Sdim  }
12455296417Sdim}
12456