]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp
Upgrade our copies of clang, llvm, lldb, compiler-rt and libc++ to 3.9.0
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 // Disabled for causing self-hosting failures once returned-attribute inference
69 // was enabled.
70 static cl::opt<bool>
71 EnableThisRetForwarding("arm-this-return-forwarding", cl::Hidden,
72                         cl::desc("Directly forward this return"),
73                         cl::init(false));
74
75 namespace {
76   class ARMCCState : public CCState {
77   public:
78     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
79                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
80                ParmContext PC)
81         : CCState(CC, isVarArg, MF, locs, C) {
82       assert(((PC == Call) || (PC == Prologue)) &&
83              "ARMCCState users must specify whether their context is call"
84              "or prologue generation.");
85       CallOrPrologue = PC;
86     }
87   };
88 }
89
90 // The APCS parameter registers.
91 static const MCPhysReg GPRArgRegs[] = {
92   ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 };
94
95 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
96                                        MVT PromotedBitwiseVT) {
97   if (VT != PromotedLdStVT) {
98     setOperationAction(ISD::LOAD, VT, Promote);
99     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
100
101     setOperationAction(ISD::STORE, VT, Promote);
102     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103   }
104
105   MVT ElemTy = VT.getVectorElementType();
106   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
107     setOperationAction(ISD::SETCC, VT, Custom);
108   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
109   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
110   if (ElemTy == MVT::i32) {
111     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
112     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
113     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
114     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
115   } else {
116     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
117     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
118     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
119     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
120   }
121   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
122   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
123   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
124   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
125   setOperationAction(ISD::SELECT,            VT, Expand);
126   setOperationAction(ISD::SELECT_CC,         VT, Expand);
127   setOperationAction(ISD::VSELECT,           VT, Expand);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
129   if (VT.isInteger()) {
130     setOperationAction(ISD::SHL, VT, Custom);
131     setOperationAction(ISD::SRA, VT, Custom);
132     setOperationAction(ISD::SRL, VT, Custom);
133   }
134
135   // Promote all bit-wise operations.
136   if (VT.isInteger() && VT != PromotedBitwiseVT) {
137     setOperationAction(ISD::AND, VT, Promote);
138     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
139     setOperationAction(ISD::OR,  VT, Promote);
140     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
141     setOperationAction(ISD::XOR, VT, Promote);
142     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143   }
144
145   // Neon does not support vector divide/remainder operations.
146   setOperationAction(ISD::SDIV, VT, Expand);
147   setOperationAction(ISD::UDIV, VT, Expand);
148   setOperationAction(ISD::FDIV, VT, Expand);
149   setOperationAction(ISD::SREM, VT, Expand);
150   setOperationAction(ISD::UREM, VT, Expand);
151   setOperationAction(ISD::FREM, VT, Expand);
152
153   if (!VT.isFloatingPoint() &&
154       VT != MVT::v2i64 && VT != MVT::v1i64)
155     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
156       setOperationAction(Opcode, VT, Legal);
157 }
158
159 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
160   addRegisterClass(VT, &ARM::DPRRegClass);
161   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
162 }
163
164 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
165   addRegisterClass(VT, &ARM::DPairRegClass);
166   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
167 }
168
169 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
170                                      const ARMSubtarget &STI)
171     : TargetLowering(TM), Subtarget(&STI) {
172   RegInfo = Subtarget->getRegisterInfo();
173   Itins = Subtarget->getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetMachO()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
180         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
181       static const struct {
182         const RTLIB::Libcall Op;
183         const char * const Name;
184         const ISD::CondCode Cond;
185       } LibraryCalls[] = {
186         // Single-precision floating-point arithmetic.
187         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
190         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
191
192         // Double-precision floating-point arithmetic.
193         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
194         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
195         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
196         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
197
198         // Single-precision comparisons.
199         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
200         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
201         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
202         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
203         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
204         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
205         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
206         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
207
208         // Double-precision comparisons.
209         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
210         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
211         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
212         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
213         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
214         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
215         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
216         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
217
218         // Floating-point to integer conversions.
219         // i64 conversions are done via library routines even when generating VFP
220         // instructions, so use the same ones.
221         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
222         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
223         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
224         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
225
226         // Conversions between floating types.
227         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
228         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
229
230         // Integer to floating-point conversions.
231         // i64 conversions are done via library routines even when generating VFP
232         // instructions, so use the same ones.
233         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
234         // e.g., __floatunsidf vs. __floatunssidfvfp.
235         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
236         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
237         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
238         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
239       };
240
241       for (const auto &LC : LibraryCalls) {
242         setLibcallName(LC.Op, LC.Name);
243         if (LC.Cond != ISD::SETCC_INVALID)
244           setCmpLibcallCC(LC.Op, LC.Cond);
245       }
246     }
247
248     // Set the correct calling convention for ARMv7k WatchOS. It's just
249     // AAPCS_VFP for functions as simple as libcalls.
250     if (Subtarget->isTargetWatchABI()) {
251       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
252         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
253     }
254   }
255
256   // These libcalls are not available in 32-bit.
257   setLibcallName(RTLIB::SHL_I128, nullptr);
258   setLibcallName(RTLIB::SRL_I128, nullptr);
259   setLibcallName(RTLIB::SRA_I128, nullptr);
260
261   // RTLIB
262   if (Subtarget->isAAPCS_ABI() &&
263       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
264        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
265     static const struct {
266       const RTLIB::Libcall Op;
267       const char * const Name;
268       const CallingConv::ID CC;
269       const ISD::CondCode Cond;
270     } LibraryCalls[] = {
271       // Double-precision floating-point arithmetic helper functions
272       // RTABI chapter 4.1.2, Table 2
273       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
274       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
275       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277
278       // Double-precision floating-point comparison helper functions
279       // RTABI chapter 4.1.2, Table 3
280       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
282       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
284       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
288
289       // Single-precision floating-point arithmetic helper functions
290       // RTABI chapter 4.1.2, Table 4
291       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
293       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295
296       // Single-precision floating-point comparison helper functions
297       // RTABI chapter 4.1.2, Table 5
298       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
300       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
301       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
302       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
303       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
304       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
305       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
306
307       // Floating-point to integer conversions.
308       // RTABI chapter 4.1.2, Table 6
309       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317
318       // Conversions between floating types.
319       // RTABI chapter 4.1.2, Table 7
320       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Integer to floating-point conversions.
325       // RTABI chapter 4.1.2, Table 8
326       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334
335       // Long long helper functions
336       // RTABI chapter 4.2, Table 9
337       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Integer division functions
343       // RTABI chapter 4.3.1
344       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352     };
353
354     for (const auto &LC : LibraryCalls) {
355       setLibcallName(LC.Op, LC.Name);
356       setLibcallCallingConv(LC.Op, LC.CC);
357       if (LC.Cond != ISD::SETCC_INVALID)
358         setCmpLibcallCC(LC.Op, LC.Cond);
359     }
360
361     // EABI dependent RTLIB
362     if (TM.Options.EABIVersion == EABI::EABI4 ||
363         TM.Options.EABIVersion == EABI::EABI5) {
364       static const struct {
365         const RTLIB::Libcall Op;
366         const char *const Name;
367         const CallingConv::ID CC;
368         const ISD::CondCode Cond;
369       } MemOpsLibraryCalls[] = {
370         // Memory operations
371         // RTABI chapter 4.3.4
372         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375       };
376
377       for (const auto &LC : MemOpsLibraryCalls) {
378         setLibcallName(LC.Op, LC.Name);
379         setLibcallCallingConv(LC.Op, LC.CC);
380         if (LC.Cond != ISD::SETCC_INVALID)
381           setCmpLibcallCC(LC.Op, LC.Cond);
382       }
383     }
384   }
385
386   if (Subtarget->isTargetWindows()) {
387     static const struct {
388       const RTLIB::Libcall Op;
389       const char * const Name;
390       const CallingConv::ID CC;
391     } LibraryCalls[] = {
392       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
393       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
394       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
395       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
396       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
397       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
398       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
399       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
400     };
401
402     for (const auto &LC : LibraryCalls) {
403       setLibcallName(LC.Op, LC.Name);
404       setLibcallCallingConv(LC.Op, LC.CC);
405     }
406   }
407
408   // Use divmod compiler-rt calls for iOS 5.0 and later.
409   if (Subtarget->isTargetWatchOS() ||
410       (Subtarget->isTargetIOS() &&
411        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
412     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
413     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
414   }
415
416   // The half <-> float conversion functions are always soft-float on
417   // non-watchos platforms, but are needed for some targets which use a
418   // hard-float calling convention by default.
419   if (!Subtarget->isTargetWatchABI()) {
420     if (Subtarget->isAAPCS_ABI()) {
421       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
422       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
423       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
424     } else {
425       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
426       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
427       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
428     }
429   }
430
431   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
432   // a __gnu_ prefix (which is the default).
433   if (Subtarget->isTargetAEABI()) {
434     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
435     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
436     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
437   }
438
439   if (Subtarget->isThumb1Only())
440     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
441   else
442     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
443   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
444       !Subtarget->isThumb1Only()) {
445     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
446     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
447   }
448
449   for (MVT VT : MVT::vector_valuetypes()) {
450     for (MVT InnerVT : MVT::vector_valuetypes()) {
451       setTruncStoreAction(VT, InnerVT, Expand);
452       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
453       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
454       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
455     }
456
457     setOperationAction(ISD::MULHS, VT, Expand);
458     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
459     setOperationAction(ISD::MULHU, VT, Expand);
460     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
461
462     setOperationAction(ISD::BSWAP, VT, Expand);
463   }
464
465   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
466   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
467
468   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
469   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
470
471   if (Subtarget->hasNEON()) {
472     addDRTypeForNEON(MVT::v2f32);
473     addDRTypeForNEON(MVT::v8i8);
474     addDRTypeForNEON(MVT::v4i16);
475     addDRTypeForNEON(MVT::v2i32);
476     addDRTypeForNEON(MVT::v1i64);
477
478     addQRTypeForNEON(MVT::v4f32);
479     addQRTypeForNEON(MVT::v2f64);
480     addQRTypeForNEON(MVT::v16i8);
481     addQRTypeForNEON(MVT::v8i16);
482     addQRTypeForNEON(MVT::v4i32);
483     addQRTypeForNEON(MVT::v2i64);
484
485     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
486     // neither Neon nor VFP support any arithmetic operations on it.
487     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
488     // supported for v4f32.
489     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
490     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
491     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
492     // FIXME: Code duplication: FDIV and FREM are expanded always, see
493     // ARMTargetLowering::addTypeForNEON method for details.
494     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
495     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
496     // FIXME: Create unittest.
497     // In another words, find a way when "copysign" appears in DAG with vector
498     // operands.
499     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
500     // FIXME: Code duplication: SETCC has custom operation action, see
501     // ARMTargetLowering::addTypeForNEON method for details.
502     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
503     // FIXME: Create unittest for FNEG and for FABS.
504     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
505     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
506     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
516     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
517     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
518     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
519     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
520     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
521     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
522     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
523
524     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
525     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
526     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
527     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
528     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
529     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
530     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
531     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
532     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
533     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
534     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
535     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
536     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
537     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
538     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
539
540     // Mark v2f32 intrinsics.
541     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
542     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
543     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
544     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
545     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
546     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
547     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
548     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
549     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
550     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
551     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
552     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
553     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
554     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
555     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
556
557     // Neon does not support some operations on v1i64 and v2i64 types.
558     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
559     // Custom handling for some quad-vector types to detect VMULL.
560     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
561     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
562     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
563     // Custom handling for some vector types to avoid expensive expansions
564     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
565     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
566     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
567     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
568     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
569     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
570     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
571     // a destination type that is wider than the source, and nor does
572     // it have a FP_TO_[SU]INT instruction with a narrower destination than
573     // source.
574     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
575     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
576     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
577     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
578
579     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
580     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
581
582     // NEON does not have single instruction CTPOP for vectors with element
583     // types wider than 8-bits.  However, custom lowering can leverage the
584     // v8i8/v16i8 vcnt instruction.
585     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
586     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
587     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
588     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
589     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
590     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
591
592     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
593     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
594
595     // NEON does not have single instruction CTTZ for vectors.
596     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
597     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
598     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
599     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
600
601     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
602     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
603     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
604     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
605
606     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
607     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
608     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
609     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
610
611     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
612     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
613     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
614     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
615
616     // NEON only has FMA instructions as of VFP4.
617     if (!Subtarget->hasVFP4()) {
618       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
619       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
620     }
621
622     setTargetDAGCombine(ISD::INTRINSIC_VOID);
623     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
624     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
625     setTargetDAGCombine(ISD::SHL);
626     setTargetDAGCombine(ISD::SRL);
627     setTargetDAGCombine(ISD::SRA);
628     setTargetDAGCombine(ISD::SIGN_EXTEND);
629     setTargetDAGCombine(ISD::ZERO_EXTEND);
630     setTargetDAGCombine(ISD::ANY_EXTEND);
631     setTargetDAGCombine(ISD::BUILD_VECTOR);
632     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
633     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
634     setTargetDAGCombine(ISD::STORE);
635     setTargetDAGCombine(ISD::FP_TO_SINT);
636     setTargetDAGCombine(ISD::FP_TO_UINT);
637     setTargetDAGCombine(ISD::FDIV);
638     setTargetDAGCombine(ISD::LOAD);
639
640     // It is legal to extload from v4i8 to v4i16 or v4i32.
641     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
642                    MVT::v2i32}) {
643       for (MVT VT : MVT::integer_vector_valuetypes()) {
644         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
645         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
646         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
647       }
648     }
649   }
650
651   // ARM and Thumb2 support UMLAL/SMLAL.
652   if (!Subtarget->isThumb1Only())
653     setTargetDAGCombine(ISD::ADDC);
654
655   if (Subtarget->isFPOnlySP()) {
656     // When targeting a floating-point unit with only single-precision
657     // operations, f64 is legal for the few double-precision instructions which
658     // are present However, no double-precision operations other than moves,
659     // loads and stores are provided by the hardware.
660     setOperationAction(ISD::FADD,       MVT::f64, Expand);
661     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
662     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
663     setOperationAction(ISD::FMA,        MVT::f64, Expand);
664     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
665     setOperationAction(ISD::FREM,       MVT::f64, Expand);
666     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
667     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
668     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
669     setOperationAction(ISD::FABS,       MVT::f64, Expand);
670     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
671     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
672     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
673     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
674     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
675     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
676     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
677     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
678     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
679     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
680     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
681     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
682     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
683     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
684     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
685     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
686     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
687     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
688     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
689     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
690     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
691     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
692     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
693   }
694
695   computeRegisterProperties(Subtarget->getRegisterInfo());
696
697   // ARM does not have floating-point extending loads.
698   for (MVT VT : MVT::fp_valuetypes()) {
699     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
700     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
701   }
702
703   // ... or truncating stores
704   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
705   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
706   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
707
708   // ARM does not have i1 sign extending load.
709   for (MVT VT : MVT::integer_valuetypes())
710     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
711
712   // ARM supports all 4 flavors of integer indexed load / store.
713   if (!Subtarget->isThumb1Only()) {
714     for (unsigned im = (unsigned)ISD::PRE_INC;
715          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
716       setIndexedLoadAction(im,  MVT::i1,  Legal);
717       setIndexedLoadAction(im,  MVT::i8,  Legal);
718       setIndexedLoadAction(im,  MVT::i16, Legal);
719       setIndexedLoadAction(im,  MVT::i32, Legal);
720       setIndexedStoreAction(im, MVT::i1,  Legal);
721       setIndexedStoreAction(im, MVT::i8,  Legal);
722       setIndexedStoreAction(im, MVT::i16, Legal);
723       setIndexedStoreAction(im, MVT::i32, Legal);
724     }
725   } else {
726     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
727     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
728     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
729   }
730
731   setOperationAction(ISD::SADDO, MVT::i32, Custom);
732   setOperationAction(ISD::UADDO, MVT::i32, Custom);
733   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
734   setOperationAction(ISD::USUBO, MVT::i32, Custom);
735
736   // i64 operation support.
737   setOperationAction(ISD::MUL,     MVT::i64, Expand);
738   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
739   if (Subtarget->isThumb1Only()) {
740     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
741     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
742   }
743   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
744       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
745     setOperationAction(ISD::MULHS, MVT::i32, Expand);
746
747   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
748   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
749   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
750   setOperationAction(ISD::SRL,       MVT::i64, Custom);
751   setOperationAction(ISD::SRA,       MVT::i64, Custom);
752
753   if (!Subtarget->isThumb1Only()) {
754     // FIXME: We should do this for Thumb1 as well.
755     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
756     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
757     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
758     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
759   }
760
761   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
762     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
763
764   // ARM does not have ROTL.
765   setOperationAction(ISD::ROTL, MVT::i32, Expand);
766   for (MVT VT : MVT::vector_valuetypes()) {
767     setOperationAction(ISD::ROTL, VT, Expand);
768     setOperationAction(ISD::ROTR, VT, Expand);
769   }
770   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
771   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
772   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
773     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
774
775   // @llvm.readcyclecounter requires the Performance Monitors extension.
776   // Default to the 0 expansion on unsupported platforms.
777   // FIXME: Technically there are older ARM CPUs that have
778   // implementation-specific ways of obtaining this information.
779   if (Subtarget->hasPerfMon())
780     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
781
782   // Only ARMv6 has BSWAP.
783   if (!Subtarget->hasV6Ops())
784     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
785
786   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
787                                         : Subtarget->hasDivideInARMMode();
788   if (!hasDivide) {
789     // These are expanded into libcalls if the cpu doesn't have HW divider.
790     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
791     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
792   }
793
794   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
795     setOperationAction(ISD::SDIV, MVT::i32, Custom);
796     setOperationAction(ISD::UDIV, MVT::i32, Custom);
797
798     setOperationAction(ISD::SDIV, MVT::i64, Custom);
799     setOperationAction(ISD::UDIV, MVT::i64, Custom);
800   }
801
802   setOperationAction(ISD::SREM,  MVT::i32, Expand);
803   setOperationAction(ISD::UREM,  MVT::i32, Expand);
804   // Register based DivRem for AEABI (RTABI 4.2)
805   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
806       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) {
807     setOperationAction(ISD::SREM, MVT::i64, Custom);
808     setOperationAction(ISD::UREM, MVT::i64, Custom);
809     HasStandaloneRem = false;
810
811     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
812     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
813     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
814     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
815     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
816     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
817     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
818     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
819
820     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
821     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
822     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
823     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
824     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
825     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
826     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
827     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
828
829     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
830     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
831     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
832     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
833   } else {
834     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
835     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
836   }
837
838   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
839   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
840   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
841   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
842
843   setOperationAction(ISD::TRAP, MVT::Other, Legal);
844
845   // Use the default implementation.
846   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
847   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
848   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
849   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
850   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
851   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
852
853   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
854     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
855   else
856     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
857
858   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
859   // the default expansion.
860   InsertFencesForAtomic = false;
861   if (Subtarget->hasAnyDataBarrier() &&
862       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
863     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
864     // to ldrex/strex loops already.
865     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
866     if (!Subtarget->isThumb() || !Subtarget->isMClass())
867       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
868
869     // On v8, we have particularly efficient implementations of atomic fences
870     // if they can be combined with nearby atomic loads and stores.
871     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
872       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
873       InsertFencesForAtomic = true;
874     }
875   } else {
876     // If there's anything we can use as a barrier, go through custom lowering
877     // for ATOMIC_FENCE.
878     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
879                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
880
881     // Set them all for expansion, which will force libcalls.
882     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
883     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
884     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
885     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
886     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
887     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
888     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
889     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
890     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
891     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
892     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
893     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
894     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
895     // Unordered/Monotonic case.
896     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
897     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
898   }
899
900   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
901
902   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
903   if (!Subtarget->hasV6Ops()) {
904     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
905     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
906   }
907   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
908
909   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
910       !Subtarget->isThumb1Only()) {
911     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
912     // iff target supports vfp2.
913     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
914     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
915   }
916
917   // We want to custom lower some of our intrinsics.
918   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
919   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
920   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
921   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
922   if (Subtarget->useSjLjEH())
923     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
924
925   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
926   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
927   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
928   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
929   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
930   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
931   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
932   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
933   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
934
935   // Thumb-1 cannot currently select ARMISD::SUBE.
936   if (!Subtarget->isThumb1Only())
937     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
938
939   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
940   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
941   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
942   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
943   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
944
945   // We don't support sin/cos/fmod/copysign/pow
946   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
947   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
948   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
949   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
950   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
951   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
952   setOperationAction(ISD::FREM,      MVT::f64, Expand);
953   setOperationAction(ISD::FREM,      MVT::f32, Expand);
954   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
955       !Subtarget->isThumb1Only()) {
956     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
957     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
958   }
959   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
960   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
961
962   if (!Subtarget->hasVFP4()) {
963     setOperationAction(ISD::FMA, MVT::f64, Expand);
964     setOperationAction(ISD::FMA, MVT::f32, Expand);
965   }
966
967   // Various VFP goodness
968   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
969     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
970     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
971       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
972       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
973     }
974
975     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
976     if (!Subtarget->hasFP16()) {
977       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
978       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
979     }
980   }
981
982   // Combine sin / cos into one node or libcall if possible.
983   if (Subtarget->hasSinCos()) {
984     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
985     setLibcallName(RTLIB::SINCOS_F64, "sincos");
986     if (Subtarget->isTargetWatchABI()) {
987       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
988       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
989     }
990     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
991       // For iOS, we don't want to the normal expansion of a libcall to
992       // sincos. We want to issue a libcall to __sincos_stret.
993       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
994       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
995     }
996   }
997
998   // FP-ARMv8 implements a lot of rounding-like FP operations.
999   if (Subtarget->hasFPARMv8()) {
1000     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1001     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1002     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1003     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1004     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1005     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1006     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1007     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1008     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1009     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1010     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1011     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1012
1013     if (!Subtarget->isFPOnlySP()) {
1014       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1015       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1016       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1017       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1018       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1019       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1020       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1021       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1022     }
1023   }
1024
1025   if (Subtarget->hasNEON()) {
1026     // vmin and vmax aren't available in a scalar form, so we use
1027     // a NEON instruction with an undef lane instead.
1028     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1029     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1030     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1031     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1032     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1033     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1034   }
1035
1036   // We have target-specific dag combine patterns for the following nodes:
1037   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1038   setTargetDAGCombine(ISD::ADD);
1039   setTargetDAGCombine(ISD::SUB);
1040   setTargetDAGCombine(ISD::MUL);
1041   setTargetDAGCombine(ISD::AND);
1042   setTargetDAGCombine(ISD::OR);
1043   setTargetDAGCombine(ISD::XOR);
1044
1045   if (Subtarget->hasV6Ops())
1046     setTargetDAGCombine(ISD::SRL);
1047
1048   setStackPointerRegisterToSaveRestore(ARM::SP);
1049
1050   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1051       !Subtarget->hasVFP2())
1052     setSchedulingPreference(Sched::RegPressure);
1053   else
1054     setSchedulingPreference(Sched::Hybrid);
1055
1056   //// temporary - rewrite interface to use type
1057   MaxStoresPerMemset = 8;
1058   MaxStoresPerMemsetOptSize = 4;
1059   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1060   MaxStoresPerMemcpyOptSize = 2;
1061   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1062   MaxStoresPerMemmoveOptSize = 2;
1063
1064   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1065   // are at least 4 bytes aligned.
1066   setMinStackArgumentAlignment(4);
1067
1068   // Prefer likely predicted branches to selects on out-of-order cores.
1069   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1070
1071   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1072 }
1073
1074 bool ARMTargetLowering::useSoftFloat() const {
1075   return Subtarget->useSoftFloat();
1076 }
1077
1078 // FIXME: It might make sense to define the representative register class as the
1079 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1080 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1081 // SPR's representative would be DPR_VFP2. This should work well if register
1082 // pressure tracking were modified such that a register use would increment the
1083 // pressure of the register class's representative and all of it's super
1084 // classes' representatives transitively. We have not implemented this because
1085 // of the difficulty prior to coalescing of modeling operand register classes
1086 // due to the common occurrence of cross class copies and subregister insertions
1087 // and extractions.
1088 std::pair<const TargetRegisterClass *, uint8_t>
1089 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1090                                            MVT VT) const {
1091   const TargetRegisterClass *RRC = nullptr;
1092   uint8_t Cost = 1;
1093   switch (VT.SimpleTy) {
1094   default:
1095     return TargetLowering::findRepresentativeClass(TRI, VT);
1096   // Use DPR as representative register class for all floating point
1097   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1098   // the cost is 1 for both f32 and f64.
1099   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1100   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1101     RRC = &ARM::DPRRegClass;
1102     // When NEON is used for SP, only half of the register file is available
1103     // because operations that define both SP and DP results will be constrained
1104     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1105     // coalescing by double-counting the SP regs. See the FIXME above.
1106     if (Subtarget->useNEONForSinglePrecisionFP())
1107       Cost = 2;
1108     break;
1109   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1110   case MVT::v4f32: case MVT::v2f64:
1111     RRC = &ARM::DPRRegClass;
1112     Cost = 2;
1113     break;
1114   case MVT::v4i64:
1115     RRC = &ARM::DPRRegClass;
1116     Cost = 4;
1117     break;
1118   case MVT::v8i64:
1119     RRC = &ARM::DPRRegClass;
1120     Cost = 8;
1121     break;
1122   }
1123   return std::make_pair(RRC, Cost);
1124 }
1125
1126 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1127   switch ((ARMISD::NodeType)Opcode) {
1128   case ARMISD::FIRST_NUMBER:  break;
1129   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1130   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1131   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1132   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1133   case ARMISD::CALL:          return "ARMISD::CALL";
1134   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1135   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1136   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1137   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1138   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1139   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1140   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1141   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1142   case ARMISD::CMP:           return "ARMISD::CMP";
1143   case ARMISD::CMN:           return "ARMISD::CMN";
1144   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1145   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1146   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1147   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1148   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1149
1150   case ARMISD::CMOV:          return "ARMISD::CMOV";
1151
1152   case ARMISD::SSAT:          return "ARMISD::SSAT";
1153
1154   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1155   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1156   case ARMISD::RRX:           return "ARMISD::RRX";
1157
1158   case ARMISD::ADDC:          return "ARMISD::ADDC";
1159   case ARMISD::ADDE:          return "ARMISD::ADDE";
1160   case ARMISD::SUBC:          return "ARMISD::SUBC";
1161   case ARMISD::SUBE:          return "ARMISD::SUBE";
1162
1163   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1164   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1165
1166   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1167   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1168   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1169
1170   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1171
1172   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1173
1174   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1175
1176   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1177
1178   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1179
1180   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1181   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1182
1183   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1184   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1185   case ARMISD::VCGE:          return "ARMISD::VCGE";
1186   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1187   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1188   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1189   case ARMISD::VCGT:          return "ARMISD::VCGT";
1190   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1191   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1192   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1193   case ARMISD::VTST:          return "ARMISD::VTST";
1194
1195   case ARMISD::VSHL:          return "ARMISD::VSHL";
1196   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1197   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1198   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1199   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1200   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1201   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1202   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1203   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1204   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1205   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1206   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1207   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1208   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1209   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1210   case ARMISD::VSLI:          return "ARMISD::VSLI";
1211   case ARMISD::VSRI:          return "ARMISD::VSRI";
1212   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1213   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1214   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1215   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1216   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1217   case ARMISD::VDUP:          return "ARMISD::VDUP";
1218   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1219   case ARMISD::VEXT:          return "ARMISD::VEXT";
1220   case ARMISD::VREV64:        return "ARMISD::VREV64";
1221   case ARMISD::VREV32:        return "ARMISD::VREV32";
1222   case ARMISD::VREV16:        return "ARMISD::VREV16";
1223   case ARMISD::VZIP:          return "ARMISD::VZIP";
1224   case ARMISD::VUZP:          return "ARMISD::VUZP";
1225   case ARMISD::VTRN:          return "ARMISD::VTRN";
1226   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1227   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1228   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1229   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1230   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1231   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1232   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1233   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1234   case ARMISD::BFI:           return "ARMISD::BFI";
1235   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1236   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1237   case ARMISD::VBSL:          return "ARMISD::VBSL";
1238   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1239   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1240   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1241   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1242   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1243   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1244   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1245   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1246   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1247   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1248   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1249   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1250   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1251   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1252   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1253   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1254   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1255   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1256   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1257   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1258   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1259   }
1260   return nullptr;
1261 }
1262
1263 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1264                                           EVT VT) const {
1265   if (!VT.isVector())
1266     return getPointerTy(DL);
1267   return VT.changeVectorElementTypeToInteger();
1268 }
1269
1270 /// getRegClassFor - Return the register class that should be used for the
1271 /// specified value type.
1272 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1273   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1274   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1275   // load / store 4 to 8 consecutive D registers.
1276   if (Subtarget->hasNEON()) {
1277     if (VT == MVT::v4i64)
1278       return &ARM::QQPRRegClass;
1279     if (VT == MVT::v8i64)
1280       return &ARM::QQQQPRRegClass;
1281   }
1282   return TargetLowering::getRegClassFor(VT);
1283 }
1284
1285 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1286 // source/dest is aligned and the copy size is large enough. We therefore want
1287 // to align such objects passed to memory intrinsics.
1288 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1289                                                unsigned &PrefAlign) const {
1290   if (!isa<MemIntrinsic>(CI))
1291     return false;
1292   MinSize = 8;
1293   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1294   // cycle faster than 4-byte aligned LDM.
1295   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1296   return true;
1297 }
1298
1299 // Create a fast isel object.
1300 FastISel *
1301 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1302                                   const TargetLibraryInfo *libInfo) const {
1303   return ARM::createFastISel(funcInfo, libInfo);
1304 }
1305
1306 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1307   unsigned NumVals = N->getNumValues();
1308   if (!NumVals)
1309     return Sched::RegPressure;
1310
1311   for (unsigned i = 0; i != NumVals; ++i) {
1312     EVT VT = N->getValueType(i);
1313     if (VT == MVT::Glue || VT == MVT::Other)
1314       continue;
1315     if (VT.isFloatingPoint() || VT.isVector())
1316       return Sched::ILP;
1317   }
1318
1319   if (!N->isMachineOpcode())
1320     return Sched::RegPressure;
1321
1322   // Load are scheduled for latency even if there instruction itinerary
1323   // is not available.
1324   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1325   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1326
1327   if (MCID.getNumDefs() == 0)
1328     return Sched::RegPressure;
1329   if (!Itins->isEmpty() &&
1330       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1331     return Sched::ILP;
1332
1333   return Sched::RegPressure;
1334 }
1335
1336 //===----------------------------------------------------------------------===//
1337 // Lowering Code
1338 //===----------------------------------------------------------------------===//
1339
1340 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1341 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1342   switch (CC) {
1343   default: llvm_unreachable("Unknown condition code!");
1344   case ISD::SETNE:  return ARMCC::NE;
1345   case ISD::SETEQ:  return ARMCC::EQ;
1346   case ISD::SETGT:  return ARMCC::GT;
1347   case ISD::SETGE:  return ARMCC::GE;
1348   case ISD::SETLT:  return ARMCC::LT;
1349   case ISD::SETLE:  return ARMCC::LE;
1350   case ISD::SETUGT: return ARMCC::HI;
1351   case ISD::SETUGE: return ARMCC::HS;
1352   case ISD::SETULT: return ARMCC::LO;
1353   case ISD::SETULE: return ARMCC::LS;
1354   }
1355 }
1356
1357 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1358 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1359                         ARMCC::CondCodes &CondCode2) {
1360   CondCode2 = ARMCC::AL;
1361   switch (CC) {
1362   default: llvm_unreachable("Unknown FP condition!");
1363   case ISD::SETEQ:
1364   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1365   case ISD::SETGT:
1366   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1367   case ISD::SETGE:
1368   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1369   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1370   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1371   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1372   case ISD::SETO:   CondCode = ARMCC::VC; break;
1373   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1374   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1375   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1376   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1377   case ISD::SETLT:
1378   case ISD::SETULT: CondCode = ARMCC::LT; break;
1379   case ISD::SETLE:
1380   case ISD::SETULE: CondCode = ARMCC::LE; break;
1381   case ISD::SETNE:
1382   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1383   }
1384 }
1385
1386 //===----------------------------------------------------------------------===//
1387 //                      Calling Convention Implementation
1388 //===----------------------------------------------------------------------===//
1389
1390 #include "ARMGenCallingConv.inc"
1391
1392 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1393 /// account presence of floating point hardware and calling convention
1394 /// limitations, such as support for variadic functions.
1395 CallingConv::ID
1396 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1397                                            bool isVarArg) const {
1398   switch (CC) {
1399   default:
1400     llvm_unreachable("Unsupported calling convention");
1401   case CallingConv::ARM_AAPCS:
1402   case CallingConv::ARM_APCS:
1403   case CallingConv::GHC:
1404     return CC;
1405   case CallingConv::PreserveMost:
1406     return CallingConv::PreserveMost;
1407   case CallingConv::ARM_AAPCS_VFP:
1408   case CallingConv::Swift:
1409     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1410   case CallingConv::C:
1411     if (!Subtarget->isAAPCS_ABI())
1412       return CallingConv::ARM_APCS;
1413     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1414              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1415              !isVarArg)
1416       return CallingConv::ARM_AAPCS_VFP;
1417     else
1418       return CallingConv::ARM_AAPCS;
1419   case CallingConv::Fast:
1420   case CallingConv::CXX_FAST_TLS:
1421     if (!Subtarget->isAAPCS_ABI()) {
1422       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1423         return CallingConv::Fast;
1424       return CallingConv::ARM_APCS;
1425     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1426       return CallingConv::ARM_AAPCS_VFP;
1427     else
1428       return CallingConv::ARM_AAPCS;
1429   }
1430 }
1431
1432 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1433 /// CallingConvention.
1434 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1435                                                  bool Return,
1436                                                  bool isVarArg) const {
1437   switch (getEffectiveCallingConv(CC, isVarArg)) {
1438   default:
1439     llvm_unreachable("Unsupported calling convention");
1440   case CallingConv::ARM_APCS:
1441     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1442   case CallingConv::ARM_AAPCS:
1443     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1444   case CallingConv::ARM_AAPCS_VFP:
1445     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1446   case CallingConv::Fast:
1447     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1448   case CallingConv::GHC:
1449     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1450   case CallingConv::PreserveMost:
1451     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1452   }
1453 }
1454
1455 /// LowerCallResult - Lower the result values of a call into the
1456 /// appropriate copies out of appropriate physical registers.
1457 SDValue ARMTargetLowering::LowerCallResult(
1458     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1459     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1460     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1461     SDValue ThisVal) const {
1462
1463   // Assign locations to each value returned by this call.
1464   SmallVector<CCValAssign, 16> RVLocs;
1465   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1466                     *DAG.getContext(), Call);
1467   CCInfo.AnalyzeCallResult(Ins,
1468                            CCAssignFnForNode(CallConv, /* Return*/ true,
1469                                              isVarArg));
1470
1471   // Copy all of the result registers out of their specified physreg.
1472   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1473     CCValAssign VA = RVLocs[i];
1474
1475     // Pass 'this' value directly from the argument to return value, to avoid
1476     // reg unit interference
1477     if (i == 0 && isThisReturn && EnableThisRetForwarding) {
1478       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1479              "unexpected return calling convention register assignment");
1480       InVals.push_back(ThisVal);
1481       continue;
1482     }
1483
1484     SDValue Val;
1485     if (VA.needsCustom()) {
1486       // Handle f64 or half of a v2f64.
1487       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1488                                       InFlag);
1489       Chain = Lo.getValue(1);
1490       InFlag = Lo.getValue(2);
1491       VA = RVLocs[++i]; // skip ahead to next loc
1492       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1493                                       InFlag);
1494       Chain = Hi.getValue(1);
1495       InFlag = Hi.getValue(2);
1496       if (!Subtarget->isLittle())
1497         std::swap (Lo, Hi);
1498       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1499
1500       if (VA.getLocVT() == MVT::v2f64) {
1501         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1502         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1503                           DAG.getConstant(0, dl, MVT::i32));
1504
1505         VA = RVLocs[++i]; // skip ahead to next loc
1506         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1507         Chain = Lo.getValue(1);
1508         InFlag = Lo.getValue(2);
1509         VA = RVLocs[++i]; // skip ahead to next loc
1510         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1511         Chain = Hi.getValue(1);
1512         InFlag = Hi.getValue(2);
1513         if (!Subtarget->isLittle())
1514           std::swap (Lo, Hi);
1515         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1516         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1517                           DAG.getConstant(1, dl, MVT::i32));
1518       }
1519     } else {
1520       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1521                                InFlag);
1522       Chain = Val.getValue(1);
1523       InFlag = Val.getValue(2);
1524     }
1525
1526     switch (VA.getLocInfo()) {
1527     default: llvm_unreachable("Unknown loc info!");
1528     case CCValAssign::Full: break;
1529     case CCValAssign::BCvt:
1530       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1531       break;
1532     }
1533
1534     InVals.push_back(Val);
1535   }
1536
1537   return Chain;
1538 }
1539
1540 /// LowerMemOpCallTo - Store the argument to the stack.
1541 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1542                                             SDValue Arg, const SDLoc &dl,
1543                                             SelectionDAG &DAG,
1544                                             const CCValAssign &VA,
1545                                             ISD::ArgFlagsTy Flags) const {
1546   unsigned LocMemOffset = VA.getLocMemOffset();
1547   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1548   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1549                        StackPtr, PtrOff);
1550   return DAG.getStore(
1551       Chain, dl, Arg, PtrOff,
1552       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1553 }
1554
1555 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1556                                          SDValue Chain, SDValue &Arg,
1557                                          RegsToPassVector &RegsToPass,
1558                                          CCValAssign &VA, CCValAssign &NextVA,
1559                                          SDValue &StackPtr,
1560                                          SmallVectorImpl<SDValue> &MemOpChains,
1561                                          ISD::ArgFlagsTy Flags) const {
1562
1563   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1564                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1565   unsigned id = Subtarget->isLittle() ? 0 : 1;
1566   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1567
1568   if (NextVA.isRegLoc())
1569     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1570   else {
1571     assert(NextVA.isMemLoc());
1572     if (!StackPtr.getNode())
1573       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1574                                     getPointerTy(DAG.getDataLayout()));
1575
1576     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1577                                            dl, DAG, NextVA,
1578                                            Flags));
1579   }
1580 }
1581
1582 /// LowerCall - Lowering a call into a callseq_start <-
1583 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1584 /// nodes.
1585 SDValue
1586 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1587                              SmallVectorImpl<SDValue> &InVals) const {
1588   SelectionDAG &DAG                     = CLI.DAG;
1589   SDLoc &dl                             = CLI.DL;
1590   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1591   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1592   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1593   SDValue Chain                         = CLI.Chain;
1594   SDValue Callee                        = CLI.Callee;
1595   bool &isTailCall                      = CLI.IsTailCall;
1596   CallingConv::ID CallConv              = CLI.CallConv;
1597   bool doesNotRet                       = CLI.DoesNotReturn;
1598   bool isVarArg                         = CLI.IsVarArg;
1599
1600   MachineFunction &MF = DAG.getMachineFunction();
1601   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1602   bool isThisReturn   = false;
1603   bool isSibCall      = false;
1604   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1605
1606   // Disable tail calls if they're not supported.
1607   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1608     isTailCall = false;
1609
1610   if (isTailCall) {
1611     // Check if it's really possible to do a tail call.
1612     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1613                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1614                                                    Outs, OutVals, Ins, DAG);
1615     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1616       report_fatal_error("failed to perform tail call elimination on a call "
1617                          "site marked musttail");
1618     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1619     // detected sibcalls.
1620     if (isTailCall) {
1621       ++NumTailCalls;
1622       isSibCall = true;
1623     }
1624   }
1625
1626   // Analyze operands of the call, assigning locations to each operand.
1627   SmallVector<CCValAssign, 16> ArgLocs;
1628   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1629                     *DAG.getContext(), Call);
1630   CCInfo.AnalyzeCallOperands(Outs,
1631                              CCAssignFnForNode(CallConv, /* Return*/ false,
1632                                                isVarArg));
1633
1634   // Get a count of how many bytes are to be pushed on the stack.
1635   unsigned NumBytes = CCInfo.getNextStackOffset();
1636
1637   // For tail calls, memory operands are available in our caller's stack.
1638   if (isSibCall)
1639     NumBytes = 0;
1640
1641   // Adjust the stack pointer for the new arguments...
1642   // These operations are automatically eliminated by the prolog/epilog pass
1643   if (!isSibCall)
1644     Chain = DAG.getCALLSEQ_START(Chain,
1645                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1646
1647   SDValue StackPtr =
1648       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1649
1650   RegsToPassVector RegsToPass;
1651   SmallVector<SDValue, 8> MemOpChains;
1652
1653   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1654   // of tail call optimization, arguments are handled later.
1655   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1656        i != e;
1657        ++i, ++realArgIdx) {
1658     CCValAssign &VA = ArgLocs[i];
1659     SDValue Arg = OutVals[realArgIdx];
1660     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1661     bool isByVal = Flags.isByVal();
1662
1663     // Promote the value if needed.
1664     switch (VA.getLocInfo()) {
1665     default: llvm_unreachable("Unknown loc info!");
1666     case CCValAssign::Full: break;
1667     case CCValAssign::SExt:
1668       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1669       break;
1670     case CCValAssign::ZExt:
1671       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1672       break;
1673     case CCValAssign::AExt:
1674       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1675       break;
1676     case CCValAssign::BCvt:
1677       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1678       break;
1679     }
1680
1681     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1682     if (VA.needsCustom()) {
1683       if (VA.getLocVT() == MVT::v2f64) {
1684         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1685                                   DAG.getConstant(0, dl, MVT::i32));
1686         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1687                                   DAG.getConstant(1, dl, MVT::i32));
1688
1689         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1690                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1691
1692         VA = ArgLocs[++i]; // skip ahead to next loc
1693         if (VA.isRegLoc()) {
1694           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1695                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1696         } else {
1697           assert(VA.isMemLoc());
1698
1699           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1700                                                  dl, DAG, VA, Flags));
1701         }
1702       } else {
1703         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1704                          StackPtr, MemOpChains, Flags);
1705       }
1706     } else if (VA.isRegLoc()) {
1707       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1708         assert(VA.getLocVT() == MVT::i32 &&
1709                "unexpected calling convention register assignment");
1710         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1711                "unexpected use of 'returned'");
1712         isThisReturn = true;
1713       }
1714       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1715     } else if (isByVal) {
1716       assert(VA.isMemLoc());
1717       unsigned offset = 0;
1718
1719       // True if this byval aggregate will be split between registers
1720       // and memory.
1721       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1722       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1723
1724       if (CurByValIdx < ByValArgsCount) {
1725
1726         unsigned RegBegin, RegEnd;
1727         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1728
1729         EVT PtrVT =
1730             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1731         unsigned int i, j;
1732         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1733           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1734           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1735           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1736                                      MachinePointerInfo(),
1737                                      DAG.InferPtrAlignment(AddArg));
1738           MemOpChains.push_back(Load.getValue(1));
1739           RegsToPass.push_back(std::make_pair(j, Load));
1740         }
1741
1742         // If parameter size outsides register area, "offset" value
1743         // helps us to calculate stack slot for remained part properly.
1744         offset = RegEnd - RegBegin;
1745
1746         CCInfo.nextInRegsParam();
1747       }
1748
1749       if (Flags.getByValSize() > 4*offset) {
1750         auto PtrVT = getPointerTy(DAG.getDataLayout());
1751         unsigned LocMemOffset = VA.getLocMemOffset();
1752         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1753         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1754         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1755         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1756         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1757                                            MVT::i32);
1758         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1759                                             MVT::i32);
1760
1761         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1762         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1763         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1764                                           Ops));
1765       }
1766     } else if (!isSibCall) {
1767       assert(VA.isMemLoc());
1768
1769       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1770                                              dl, DAG, VA, Flags));
1771     }
1772   }
1773
1774   if (!MemOpChains.empty())
1775     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1776
1777   // Build a sequence of copy-to-reg nodes chained together with token chain
1778   // and flag operands which copy the outgoing args into the appropriate regs.
1779   SDValue InFlag;
1780   // Tail call byval lowering might overwrite argument registers so in case of
1781   // tail call optimization the copies to registers are lowered later.
1782   if (!isTailCall)
1783     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1784       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1785                                RegsToPass[i].second, InFlag);
1786       InFlag = Chain.getValue(1);
1787     }
1788
1789   // For tail calls lower the arguments to the 'real' stack slot.
1790   if (isTailCall) {
1791     // Force all the incoming stack arguments to be loaded from the stack
1792     // before any new outgoing arguments are stored to the stack, because the
1793     // outgoing stack slots may alias the incoming argument stack slots, and
1794     // the alias isn't otherwise explicit. This is slightly more conservative
1795     // than necessary, because it means that each store effectively depends
1796     // on every argument instead of just those arguments it would clobber.
1797
1798     // Do not flag preceding copytoreg stuff together with the following stuff.
1799     InFlag = SDValue();
1800     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1801       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1802                                RegsToPass[i].second, InFlag);
1803       InFlag = Chain.getValue(1);
1804     }
1805     InFlag = SDValue();
1806   }
1807
1808   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1809   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1810   // node so that legalize doesn't hack it.
1811   bool isDirect = false;
1812
1813   const TargetMachine &TM = getTargetMachine();
1814   const Module *Mod = MF.getFunction()->getParent();
1815   const GlobalValue *GV = nullptr;
1816   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1817     GV = G->getGlobal();
1818   bool isStub =
1819       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1820
1821   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1822   bool isLocalARMFunc = false;
1823   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1824   auto PtrVt = getPointerTy(DAG.getDataLayout());
1825
1826   if (Subtarget->genLongCalls()) {
1827     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1828            "long-calls codegen is not position independent!");
1829     // Handle a global address or an external symbol. If it's not one of
1830     // those, the target's already in a register, so we don't need to do
1831     // anything extra.
1832     if (isa<GlobalAddressSDNode>(Callee)) {
1833       // Create a constant pool entry for the callee address
1834       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1835       ARMConstantPoolValue *CPV =
1836         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1837
1838       // Get the address of the callee into a register
1839       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1840       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1841       Callee = DAG.getLoad(
1842           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1843           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1844     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1845       const char *Sym = S->getSymbol();
1846
1847       // Create a constant pool entry for the callee address
1848       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1849       ARMConstantPoolValue *CPV =
1850         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1851                                       ARMPCLabelIndex, 0);
1852       // Get the address of the callee into a register
1853       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1854       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1855       Callee = DAG.getLoad(
1856           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1857           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1858     }
1859   } else if (isa<GlobalAddressSDNode>(Callee)) {
1860     // If we're optimizing for minimum size and the function is called three or
1861     // more times in this block, we can improve codesize by calling indirectly
1862     // as BLXr has a 16-bit encoding.
1863     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
1864     auto *BB = CLI.CS->getParent();
1865     bool PreferIndirect =
1866         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
1867         std::count_if(GV->user_begin(), GV->user_end(), [&BB](const User *U) {
1868           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
1869         }) > 2;
1870
1871     if (!PreferIndirect) {
1872       isDirect = true;
1873       bool isDef = GV->isStrongDefinitionForLinker();
1874
1875       // ARM call to a local ARM function is predicable.
1876       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1877       // tBX takes a register source operand.
1878       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1879         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1880         Callee = DAG.getNode(
1881             ARMISD::WrapperPIC, dl, PtrVt,
1882             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1883         Callee =
1884             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1885                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1886                         /* Alignment = */ 0, MachineMemOperand::MOInvariant);
1887       } else if (Subtarget->isTargetCOFF()) {
1888         assert(Subtarget->isTargetWindows() &&
1889                "Windows is the only supported COFF target");
1890         unsigned TargetFlags = GV->hasDLLImportStorageClass()
1891                                    ? ARMII::MO_DLLIMPORT
1892                                    : ARMII::MO_NO_FLAG;
1893         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
1894                                             TargetFlags);
1895         if (GV->hasDLLImportStorageClass())
1896           Callee =
1897               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1898                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1899                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1900       } else {
1901         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
1902       }
1903     }
1904   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1905     isDirect = true;
1906     // tBX takes a register source operand.
1907     const char *Sym = S->getSymbol();
1908     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1909       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1910       ARMConstantPoolValue *CPV =
1911         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1912                                       ARMPCLabelIndex, 4);
1913       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1914       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1915       Callee = DAG.getLoad(
1916           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1917           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
1918       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1919       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1920     } else {
1921       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
1922     }
1923   }
1924
1925   // FIXME: handle tail calls differently.
1926   unsigned CallOpc;
1927   if (Subtarget->isThumb()) {
1928     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1929       CallOpc = ARMISD::CALL_NOLINK;
1930     else
1931       CallOpc = ARMISD::CALL;
1932   } else {
1933     if (!isDirect && !Subtarget->hasV5TOps())
1934       CallOpc = ARMISD::CALL_NOLINK;
1935     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
1936              // Emit regular call when code size is the priority
1937              !MF.getFunction()->optForMinSize())
1938       // "mov lr, pc; b _foo" to avoid confusing the RSP
1939       CallOpc = ARMISD::CALL_NOLINK;
1940     else
1941       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1942   }
1943
1944   std::vector<SDValue> Ops;
1945   Ops.push_back(Chain);
1946   Ops.push_back(Callee);
1947
1948   // Add argument registers to the end of the list so that they are known live
1949   // into the call.
1950   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1951     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1952                                   RegsToPass[i].second.getValueType()));
1953
1954   // Add a register mask operand representing the call-preserved registers.
1955   if (!isTailCall) {
1956     const uint32_t *Mask;
1957     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1958     if (isThisReturn) {
1959       // For 'this' returns, use the R0-preserving mask if applicable
1960       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1961       if (!Mask) {
1962         // Set isThisReturn to false if the calling convention is not one that
1963         // allows 'returned' to be modeled in this way, so LowerCallResult does
1964         // not try to pass 'this' straight through
1965         isThisReturn = false;
1966         Mask = ARI->getCallPreservedMask(MF, CallConv);
1967       }
1968     } else
1969       Mask = ARI->getCallPreservedMask(MF, CallConv);
1970
1971     assert(Mask && "Missing call preserved mask for calling convention");
1972     Ops.push_back(DAG.getRegisterMask(Mask));
1973   }
1974
1975   if (InFlag.getNode())
1976     Ops.push_back(InFlag);
1977
1978   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1979   if (isTailCall) {
1980     MF.getFrameInfo()->setHasTailCall();
1981     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1982   }
1983
1984   // Returns a chain and a flag for retval copy to use.
1985   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1986   InFlag = Chain.getValue(1);
1987
1988   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1989                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1990   if (!Ins.empty())
1991     InFlag = Chain.getValue(1);
1992
1993   // Handle result values, copying them out of physregs into vregs that we
1994   // return.
1995   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1996                          InVals, isThisReturn,
1997                          isThisReturn ? OutVals[0] : SDValue());
1998 }
1999
2000 /// HandleByVal - Every parameter *after* a byval parameter is passed
2001 /// on the stack.  Remember the next parameter register to allocate,
2002 /// and then confiscate the rest of the parameter registers to insure
2003 /// this.
2004 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2005                                     unsigned Align) const {
2006   assert((State->getCallOrPrologue() == Prologue ||
2007           State->getCallOrPrologue() == Call) &&
2008          "unhandled ParmContext");
2009
2010   // Byval (as with any stack) slots are always at least 4 byte aligned.
2011   Align = std::max(Align, 4U);
2012
2013   unsigned Reg = State->AllocateReg(GPRArgRegs);
2014   if (!Reg)
2015     return;
2016
2017   unsigned AlignInRegs = Align / 4;
2018   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2019   for (unsigned i = 0; i < Waste; ++i)
2020     Reg = State->AllocateReg(GPRArgRegs);
2021
2022   if (!Reg)
2023     return;
2024
2025   unsigned Excess = 4 * (ARM::R4 - Reg);
2026
2027   // Special case when NSAA != SP and parameter size greater than size of
2028   // all remained GPR regs. In that case we can't split parameter, we must
2029   // send it to stack. We also must set NCRN to R4, so waste all
2030   // remained registers.
2031   const unsigned NSAAOffset = State->getNextStackOffset();
2032   if (NSAAOffset != 0 && Size > Excess) {
2033     while (State->AllocateReg(GPRArgRegs))
2034       ;
2035     return;
2036   }
2037
2038   // First register for byval parameter is the first register that wasn't
2039   // allocated before this method call, so it would be "reg".
2040   // If parameter is small enough to be saved in range [reg, r4), then
2041   // the end (first after last) register would be reg + param-size-in-regs,
2042   // else parameter would be splitted between registers and stack,
2043   // end register would be r4 in this case.
2044   unsigned ByValRegBegin = Reg;
2045   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2046   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2047   // Note, first register is allocated in the beginning of function already,
2048   // allocate remained amount of registers we need.
2049   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2050     State->AllocateReg(GPRArgRegs);
2051   // A byval parameter that is split between registers and memory needs its
2052   // size truncated here.
2053   // In the case where the entire structure fits in registers, we set the
2054   // size in memory to zero.
2055   Size = std::max<int>(Size - Excess, 0);
2056 }
2057
2058 /// MatchingStackOffset - Return true if the given stack call argument is
2059 /// already available in the same position (relatively) of the caller's
2060 /// incoming argument stack.
2061 static
2062 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2063                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2064                          const TargetInstrInfo *TII) {
2065   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2066   int FI = INT_MAX;
2067   if (Arg.getOpcode() == ISD::CopyFromReg) {
2068     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2069     if (!TargetRegisterInfo::isVirtualRegister(VR))
2070       return false;
2071     MachineInstr *Def = MRI->getVRegDef(VR);
2072     if (!Def)
2073       return false;
2074     if (!Flags.isByVal()) {
2075       if (!TII->isLoadFromStackSlot(*Def, FI))
2076         return false;
2077     } else {
2078       return false;
2079     }
2080   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2081     if (Flags.isByVal())
2082       // ByVal argument is passed in as a pointer but it's now being
2083       // dereferenced. e.g.
2084       // define @foo(%struct.X* %A) {
2085       //   tail call @bar(%struct.X* byval %A)
2086       // }
2087       return false;
2088     SDValue Ptr = Ld->getBasePtr();
2089     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2090     if (!FINode)
2091       return false;
2092     FI = FINode->getIndex();
2093   } else
2094     return false;
2095
2096   assert(FI != INT_MAX);
2097   if (!MFI->isFixedObjectIndex(FI))
2098     return false;
2099   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2100 }
2101
2102 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2103 /// for tail call optimization. Targets which want to do tail call
2104 /// optimization should implement this function.
2105 bool
2106 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2107                                                      CallingConv::ID CalleeCC,
2108                                                      bool isVarArg,
2109                                                      bool isCalleeStructRet,
2110                                                      bool isCallerStructRet,
2111                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2112                                     const SmallVectorImpl<SDValue> &OutVals,
2113                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2114                                                      SelectionDAG& DAG) const {
2115   MachineFunction &MF = DAG.getMachineFunction();
2116   const Function *CallerF = MF.getFunction();
2117   CallingConv::ID CallerCC = CallerF->getCallingConv();
2118
2119   assert(Subtarget->supportsTailCall());
2120
2121   // Look for obvious safe cases to perform tail call optimization that do not
2122   // require ABI changes. This is what gcc calls sibcall.
2123
2124   // Do not sibcall optimize vararg calls unless the call site is not passing
2125   // any arguments.
2126   if (isVarArg && !Outs.empty())
2127     return false;
2128
2129   // Exception-handling functions need a special set of instructions to indicate
2130   // a return to the hardware. Tail-calling another function would probably
2131   // break this.
2132   if (CallerF->hasFnAttribute("interrupt"))
2133     return false;
2134
2135   // Also avoid sibcall optimization if either caller or callee uses struct
2136   // return semantics.
2137   if (isCalleeStructRet || isCallerStructRet)
2138     return false;
2139
2140   // Externally-defined functions with weak linkage should not be
2141   // tail-called on ARM when the OS does not support dynamic
2142   // pre-emption of symbols, as the AAELF spec requires normal calls
2143   // to undefined weak functions to be replaced with a NOP or jump to the
2144   // next instruction. The behaviour of branch instructions in this
2145   // situation (as used for tail calls) is implementation-defined, so we
2146   // cannot rely on the linker replacing the tail call with a return.
2147   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2148     const GlobalValue *GV = G->getGlobal();
2149     const Triple &TT = getTargetMachine().getTargetTriple();
2150     if (GV->hasExternalWeakLinkage() &&
2151         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2152       return false;
2153   }
2154
2155   // Check that the call results are passed in the same way.
2156   LLVMContext &C = *DAG.getContext();
2157   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2158                                   CCAssignFnForNode(CalleeCC, true, isVarArg),
2159                                   CCAssignFnForNode(CallerCC, true, isVarArg)))
2160     return false;
2161   // The callee has to preserve all registers the caller needs to preserve.
2162   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2163   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2164   if (CalleeCC != CallerCC) {
2165     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2166     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2167       return false;
2168   }
2169
2170   // If Caller's vararg or byval argument has been split between registers and
2171   // stack, do not perform tail call, since part of the argument is in caller's
2172   // local frame.
2173   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2174   if (AFI_Caller->getArgRegsSaveSize())
2175     return false;
2176
2177   // If the callee takes no arguments then go on to check the results of the
2178   // call.
2179   if (!Outs.empty()) {
2180     // Check if stack adjustment is needed. For now, do not do this if any
2181     // argument is passed on the stack.
2182     SmallVector<CCValAssign, 16> ArgLocs;
2183     ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call);
2184     CCInfo.AnalyzeCallOperands(Outs,
2185                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2186     if (CCInfo.getNextStackOffset()) {
2187       // Check if the arguments are already laid out in the right way as
2188       // the caller's fixed stack objects.
2189       MachineFrameInfo *MFI = MF.getFrameInfo();
2190       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2191       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2192       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2193            i != e;
2194            ++i, ++realArgIdx) {
2195         CCValAssign &VA = ArgLocs[i];
2196         EVT RegVT = VA.getLocVT();
2197         SDValue Arg = OutVals[realArgIdx];
2198         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2199         if (VA.getLocInfo() == CCValAssign::Indirect)
2200           return false;
2201         if (VA.needsCustom()) {
2202           // f64 and vector types are split into multiple registers or
2203           // register/stack-slot combinations.  The types will not match
2204           // the registers; give up on memory f64 refs until we figure
2205           // out what to do about this.
2206           if (!VA.isRegLoc())
2207             return false;
2208           if (!ArgLocs[++i].isRegLoc())
2209             return false;
2210           if (RegVT == MVT::v2f64) {
2211             if (!ArgLocs[++i].isRegLoc())
2212               return false;
2213             if (!ArgLocs[++i].isRegLoc())
2214               return false;
2215           }
2216         } else if (!VA.isRegLoc()) {
2217           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2218                                    MFI, MRI, TII))
2219             return false;
2220         }
2221       }
2222     }
2223
2224     const MachineRegisterInfo &MRI = MF.getRegInfo();
2225     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2226       return false;
2227   }
2228
2229   return true;
2230 }
2231
2232 bool
2233 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2234                                   MachineFunction &MF, bool isVarArg,
2235                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2236                                   LLVMContext &Context) const {
2237   SmallVector<CCValAssign, 16> RVLocs;
2238   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2239   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2240                                                     isVarArg));
2241 }
2242
2243 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2244                                     const SDLoc &DL, SelectionDAG &DAG) {
2245   const MachineFunction &MF = DAG.getMachineFunction();
2246   const Function *F = MF.getFunction();
2247
2248   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2249
2250   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2251   // version of the "preferred return address". These offsets affect the return
2252   // instruction if this is a return from PL1 without hypervisor extensions.
2253   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2254   //    SWI:     0      "subs pc, lr, #0"
2255   //    ABORT:   +4     "subs pc, lr, #4"
2256   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2257   // UNDEF varies depending on where the exception came from ARM or Thumb
2258   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2259
2260   int64_t LROffset;
2261   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2262       IntKind == "ABORT")
2263     LROffset = 4;
2264   else if (IntKind == "SWI" || IntKind == "UNDEF")
2265     LROffset = 0;
2266   else
2267     report_fatal_error("Unsupported interrupt attribute. If present, value "
2268                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2269
2270   RetOps.insert(RetOps.begin() + 1,
2271                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2272
2273   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2274 }
2275
2276 SDValue
2277 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2278                                bool isVarArg,
2279                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2280                                const SmallVectorImpl<SDValue> &OutVals,
2281                                const SDLoc &dl, SelectionDAG &DAG) const {
2282
2283   // CCValAssign - represent the assignment of the return value to a location.
2284   SmallVector<CCValAssign, 16> RVLocs;
2285
2286   // CCState - Info about the registers and stack slots.
2287   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2288                     *DAG.getContext(), Call);
2289
2290   // Analyze outgoing return values.
2291   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2292                                                isVarArg));
2293
2294   SDValue Flag;
2295   SmallVector<SDValue, 4> RetOps;
2296   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2297   bool isLittleEndian = Subtarget->isLittle();
2298
2299   MachineFunction &MF = DAG.getMachineFunction();
2300   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2301   AFI->setReturnRegsCount(RVLocs.size());
2302
2303   // Copy the result values into the output registers.
2304   for (unsigned i = 0, realRVLocIdx = 0;
2305        i != RVLocs.size();
2306        ++i, ++realRVLocIdx) {
2307     CCValAssign &VA = RVLocs[i];
2308     assert(VA.isRegLoc() && "Can only return in registers!");
2309
2310     SDValue Arg = OutVals[realRVLocIdx];
2311
2312     switch (VA.getLocInfo()) {
2313     default: llvm_unreachable("Unknown loc info!");
2314     case CCValAssign::Full: break;
2315     case CCValAssign::BCvt:
2316       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2317       break;
2318     }
2319
2320     if (VA.needsCustom()) {
2321       if (VA.getLocVT() == MVT::v2f64) {
2322         // Extract the first half and return it in two registers.
2323         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2324                                    DAG.getConstant(0, dl, MVT::i32));
2325         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2326                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2327
2328         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2329                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2330                                  Flag);
2331         Flag = Chain.getValue(1);
2332         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2333         VA = RVLocs[++i]; // skip ahead to next loc
2334         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2335                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2336                                  Flag);
2337         Flag = Chain.getValue(1);
2338         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2339         VA = RVLocs[++i]; // skip ahead to next loc
2340
2341         // Extract the 2nd half and fall through to handle it as an f64 value.
2342         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2343                           DAG.getConstant(1, dl, MVT::i32));
2344       }
2345       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2346       // available.
2347       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2348                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2349       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2350                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2351                                Flag);
2352       Flag = Chain.getValue(1);
2353       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2354       VA = RVLocs[++i]; // skip ahead to next loc
2355       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2356                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2357                                Flag);
2358     } else
2359       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2360
2361     // Guarantee that all emitted copies are
2362     // stuck together, avoiding something bad.
2363     Flag = Chain.getValue(1);
2364     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2365   }
2366   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2367   const MCPhysReg *I =
2368       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2369   if (I) {
2370     for (; *I; ++I) {
2371       if (ARM::GPRRegClass.contains(*I))
2372         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2373       else if (ARM::DPRRegClass.contains(*I))
2374         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2375       else
2376         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2377     }
2378   }
2379
2380   // Update chain and glue.
2381   RetOps[0] = Chain;
2382   if (Flag.getNode())
2383     RetOps.push_back(Flag);
2384
2385   // CPUs which aren't M-class use a special sequence to return from
2386   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2387   // though we use "subs pc, lr, #N").
2388   //
2389   // M-class CPUs actually use a normal return sequence with a special
2390   // (hardware-provided) value in LR, so the normal code path works.
2391   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2392       !Subtarget->isMClass()) {
2393     if (Subtarget->isThumb1Only())
2394       report_fatal_error("interrupt attribute is not supported in Thumb1");
2395     return LowerInterruptReturn(RetOps, dl, DAG);
2396   }
2397
2398   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2399 }
2400
2401 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2402   if (N->getNumValues() != 1)
2403     return false;
2404   if (!N->hasNUsesOfValue(1, 0))
2405     return false;
2406
2407   SDValue TCChain = Chain;
2408   SDNode *Copy = *N->use_begin();
2409   if (Copy->getOpcode() == ISD::CopyToReg) {
2410     // If the copy has a glue operand, we conservatively assume it isn't safe to
2411     // perform a tail call.
2412     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2413       return false;
2414     TCChain = Copy->getOperand(0);
2415   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2416     SDNode *VMov = Copy;
2417     // f64 returned in a pair of GPRs.
2418     SmallPtrSet<SDNode*, 2> Copies;
2419     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2420          UI != UE; ++UI) {
2421       if (UI->getOpcode() != ISD::CopyToReg)
2422         return false;
2423       Copies.insert(*UI);
2424     }
2425     if (Copies.size() > 2)
2426       return false;
2427
2428     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2429          UI != UE; ++UI) {
2430       SDValue UseChain = UI->getOperand(0);
2431       if (Copies.count(UseChain.getNode()))
2432         // Second CopyToReg
2433         Copy = *UI;
2434       else {
2435         // We are at the top of this chain.
2436         // If the copy has a glue operand, we conservatively assume it
2437         // isn't safe to perform a tail call.
2438         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2439           return false;
2440         // First CopyToReg
2441         TCChain = UseChain;
2442       }
2443     }
2444   } else if (Copy->getOpcode() == ISD::BITCAST) {
2445     // f32 returned in a single GPR.
2446     if (!Copy->hasOneUse())
2447       return false;
2448     Copy = *Copy->use_begin();
2449     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2450       return false;
2451     // If the copy has a glue operand, we conservatively assume it isn't safe to
2452     // perform a tail call.
2453     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2454       return false;
2455     TCChain = Copy->getOperand(0);
2456   } else {
2457     return false;
2458   }
2459
2460   bool HasRet = false;
2461   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2462        UI != UE; ++UI) {
2463     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2464         UI->getOpcode() != ARMISD::INTRET_FLAG)
2465       return false;
2466     HasRet = true;
2467   }
2468
2469   if (!HasRet)
2470     return false;
2471
2472   Chain = TCChain;
2473   return true;
2474 }
2475
2476 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2477   if (!Subtarget->supportsTailCall())
2478     return false;
2479
2480   auto Attr =
2481       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2482   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2483     return false;
2484
2485   return true;
2486 }
2487
2488 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2489 // and pass the lower and high parts through.
2490 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2491   SDLoc DL(Op);
2492   SDValue WriteValue = Op->getOperand(2);
2493
2494   // This function is only supposed to be called for i64 type argument.
2495   assert(WriteValue.getValueType() == MVT::i64
2496           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2497
2498   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2499                            DAG.getConstant(0, DL, MVT::i32));
2500   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2501                            DAG.getConstant(1, DL, MVT::i32));
2502   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2503   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2504 }
2505
2506 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2507 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2508 // one of the above mentioned nodes. It has to be wrapped because otherwise
2509 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2510 // be used to form addressing mode. These wrapped nodes will be selected
2511 // into MOVi.
2512 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2513   EVT PtrVT = Op.getValueType();
2514   // FIXME there is no actual debug info here
2515   SDLoc dl(Op);
2516   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2517   SDValue Res;
2518   if (CP->isMachineConstantPoolEntry())
2519     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2520                                     CP->getAlignment());
2521   else
2522     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2523                                     CP->getAlignment());
2524   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2525 }
2526
2527 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2528   return MachineJumpTableInfo::EK_Inline;
2529 }
2530
2531 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2532                                              SelectionDAG &DAG) const {
2533   MachineFunction &MF = DAG.getMachineFunction();
2534   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2535   unsigned ARMPCLabelIndex = 0;
2536   SDLoc DL(Op);
2537   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2538   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2539   SDValue CPAddr;
2540   bool IsPositionIndependent = isPositionIndependent();
2541   if (!IsPositionIndependent) {
2542     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2543   } else {
2544     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2545     ARMPCLabelIndex = AFI->createPICLabelUId();
2546     ARMConstantPoolValue *CPV =
2547       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2548                                       ARMCP::CPBlockAddress, PCAdj);
2549     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2550   }
2551   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2552   SDValue Result = DAG.getLoad(
2553       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2554       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2555   if (!IsPositionIndependent)
2556     return Result;
2557   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2558   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2559 }
2560
2561 /// \brief Convert a TLS address reference into the correct sequence of loads
2562 /// and calls to compute the variable's address for Darwin, and return an
2563 /// SDValue containing the final node.
2564
2565 /// Darwin only has one TLS scheme which must be capable of dealing with the
2566 /// fully general situation, in the worst case. This means:
2567 ///     + "extern __thread" declaration.
2568 ///     + Defined in a possibly unknown dynamic library.
2569 ///
2570 /// The general system is that each __thread variable has a [3 x i32] descriptor
2571 /// which contains information used by the runtime to calculate the address. The
2572 /// only part of this the compiler needs to know about is the first word, which
2573 /// contains a function pointer that must be called with the address of the
2574 /// entire descriptor in "r0".
2575 ///
2576 /// Since this descriptor may be in a different unit, in general access must
2577 /// proceed along the usual ARM rules. A common sequence to produce is:
2578 ///
2579 ///     movw rT1, :lower16:_var$non_lazy_ptr
2580 ///     movt rT1, :upper16:_var$non_lazy_ptr
2581 ///     ldr r0, [rT1]
2582 ///     ldr rT2, [r0]
2583 ///     blx rT2
2584 ///     [...address now in r0...]
2585 SDValue
2586 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2587                                                SelectionDAG &DAG) const {
2588   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2589   SDLoc DL(Op);
2590
2591   // First step is to get the address of the actua global symbol. This is where
2592   // the TLS descriptor lives.
2593   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2594
2595   // The first entry in the descriptor is a function pointer that we must call
2596   // to obtain the address of the variable.
2597   SDValue Chain = DAG.getEntryNode();
2598   SDValue FuncTLVGet =
2599       DAG.getLoad(MVT::i32, DL, Chain, DescAddr,
2600                   MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2601                   /* Alignment = */ 4, MachineMemOperand::MONonTemporal |
2602                                            MachineMemOperand::MOInvariant);
2603   Chain = FuncTLVGet.getValue(1);
2604
2605   MachineFunction &F = DAG.getMachineFunction();
2606   MachineFrameInfo *MFI = F.getFrameInfo();
2607   MFI->setAdjustsStack(true);
2608
2609   // TLS calls preserve all registers except those that absolutely must be
2610   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2611   // silly).
2612   auto TRI =
2613       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2614   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2615   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2616
2617   // Finally, we can make the call. This is just a degenerate version of a
2618   // normal AArch64 call node: r0 takes the address of the descriptor, and
2619   // returns the address of the variable in this thread.
2620   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2621   Chain =
2622       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2623                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2624                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2625   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2626 }
2627
2628 SDValue
2629 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2630                                                 SelectionDAG &DAG) const {
2631   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2632
2633   SDValue Chain = DAG.getEntryNode();
2634   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2635   SDLoc DL(Op);
2636
2637   // Load the current TEB (thread environment block)
2638   SDValue Ops[] = {Chain,
2639                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2640                    DAG.getConstant(15, DL, MVT::i32),
2641                    DAG.getConstant(0, DL, MVT::i32),
2642                    DAG.getConstant(13, DL, MVT::i32),
2643                    DAG.getConstant(0, DL, MVT::i32),
2644                    DAG.getConstant(2, DL, MVT::i32)};
2645   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2646                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2647
2648   SDValue TEB = CurrentTEB.getValue(0);
2649   Chain = CurrentTEB.getValue(1);
2650
2651   // Load the ThreadLocalStoragePointer from the TEB
2652   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2653   SDValue TLSArray =
2654       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2655   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2656
2657   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2658   // offset into the TLSArray.
2659
2660   // Load the TLS index from the C runtime
2661   SDValue TLSIndex =
2662       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2663   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2664   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2665
2666   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2667                               DAG.getConstant(2, DL, MVT::i32));
2668   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2669                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2670                             MachinePointerInfo());
2671
2672   // Get the offset of the start of the .tls section (section base)
2673   const auto *GA = cast<GlobalAddressSDNode>(Op);
2674   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2675   SDValue Offset = DAG.getLoad(
2676       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2677                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2678       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2679
2680   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2681 }
2682
2683 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2684 SDValue
2685 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2686                                                  SelectionDAG &DAG) const {
2687   SDLoc dl(GA);
2688   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2689   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2690   MachineFunction &MF = DAG.getMachineFunction();
2691   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2692   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2693   ARMConstantPoolValue *CPV =
2694     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2695                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2696   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2697   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2698   Argument = DAG.getLoad(
2699       PtrVT, dl, DAG.getEntryNode(), Argument,
2700       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2701   SDValue Chain = Argument.getValue(1);
2702
2703   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2704   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2705
2706   // call __tls_get_addr.
2707   ArgListTy Args;
2708   ArgListEntry Entry;
2709   Entry.Node = Argument;
2710   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2711   Args.push_back(Entry);
2712
2713   // FIXME: is there useful debug info available here?
2714   TargetLowering::CallLoweringInfo CLI(DAG);
2715   CLI.setDebugLoc(dl).setChain(Chain)
2716     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2717                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2718
2719   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2720   return CallResult.first;
2721 }
2722
2723 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2724 // "local exec" model.
2725 SDValue
2726 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2727                                         SelectionDAG &DAG,
2728                                         TLSModel::Model model) const {
2729   const GlobalValue *GV = GA->getGlobal();
2730   SDLoc dl(GA);
2731   SDValue Offset;
2732   SDValue Chain = DAG.getEntryNode();
2733   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2734   // Get the Thread Pointer
2735   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2736
2737   if (model == TLSModel::InitialExec) {
2738     MachineFunction &MF = DAG.getMachineFunction();
2739     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2740     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2741     // Initial exec model.
2742     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2743     ARMConstantPoolValue *CPV =
2744       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2745                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2746                                       true);
2747     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2748     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2749     Offset = DAG.getLoad(
2750         PtrVT, dl, Chain, Offset,
2751         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2752     Chain = Offset.getValue(1);
2753
2754     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2755     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2756
2757     Offset = DAG.getLoad(
2758         PtrVT, dl, Chain, Offset,
2759         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2760   } else {
2761     // local exec model
2762     assert(model == TLSModel::LocalExec);
2763     ARMConstantPoolValue *CPV =
2764       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2765     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2766     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2767     Offset = DAG.getLoad(
2768         PtrVT, dl, Chain, Offset,
2769         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2770   }
2771
2772   // The address of the thread local variable is the add of the thread
2773   // pointer with the offset of the variable.
2774   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2775 }
2776
2777 SDValue
2778 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2779   if (Subtarget->isTargetDarwin())
2780     return LowerGlobalTLSAddressDarwin(Op, DAG);
2781
2782   if (Subtarget->isTargetWindows())
2783     return LowerGlobalTLSAddressWindows(Op, DAG);
2784
2785   // TODO: implement the "local dynamic" model
2786   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2787   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2788   if (DAG.getTarget().Options.EmulatedTLS)
2789     return LowerToTLSEmulatedModel(GA, DAG);
2790
2791   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2792
2793   switch (model) {
2794     case TLSModel::GeneralDynamic:
2795     case TLSModel::LocalDynamic:
2796       return LowerToTLSGeneralDynamicModel(GA, DAG);
2797     case TLSModel::InitialExec:
2798     case TLSModel::LocalExec:
2799       return LowerToTLSExecModels(GA, DAG, model);
2800   }
2801   llvm_unreachable("bogus TLS model");
2802 }
2803
2804 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2805                                                  SelectionDAG &DAG) const {
2806   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2807   SDLoc dl(Op);
2808   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2809   const TargetMachine &TM = getTargetMachine();
2810   if (isPositionIndependent()) {
2811     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
2812
2813     MachineFunction &MF = DAG.getMachineFunction();
2814     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2815     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2816     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2817     SDLoc dl(Op);
2818     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2819     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2820         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2821         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2822         /*AddCurrentAddress=*/UseGOT_PREL);
2823     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2824     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2825     SDValue Result = DAG.getLoad(
2826         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2827         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2828     SDValue Chain = Result.getValue(1);
2829     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2830     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2831     if (UseGOT_PREL)
2832       Result =
2833           DAG.getLoad(PtrVT, dl, Chain, Result,
2834                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2835     return Result;
2836   }
2837
2838   // If we have T2 ops, we can materialize the address directly via movt/movw
2839   // pair. This is always cheaper.
2840   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2841     ++NumMovwMovt;
2842     // FIXME: Once remat is capable of dealing with instructions with register
2843     // operands, expand this into two nodes.
2844     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2845                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2846   } else {
2847     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2848     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2849     return DAG.getLoad(
2850         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2851         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2852   }
2853 }
2854
2855 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2856                                                     SelectionDAG &DAG) const {
2857   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2858   SDLoc dl(Op);
2859   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2860
2861   if (Subtarget->useMovt(DAG.getMachineFunction()))
2862     ++NumMovwMovt;
2863
2864   // FIXME: Once remat is capable of dealing with instructions with register
2865   // operands, expand this into multiple nodes
2866   unsigned Wrapper =
2867       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2868
2869   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2870   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2871
2872   if (Subtarget->isGVIndirectSymbol(GV))
2873     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2874                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2875   return Result;
2876 }
2877
2878 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2879                                                      SelectionDAG &DAG) const {
2880   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2881   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2882          "Windows on ARM expects to use movw/movt");
2883
2884   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2885   const ARMII::TOF TargetFlags =
2886     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2887   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2888   SDValue Result;
2889   SDLoc DL(Op);
2890
2891   ++NumMovwMovt;
2892
2893   // FIXME: Once remat is capable of dealing with instructions with register
2894   // operands, expand this into two nodes.
2895   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2896                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2897                                                   TargetFlags));
2898   if (GV->hasDLLImportStorageClass())
2899     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2900                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2901   return Result;
2902 }
2903
2904 SDValue
2905 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2906   SDLoc dl(Op);
2907   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2908   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2909                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2910                      Op.getOperand(1), Val);
2911 }
2912
2913 SDValue
2914 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2915   SDLoc dl(Op);
2916   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2917                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2918 }
2919
2920 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2921                                                       SelectionDAG &DAG) const {
2922   SDLoc dl(Op);
2923   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2924                      Op.getOperand(0));
2925 }
2926
2927 SDValue
2928 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2929                                           const ARMSubtarget *Subtarget) const {
2930   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2931   SDLoc dl(Op);
2932   switch (IntNo) {
2933   default: return SDValue();    // Don't custom lower most intrinsics.
2934   case Intrinsic::arm_rbit: {
2935     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2936            "RBIT intrinsic must have i32 type!");
2937     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
2938   }
2939   case Intrinsic::thread_pointer: {
2940     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2941     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2942   }
2943   case Intrinsic::eh_sjlj_lsda: {
2944     MachineFunction &MF = DAG.getMachineFunction();
2945     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2946     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2947     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2948     SDValue CPAddr;
2949     bool IsPositionIndependent = isPositionIndependent();
2950     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
2951     ARMConstantPoolValue *CPV =
2952       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2953                                       ARMCP::CPLSDA, PCAdj);
2954     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2955     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2956     SDValue Result = DAG.getLoad(
2957         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2958         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2959
2960     if (IsPositionIndependent) {
2961       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2962       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2963     }
2964     return Result;
2965   }
2966   case Intrinsic::arm_neon_vmulls:
2967   case Intrinsic::arm_neon_vmullu: {
2968     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2969       ? ARMISD::VMULLs : ARMISD::VMULLu;
2970     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2971                        Op.getOperand(1), Op.getOperand(2));
2972   }
2973   case Intrinsic::arm_neon_vminnm:
2974   case Intrinsic::arm_neon_vmaxnm: {
2975     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2976       ? ISD::FMINNUM : ISD::FMAXNUM;
2977     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2978                        Op.getOperand(1), Op.getOperand(2));
2979   }
2980   case Intrinsic::arm_neon_vminu:
2981   case Intrinsic::arm_neon_vmaxu: {
2982     if (Op.getValueType().isFloatingPoint())
2983       return SDValue();
2984     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2985       ? ISD::UMIN : ISD::UMAX;
2986     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2987                          Op.getOperand(1), Op.getOperand(2));
2988   }
2989   case Intrinsic::arm_neon_vmins:
2990   case Intrinsic::arm_neon_vmaxs: {
2991     // v{min,max}s is overloaded between signed integers and floats.
2992     if (!Op.getValueType().isFloatingPoint()) {
2993       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2994         ? ISD::SMIN : ISD::SMAX;
2995       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2996                          Op.getOperand(1), Op.getOperand(2));
2997     }
2998     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2999       ? ISD::FMINNAN : ISD::FMAXNAN;
3000     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3001                        Op.getOperand(1), Op.getOperand(2));
3002   }
3003   }
3004 }
3005
3006 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3007                                  const ARMSubtarget *Subtarget) {
3008   // FIXME: handle "fence singlethread" more efficiently.
3009   SDLoc dl(Op);
3010   if (!Subtarget->hasDataBarrier()) {
3011     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3012     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3013     // here.
3014     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3015            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3016     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3017                        DAG.getConstant(0, dl, MVT::i32));
3018   }
3019
3020   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3021   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3022   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3023   if (Subtarget->isMClass()) {
3024     // Only a full system barrier exists in the M-class architectures.
3025     Domain = ARM_MB::SY;
3026   } else if (Subtarget->preferISHSTBarriers() &&
3027              Ord == AtomicOrdering::Release) {
3028     // Swift happens to implement ISHST barriers in a way that's compatible with
3029     // Release semantics but weaker than ISH so we'd be fools not to use
3030     // it. Beware: other processors probably don't!
3031     Domain = ARM_MB::ISHST;
3032   }
3033
3034   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3035                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3036                      DAG.getConstant(Domain, dl, MVT::i32));
3037 }
3038
3039 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3040                              const ARMSubtarget *Subtarget) {
3041   // ARM pre v5TE and Thumb1 does not have preload instructions.
3042   if (!(Subtarget->isThumb2() ||
3043         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3044     // Just preserve the chain.
3045     return Op.getOperand(0);
3046
3047   SDLoc dl(Op);
3048   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3049   if (!isRead &&
3050       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3051     // ARMv7 with MP extension has PLDW.
3052     return Op.getOperand(0);
3053
3054   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3055   if (Subtarget->isThumb()) {
3056     // Invert the bits.
3057     isRead = ~isRead & 1;
3058     isData = ~isData & 1;
3059   }
3060
3061   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3062                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3063                      DAG.getConstant(isData, dl, MVT::i32));
3064 }
3065
3066 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3067   MachineFunction &MF = DAG.getMachineFunction();
3068   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3069
3070   // vastart just stores the address of the VarArgsFrameIndex slot into the
3071   // memory location argument.
3072   SDLoc dl(Op);
3073   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3074   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3075   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3076   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3077                       MachinePointerInfo(SV));
3078 }
3079
3080 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3081                                                 CCValAssign &NextVA,
3082                                                 SDValue &Root,
3083                                                 SelectionDAG &DAG,
3084                                                 const SDLoc &dl) const {
3085   MachineFunction &MF = DAG.getMachineFunction();
3086   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3087
3088   const TargetRegisterClass *RC;
3089   if (AFI->isThumb1OnlyFunction())
3090     RC = &ARM::tGPRRegClass;
3091   else
3092     RC = &ARM::GPRRegClass;
3093
3094   // Transform the arguments stored in physical registers into virtual ones.
3095   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3096   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3097
3098   SDValue ArgValue2;
3099   if (NextVA.isMemLoc()) {
3100     MachineFrameInfo *MFI = MF.getFrameInfo();
3101     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3102
3103     // Create load node to retrieve arguments from the stack.
3104     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3105     ArgValue2 = DAG.getLoad(
3106         MVT::i32, dl, Root, FIN,
3107         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3108   } else {
3109     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3110     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3111   }
3112   if (!Subtarget->isLittle())
3113     std::swap (ArgValue, ArgValue2);
3114   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3115 }
3116
3117 // The remaining GPRs hold either the beginning of variable-argument
3118 // data, or the beginning of an aggregate passed by value (usually
3119 // byval).  Either way, we allocate stack slots adjacent to the data
3120 // provided by our caller, and store the unallocated registers there.
3121 // If this is a variadic function, the va_list pointer will begin with
3122 // these values; otherwise, this reassembles a (byval) structure that
3123 // was split between registers and memory.
3124 // Return: The frame index registers were stored into.
3125 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3126                                       const SDLoc &dl, SDValue &Chain,
3127                                       const Value *OrigArg,
3128                                       unsigned InRegsParamRecordIdx,
3129                                       int ArgOffset, unsigned ArgSize) const {
3130   // Currently, two use-cases possible:
3131   // Case #1. Non-var-args function, and we meet first byval parameter.
3132   //          Setup first unallocated register as first byval register;
3133   //          eat all remained registers
3134   //          (these two actions are performed by HandleByVal method).
3135   //          Then, here, we initialize stack frame with
3136   //          "store-reg" instructions.
3137   // Case #2. Var-args function, that doesn't contain byval parameters.
3138   //          The same: eat all remained unallocated registers,
3139   //          initialize stack frame.
3140
3141   MachineFunction &MF = DAG.getMachineFunction();
3142   MachineFrameInfo *MFI = MF.getFrameInfo();
3143   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3144   unsigned RBegin, REnd;
3145   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3146     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3147   } else {
3148     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3149     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3150     REnd = ARM::R4;
3151   }
3152
3153   if (REnd != RBegin)
3154     ArgOffset = -4 * (ARM::R4 - RBegin);
3155
3156   auto PtrVT = getPointerTy(DAG.getDataLayout());
3157   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3158   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3159
3160   SmallVector<SDValue, 4> MemOps;
3161   const TargetRegisterClass *RC =
3162       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3163
3164   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3165     unsigned VReg = MF.addLiveIn(Reg, RC);
3166     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3167     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3168                                  MachinePointerInfo(OrigArg, 4 * i));
3169     MemOps.push_back(Store);
3170     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3171   }
3172
3173   if (!MemOps.empty())
3174     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3175   return FrameIndex;
3176 }
3177
3178 // Setup stack frame, the va_list pointer will start from.
3179 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3180                                              const SDLoc &dl, SDValue &Chain,
3181                                              unsigned ArgOffset,
3182                                              unsigned TotalArgRegsSaveSize,
3183                                              bool ForceMutable) const {
3184   MachineFunction &MF = DAG.getMachineFunction();
3185   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3186
3187   // Try to store any remaining integer argument regs
3188   // to their spots on the stack so that they may be loaded by dereferencing
3189   // the result of va_next.
3190   // If there is no regs to be stored, just point address after last
3191   // argument passed via stack.
3192   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3193                                   CCInfo.getInRegsParamsCount(),
3194                                   CCInfo.getNextStackOffset(), 4);
3195   AFI->setVarArgsFrameIndex(FrameIndex);
3196 }
3197
3198 SDValue ARMTargetLowering::LowerFormalArguments(
3199     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3200     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3201     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3202   MachineFunction &MF = DAG.getMachineFunction();
3203   MachineFrameInfo *MFI = MF.getFrameInfo();
3204
3205   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3206
3207   // Assign locations to all of the incoming arguments.
3208   SmallVector<CCValAssign, 16> ArgLocs;
3209   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3210                     *DAG.getContext(), Prologue);
3211   CCInfo.AnalyzeFormalArguments(Ins,
3212                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3213                                                   isVarArg));
3214
3215   SmallVector<SDValue, 16> ArgValues;
3216   SDValue ArgValue;
3217   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3218   unsigned CurArgIdx = 0;
3219
3220   // Initially ArgRegsSaveSize is zero.
3221   // Then we increase this value each time we meet byval parameter.
3222   // We also increase this value in case of varargs function.
3223   AFI->setArgRegsSaveSize(0);
3224
3225   // Calculate the amount of stack space that we need to allocate to store
3226   // byval and variadic arguments that are passed in registers.
3227   // We need to know this before we allocate the first byval or variadic
3228   // argument, as they will be allocated a stack slot below the CFA (Canonical
3229   // Frame Address, the stack pointer at entry to the function).
3230   unsigned ArgRegBegin = ARM::R4;
3231   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3232     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3233       break;
3234
3235     CCValAssign &VA = ArgLocs[i];
3236     unsigned Index = VA.getValNo();
3237     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3238     if (!Flags.isByVal())
3239       continue;
3240
3241     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3242     unsigned RBegin, REnd;
3243     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3244     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3245
3246     CCInfo.nextInRegsParam();
3247   }
3248   CCInfo.rewindByValRegsInfo();
3249
3250   int lastInsIndex = -1;
3251   if (isVarArg && MFI->hasVAStart()) {
3252     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3253     if (RegIdx != array_lengthof(GPRArgRegs))
3254       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3255   }
3256
3257   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3258   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3259   auto PtrVT = getPointerTy(DAG.getDataLayout());
3260
3261   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3262     CCValAssign &VA = ArgLocs[i];
3263     if (Ins[VA.getValNo()].isOrigArg()) {
3264       std::advance(CurOrigArg,
3265                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3266       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3267     }
3268     // Arguments stored in registers.
3269     if (VA.isRegLoc()) {
3270       EVT RegVT = VA.getLocVT();
3271
3272       if (VA.needsCustom()) {
3273         // f64 and vector types are split up into multiple registers or
3274         // combinations of registers and stack slots.
3275         if (VA.getLocVT() == MVT::v2f64) {
3276           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3277                                                    Chain, DAG, dl);
3278           VA = ArgLocs[++i]; // skip ahead to next loc
3279           SDValue ArgValue2;
3280           if (VA.isMemLoc()) {
3281             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3282             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3283             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3284                                     MachinePointerInfo::getFixedStack(
3285                                         DAG.getMachineFunction(), FI));
3286           } else {
3287             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3288                                              Chain, DAG, dl);
3289           }
3290           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3291           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3292                                  ArgValue, ArgValue1,
3293                                  DAG.getIntPtrConstant(0, dl));
3294           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3295                                  ArgValue, ArgValue2,
3296                                  DAG.getIntPtrConstant(1, dl));
3297         } else
3298           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3299
3300       } else {
3301         const TargetRegisterClass *RC;
3302
3303         if (RegVT == MVT::f32)
3304           RC = &ARM::SPRRegClass;
3305         else if (RegVT == MVT::f64)
3306           RC = &ARM::DPRRegClass;
3307         else if (RegVT == MVT::v2f64)
3308           RC = &ARM::QPRRegClass;
3309         else if (RegVT == MVT::i32)
3310           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3311                                            : &ARM::GPRRegClass;
3312         else
3313           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3314
3315         // Transform the arguments in physical registers into virtual ones.
3316         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3317         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3318       }
3319
3320       // If this is an 8 or 16-bit value, it is really passed promoted
3321       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3322       // truncate to the right size.
3323       switch (VA.getLocInfo()) {
3324       default: llvm_unreachable("Unknown loc info!");
3325       case CCValAssign::Full: break;
3326       case CCValAssign::BCvt:
3327         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3328         break;
3329       case CCValAssign::SExt:
3330         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3331                                DAG.getValueType(VA.getValVT()));
3332         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3333         break;
3334       case CCValAssign::ZExt:
3335         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3336                                DAG.getValueType(VA.getValVT()));
3337         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3338         break;
3339       }
3340
3341       InVals.push_back(ArgValue);
3342
3343     } else { // VA.isRegLoc()
3344
3345       // sanity check
3346       assert(VA.isMemLoc());
3347       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3348
3349       int index = VA.getValNo();
3350
3351       // Some Ins[] entries become multiple ArgLoc[] entries.
3352       // Process them only once.
3353       if (index != lastInsIndex)
3354         {
3355           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3356           // FIXME: For now, all byval parameter objects are marked mutable.
3357           // This can be changed with more analysis.
3358           // In case of tail call optimization mark all arguments mutable.
3359           // Since they could be overwritten by lowering of arguments in case of
3360           // a tail call.
3361           if (Flags.isByVal()) {
3362             assert(Ins[index].isOrigArg() &&
3363                    "Byval arguments cannot be implicit");
3364             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3365
3366             int FrameIndex = StoreByValRegs(
3367                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3368                 VA.getLocMemOffset(), Flags.getByValSize());
3369             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3370             CCInfo.nextInRegsParam();
3371           } else {
3372             unsigned FIOffset = VA.getLocMemOffset();
3373             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3374                                             FIOffset, true);
3375
3376             // Create load nodes to retrieve arguments from the stack.
3377             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3378             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3379                                          MachinePointerInfo::getFixedStack(
3380                                              DAG.getMachineFunction(), FI)));
3381           }
3382           lastInsIndex = index;
3383         }
3384     }
3385   }
3386
3387   // varargs
3388   if (isVarArg && MFI->hasVAStart())
3389     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3390                          CCInfo.getNextStackOffset(),
3391                          TotalArgRegsSaveSize);
3392
3393   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3394
3395   return Chain;
3396 }
3397
3398 /// isFloatingPointZero - Return true if this is +0.0.
3399 static bool isFloatingPointZero(SDValue Op) {
3400   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3401     return CFP->getValueAPF().isPosZero();
3402   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3403     // Maybe this has already been legalized into the constant pool?
3404     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3405       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3406       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3407         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3408           return CFP->getValueAPF().isPosZero();
3409     }
3410   } else if (Op->getOpcode() == ISD::BITCAST &&
3411              Op->getValueType(0) == MVT::f64) {
3412     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3413     // created by LowerConstantFP().
3414     SDValue BitcastOp = Op->getOperand(0);
3415     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3416         isNullConstant(BitcastOp->getOperand(0)))
3417       return true;
3418   }
3419   return false;
3420 }
3421
3422 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3423 /// the given operands.
3424 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3425                                      SDValue &ARMcc, SelectionDAG &DAG,
3426                                      const SDLoc &dl) const {
3427   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3428     unsigned C = RHSC->getZExtValue();
3429     if (!isLegalICmpImmediate(C)) {
3430       // Constant does not fit, try adjusting it by one?
3431       switch (CC) {
3432       default: break;
3433       case ISD::SETLT:
3434       case ISD::SETGE:
3435         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3436           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3437           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3438         }
3439         break;
3440       case ISD::SETULT:
3441       case ISD::SETUGE:
3442         if (C != 0 && isLegalICmpImmediate(C-1)) {
3443           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3444           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3445         }
3446         break;
3447       case ISD::SETLE:
3448       case ISD::SETGT:
3449         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3450           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3451           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3452         }
3453         break;
3454       case ISD::SETULE:
3455       case ISD::SETUGT:
3456         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3457           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3458           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3459         }
3460         break;
3461       }
3462     }
3463   }
3464
3465   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3466   ARMISD::NodeType CompareType;
3467   switch (CondCode) {
3468   default:
3469     CompareType = ARMISD::CMP;
3470     break;
3471   case ARMCC::EQ:
3472   case ARMCC::NE:
3473     // Uses only Z Flag
3474     CompareType = ARMISD::CMPZ;
3475     break;
3476   }
3477   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3478   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3479 }
3480
3481 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3482 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3483                                      SelectionDAG &DAG, const SDLoc &dl) const {
3484   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3485   SDValue Cmp;
3486   if (!isFloatingPointZero(RHS))
3487     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3488   else
3489     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3490   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3491 }
3492
3493 /// duplicateCmp - Glue values can have only one use, so this function
3494 /// duplicates a comparison node.
3495 SDValue
3496 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3497   unsigned Opc = Cmp.getOpcode();
3498   SDLoc DL(Cmp);
3499   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3500     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3501
3502   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3503   Cmp = Cmp.getOperand(0);
3504   Opc = Cmp.getOpcode();
3505   if (Opc == ARMISD::CMPFP)
3506     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3507   else {
3508     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3509     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3510   }
3511   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3512 }
3513
3514 std::pair<SDValue, SDValue>
3515 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3516                                  SDValue &ARMcc) const {
3517   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3518
3519   SDValue Value, OverflowCmp;
3520   SDValue LHS = Op.getOperand(0);
3521   SDValue RHS = Op.getOperand(1);
3522   SDLoc dl(Op);
3523
3524   // FIXME: We are currently always generating CMPs because we don't support
3525   // generating CMN through the backend. This is not as good as the natural
3526   // CMP case because it causes a register dependency and cannot be folded
3527   // later.
3528
3529   switch (Op.getOpcode()) {
3530   default:
3531     llvm_unreachable("Unknown overflow instruction!");
3532   case ISD::SADDO:
3533     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3534     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3535     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3536     break;
3537   case ISD::UADDO:
3538     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3539     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3540     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3541     break;
3542   case ISD::SSUBO:
3543     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3544     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3545     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3546     break;
3547   case ISD::USUBO:
3548     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3549     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3550     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3551     break;
3552   } // switch (...)
3553
3554   return std::make_pair(Value, OverflowCmp);
3555 }
3556
3557
3558 SDValue
3559 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3560   // Let legalize expand this if it isn't a legal type yet.
3561   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3562     return SDValue();
3563
3564   SDValue Value, OverflowCmp;
3565   SDValue ARMcc;
3566   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3567   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3568   SDLoc dl(Op);
3569   // We use 0 and 1 as false and true values.
3570   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3571   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3572   EVT VT = Op.getValueType();
3573
3574   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3575                                  ARMcc, CCR, OverflowCmp);
3576
3577   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3578   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3579 }
3580
3581
3582 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3583   SDValue Cond = Op.getOperand(0);
3584   SDValue SelectTrue = Op.getOperand(1);
3585   SDValue SelectFalse = Op.getOperand(2);
3586   SDLoc dl(Op);
3587   unsigned Opc = Cond.getOpcode();
3588
3589   if (Cond.getResNo() == 1 &&
3590       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3591        Opc == ISD::USUBO)) {
3592     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3593       return SDValue();
3594
3595     SDValue Value, OverflowCmp;
3596     SDValue ARMcc;
3597     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3598     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3599     EVT VT = Op.getValueType();
3600
3601     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3602                    OverflowCmp, DAG);
3603   }
3604
3605   // Convert:
3606   //
3607   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3608   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3609   //
3610   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3611     const ConstantSDNode *CMOVTrue =
3612       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3613     const ConstantSDNode *CMOVFalse =
3614       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3615
3616     if (CMOVTrue && CMOVFalse) {
3617       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3618       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3619
3620       SDValue True;
3621       SDValue False;
3622       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3623         True = SelectTrue;
3624         False = SelectFalse;
3625       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3626         True = SelectFalse;
3627         False = SelectTrue;
3628       }
3629
3630       if (True.getNode() && False.getNode()) {
3631         EVT VT = Op.getValueType();
3632         SDValue ARMcc = Cond.getOperand(2);
3633         SDValue CCR = Cond.getOperand(3);
3634         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3635         assert(True.getValueType() == VT);
3636         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3637       }
3638     }
3639   }
3640
3641   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3642   // undefined bits before doing a full-word comparison with zero.
3643   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3644                      DAG.getConstant(1, dl, Cond.getValueType()));
3645
3646   return DAG.getSelectCC(dl, Cond,
3647                          DAG.getConstant(0, dl, Cond.getValueType()),
3648                          SelectTrue, SelectFalse, ISD::SETNE);
3649 }
3650
3651 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3652                                  bool &swpCmpOps, bool &swpVselOps) {
3653   // Start by selecting the GE condition code for opcodes that return true for
3654   // 'equality'
3655   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3656       CC == ISD::SETULE)
3657     CondCode = ARMCC::GE;
3658
3659   // and GT for opcodes that return false for 'equality'.
3660   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3661            CC == ISD::SETULT)
3662     CondCode = ARMCC::GT;
3663
3664   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3665   // to swap the compare operands.
3666   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3667       CC == ISD::SETULT)
3668     swpCmpOps = true;
3669
3670   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3671   // If we have an unordered opcode, we need to swap the operands to the VSEL
3672   // instruction (effectively negating the condition).
3673   //
3674   // This also has the effect of swapping which one of 'less' or 'greater'
3675   // returns true, so we also swap the compare operands. It also switches
3676   // whether we return true for 'equality', so we compensate by picking the
3677   // opposite condition code to our original choice.
3678   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3679       CC == ISD::SETUGT) {
3680     swpCmpOps = !swpCmpOps;
3681     swpVselOps = !swpVselOps;
3682     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3683   }
3684
3685   // 'ordered' is 'anything but unordered', so use the VS condition code and
3686   // swap the VSEL operands.
3687   if (CC == ISD::SETO) {
3688     CondCode = ARMCC::VS;
3689     swpVselOps = true;
3690   }
3691
3692   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3693   // code and swap the VSEL operands.
3694   if (CC == ISD::SETUNE) {
3695     CondCode = ARMCC::EQ;
3696     swpVselOps = true;
3697   }
3698 }
3699
3700 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
3701                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3702                                    SDValue Cmp, SelectionDAG &DAG) const {
3703   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3704     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3705                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3706     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3707                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3708
3709     SDValue TrueLow = TrueVal.getValue(0);
3710     SDValue TrueHigh = TrueVal.getValue(1);
3711     SDValue FalseLow = FalseVal.getValue(0);
3712     SDValue FalseHigh = FalseVal.getValue(1);
3713
3714     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3715                               ARMcc, CCR, Cmp);
3716     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3717                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3718
3719     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3720   } else {
3721     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3722                        Cmp);
3723   }
3724 }
3725
3726 static bool isGTorGE(ISD::CondCode CC) {
3727   return CC == ISD::SETGT || CC == ISD::SETGE;
3728 }
3729
3730 static bool isLTorLE(ISD::CondCode CC) {
3731   return CC == ISD::SETLT || CC == ISD::SETLE;
3732 }
3733
3734 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
3735 // All of these conditions (and their <= and >= counterparts) will do:
3736 //          x < k ? k : x
3737 //          x > k ? x : k
3738 //          k < x ? x : k
3739 //          k > x ? k : x
3740 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
3741                             const SDValue TrueVal, const SDValue FalseVal,
3742                             const ISD::CondCode CC, const SDValue K) {
3743   return (isGTorGE(CC) &&
3744           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
3745          (isLTorLE(CC) &&
3746           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
3747 }
3748
3749 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
3750 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
3751                             const SDValue TrueVal, const SDValue FalseVal,
3752                             const ISD::CondCode CC, const SDValue K) {
3753   return (isGTorGE(CC) &&
3754           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
3755          (isLTorLE(CC) &&
3756           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
3757 }
3758
3759 // Check if two chained conditionals could be converted into SSAT.
3760 //
3761 // SSAT can replace a set of two conditional selectors that bound a number to an
3762 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
3763 //
3764 //     x < -k ? -k : (x > k ? k : x)
3765 //     x < -k ? -k : (x < k ? x : k)
3766 //     x > -k ? (x > k ? k : x) : -k
3767 //     x < k ? (x < -k ? -k : x) : k
3768 //     etc.
3769 //
3770 // It returns true if the conversion can be done, false otherwise.
3771 // Additionally, the variable is returned in parameter V and the constant in K.
3772 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
3773                                     uint64_t &K) {
3774
3775   SDValue LHS1 = Op.getOperand(0);
3776   SDValue RHS1 = Op.getOperand(1);
3777   SDValue TrueVal1 = Op.getOperand(2);
3778   SDValue FalseVal1 = Op.getOperand(3);
3779   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3780
3781   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
3782   if (Op2.getOpcode() != ISD::SELECT_CC)
3783     return false;
3784
3785   SDValue LHS2 = Op2.getOperand(0);
3786   SDValue RHS2 = Op2.getOperand(1);
3787   SDValue TrueVal2 = Op2.getOperand(2);
3788   SDValue FalseVal2 = Op2.getOperand(3);
3789   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
3790
3791   // Find out which are the constants and which are the variables
3792   // in each conditional
3793   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
3794                                                         ? &RHS1
3795                                                         : NULL;
3796   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
3797                                                         ? &RHS2
3798                                                         : NULL;
3799   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
3800   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
3801   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
3802   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
3803
3804   // We must detect cases where the original operations worked with 16- or
3805   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
3806   // must work with sign-extended values but the select operations return
3807   // the original non-extended value.
3808   SDValue V2TmpReg = V2Tmp;
3809   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
3810     V2TmpReg = V2Tmp->getOperand(0);
3811
3812   // Check that the registers and the constants have the correct values
3813   // in both conditionals
3814   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
3815       V2TmpReg != V2)
3816     return false;
3817
3818   // Figure out which conditional is saturating the lower/upper bound.
3819   const SDValue *LowerCheckOp =
3820       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
3821           ? &Op
3822           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
3823                                                                        : NULL;
3824   const SDValue *UpperCheckOp =
3825       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
3826           ? &Op
3827           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
3828                                                                        : NULL;
3829
3830   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
3831     return false;
3832
3833   // Check that the constant in the lower-bound check is
3834   // the opposite of the constant in the upper-bound check
3835   // in 1's complement.
3836   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
3837   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
3838   int64_t PosVal = std::max(Val1, Val2);
3839
3840   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
3841        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
3842       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
3843
3844     V = V2;
3845     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
3846     return true;
3847   }
3848
3849   return false;
3850 }
3851
3852 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3853
3854   EVT VT = Op.getValueType();
3855   SDLoc dl(Op);
3856
3857   // Try to convert two saturating conditional selects into a single SSAT
3858   SDValue SatValue;
3859   uint64_t SatConstant;
3860   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
3861       isSaturatingConditional(Op, SatValue, SatConstant))
3862     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
3863                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
3864
3865   SDValue LHS = Op.getOperand(0);
3866   SDValue RHS = Op.getOperand(1);
3867   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3868   SDValue TrueVal = Op.getOperand(2);
3869   SDValue FalseVal = Op.getOperand(3);
3870
3871   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3872     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3873                                                     dl);
3874
3875     // If softenSetCCOperands only returned one value, we should compare it to
3876     // zero.
3877     if (!RHS.getNode()) {
3878       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3879       CC = ISD::SETNE;
3880     }
3881   }
3882
3883   if (LHS.getValueType() == MVT::i32) {
3884     // Try to generate VSEL on ARMv8.
3885     // The VSEL instruction can't use all the usual ARM condition
3886     // codes: it only has two bits to select the condition code, so it's
3887     // constrained to use only GE, GT, VS and EQ.
3888     //
3889     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3890     // swap the operands of the previous compare instruction (effectively
3891     // inverting the compare condition, swapping 'less' and 'greater') and
3892     // sometimes need to swap the operands to the VSEL (which inverts the
3893     // condition in the sense of firing whenever the previous condition didn't)
3894     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3895                                     TrueVal.getValueType() == MVT::f64)) {
3896       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3897       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3898           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3899         CC = ISD::getSetCCInverse(CC, true);
3900         std::swap(TrueVal, FalseVal);
3901       }
3902     }
3903
3904     SDValue ARMcc;
3905     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3906     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3907     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3908   }
3909
3910   ARMCC::CondCodes CondCode, CondCode2;
3911   FPCCToARMCC(CC, CondCode, CondCode2);
3912
3913   // Try to generate VMAXNM/VMINNM on ARMv8.
3914   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3915                                   TrueVal.getValueType() == MVT::f64)) {
3916     bool swpCmpOps = false;
3917     bool swpVselOps = false;
3918     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3919
3920     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3921         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3922       if (swpCmpOps)
3923         std::swap(LHS, RHS);
3924       if (swpVselOps)
3925         std::swap(TrueVal, FalseVal);
3926     }
3927   }
3928
3929   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3930   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3931   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3932   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3933   if (CondCode2 != ARMCC::AL) {
3934     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3935     // FIXME: Needs another CMP because flag can have but one use.
3936     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3937     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3938   }
3939   return Result;
3940 }
3941
3942 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3943 /// to morph to an integer compare sequence.
3944 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3945                            const ARMSubtarget *Subtarget) {
3946   SDNode *N = Op.getNode();
3947   if (!N->hasOneUse())
3948     // Otherwise it requires moving the value from fp to integer registers.
3949     return false;
3950   if (!N->getNumValues())
3951     return false;
3952   EVT VT = Op.getValueType();
3953   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3954     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3955     // vmrs are very slow, e.g. cortex-a8.
3956     return false;
3957
3958   if (isFloatingPointZero(Op)) {
3959     SeenZero = true;
3960     return true;
3961   }
3962   return ISD::isNormalLoad(N);
3963 }
3964
3965 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3966   if (isFloatingPointZero(Op))
3967     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3968
3969   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3970     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
3971                        Ld->getPointerInfo(), Ld->getAlignment(),
3972                        Ld->getMemOperand()->getFlags());
3973
3974   llvm_unreachable("Unknown VFP cmp argument!");
3975 }
3976
3977 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3978                            SDValue &RetVal1, SDValue &RetVal2) {
3979   SDLoc dl(Op);
3980
3981   if (isFloatingPointZero(Op)) {
3982     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3983     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3984     return;
3985   }
3986
3987   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3988     SDValue Ptr = Ld->getBasePtr();
3989     RetVal1 =
3990         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
3991                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
3992
3993     EVT PtrType = Ptr.getValueType();
3994     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3995     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3996                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3997     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
3998                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
3999                           Ld->getMemOperand()->getFlags());
4000     return;
4001   }
4002
4003   llvm_unreachable("Unknown VFP cmp argument!");
4004 }
4005
4006 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4007 /// f32 and even f64 comparisons to integer ones.
4008 SDValue
4009 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4010   SDValue Chain = Op.getOperand(0);
4011   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4012   SDValue LHS = Op.getOperand(2);
4013   SDValue RHS = Op.getOperand(3);
4014   SDValue Dest = Op.getOperand(4);
4015   SDLoc dl(Op);
4016
4017   bool LHSSeenZero = false;
4018   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4019   bool RHSSeenZero = false;
4020   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4021   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4022     // If unsafe fp math optimization is enabled and there are no other uses of
4023     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4024     // to an integer comparison.
4025     if (CC == ISD::SETOEQ)
4026       CC = ISD::SETEQ;
4027     else if (CC == ISD::SETUNE)
4028       CC = ISD::SETNE;
4029
4030     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4031     SDValue ARMcc;
4032     if (LHS.getValueType() == MVT::f32) {
4033       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4034                         bitcastf32Toi32(LHS, DAG), Mask);
4035       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4036                         bitcastf32Toi32(RHS, DAG), Mask);
4037       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4038       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4039       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4040                          Chain, Dest, ARMcc, CCR, Cmp);
4041     }
4042
4043     SDValue LHS1, LHS2;
4044     SDValue RHS1, RHS2;
4045     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4046     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4047     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4048     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4049     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4050     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4051     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4052     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4053     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4054   }
4055
4056   return SDValue();
4057 }
4058
4059 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4060   SDValue Chain = Op.getOperand(0);
4061   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4062   SDValue LHS = Op.getOperand(2);
4063   SDValue RHS = Op.getOperand(3);
4064   SDValue Dest = Op.getOperand(4);
4065   SDLoc dl(Op);
4066
4067   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4068     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4069                                                     dl);
4070
4071     // If softenSetCCOperands only returned one value, we should compare it to
4072     // zero.
4073     if (!RHS.getNode()) {
4074       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4075       CC = ISD::SETNE;
4076     }
4077   }
4078
4079   if (LHS.getValueType() == MVT::i32) {
4080     SDValue ARMcc;
4081     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4082     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4083     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4084                        Chain, Dest, ARMcc, CCR, Cmp);
4085   }
4086
4087   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4088
4089   if (getTargetMachine().Options.UnsafeFPMath &&
4090       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4091        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4092     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4093       return Result;
4094   }
4095
4096   ARMCC::CondCodes CondCode, CondCode2;
4097   FPCCToARMCC(CC, CondCode, CondCode2);
4098
4099   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4100   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4101   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4102   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4103   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4104   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4105   if (CondCode2 != ARMCC::AL) {
4106     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4107     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4108     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4109   }
4110   return Res;
4111 }
4112
4113 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4114   SDValue Chain = Op.getOperand(0);
4115   SDValue Table = Op.getOperand(1);
4116   SDValue Index = Op.getOperand(2);
4117   SDLoc dl(Op);
4118
4119   EVT PTy = getPointerTy(DAG.getDataLayout());
4120   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4121   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4122   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4123   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4124   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4125   if (Subtarget->isThumb2()) {
4126     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4127     // which does another jump to the destination. This also makes it easier
4128     // to translate it to TBB / TBH later.
4129     // FIXME: This might not work if the function is extremely large.
4130     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4131                        Addr, Op.getOperand(2), JTI);
4132   }
4133   if (isPositionIndependent()) {
4134     Addr =
4135         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4136                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4137     Chain = Addr.getValue(1);
4138     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4139     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4140   } else {
4141     Addr =
4142         DAG.getLoad(PTy, dl, Chain, Addr,
4143                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4144     Chain = Addr.getValue(1);
4145     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4146   }
4147 }
4148
4149 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4150   EVT VT = Op.getValueType();
4151   SDLoc dl(Op);
4152
4153   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4154     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4155       return Op;
4156     return DAG.UnrollVectorOp(Op.getNode());
4157   }
4158
4159   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4160          "Invalid type for custom lowering!");
4161   if (VT != MVT::v4i16)
4162     return DAG.UnrollVectorOp(Op.getNode());
4163
4164   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4165   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4166 }
4167
4168 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4169   EVT VT = Op.getValueType();
4170   if (VT.isVector())
4171     return LowerVectorFP_TO_INT(Op, DAG);
4172   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4173     RTLIB::Libcall LC;
4174     if (Op.getOpcode() == ISD::FP_TO_SINT)
4175       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4176                               Op.getValueType());
4177     else
4178       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4179                               Op.getValueType());
4180     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4181                        /*isSigned*/ false, SDLoc(Op)).first;
4182   }
4183
4184   return Op;
4185 }
4186
4187 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4188   EVT VT = Op.getValueType();
4189   SDLoc dl(Op);
4190
4191   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4192     if (VT.getVectorElementType() == MVT::f32)
4193       return Op;
4194     return DAG.UnrollVectorOp(Op.getNode());
4195   }
4196
4197   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4198          "Invalid type for custom lowering!");
4199   if (VT != MVT::v4f32)
4200     return DAG.UnrollVectorOp(Op.getNode());
4201
4202   unsigned CastOpc;
4203   unsigned Opc;
4204   switch (Op.getOpcode()) {
4205   default: llvm_unreachable("Invalid opcode!");
4206   case ISD::SINT_TO_FP:
4207     CastOpc = ISD::SIGN_EXTEND;
4208     Opc = ISD::SINT_TO_FP;
4209     break;
4210   case ISD::UINT_TO_FP:
4211     CastOpc = ISD::ZERO_EXTEND;
4212     Opc = ISD::UINT_TO_FP;
4213     break;
4214   }
4215
4216   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4217   return DAG.getNode(Opc, dl, VT, Op);
4218 }
4219
4220 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4221   EVT VT = Op.getValueType();
4222   if (VT.isVector())
4223     return LowerVectorINT_TO_FP(Op, DAG);
4224   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4225     RTLIB::Libcall LC;
4226     if (Op.getOpcode() == ISD::SINT_TO_FP)
4227       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4228                               Op.getValueType());
4229     else
4230       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4231                               Op.getValueType());
4232     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4233                        /*isSigned*/ false, SDLoc(Op)).first;
4234   }
4235
4236   return Op;
4237 }
4238
4239 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4240   // Implement fcopysign with a fabs and a conditional fneg.
4241   SDValue Tmp0 = Op.getOperand(0);
4242   SDValue Tmp1 = Op.getOperand(1);
4243   SDLoc dl(Op);
4244   EVT VT = Op.getValueType();
4245   EVT SrcVT = Tmp1.getValueType();
4246   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4247     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4248   bool UseNEON = !InGPR && Subtarget->hasNEON();
4249
4250   if (UseNEON) {
4251     // Use VBSL to copy the sign bit.
4252     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4253     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4254                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4255     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4256     if (VT == MVT::f64)
4257       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4258                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4259                          DAG.getConstant(32, dl, MVT::i32));
4260     else /*if (VT == MVT::f32)*/
4261       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4262     if (SrcVT == MVT::f32) {
4263       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4264       if (VT == MVT::f64)
4265         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4266                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4267                            DAG.getConstant(32, dl, MVT::i32));
4268     } else if (VT == MVT::f32)
4269       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4270                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4271                          DAG.getConstant(32, dl, MVT::i32));
4272     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4273     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4274
4275     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4276                                             dl, MVT::i32);
4277     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4278     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4279                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4280
4281     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4282                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4283                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4284     if (VT == MVT::f32) {
4285       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4286       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4287                         DAG.getConstant(0, dl, MVT::i32));
4288     } else {
4289       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4290     }
4291
4292     return Res;
4293   }
4294
4295   // Bitcast operand 1 to i32.
4296   if (SrcVT == MVT::f64)
4297     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4298                        Tmp1).getValue(1);
4299   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4300
4301   // Or in the signbit with integer operations.
4302   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4303   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4304   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4305   if (VT == MVT::f32) {
4306     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4307                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4308     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4309                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4310   }
4311
4312   // f64: Or the high part with signbit and then combine two parts.
4313   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4314                      Tmp0);
4315   SDValue Lo = Tmp0.getValue(0);
4316   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4317   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4318   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4319 }
4320
4321 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4322   MachineFunction &MF = DAG.getMachineFunction();
4323   MachineFrameInfo *MFI = MF.getFrameInfo();
4324   MFI->setReturnAddressIsTaken(true);
4325
4326   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4327     return SDValue();
4328
4329   EVT VT = Op.getValueType();
4330   SDLoc dl(Op);
4331   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4332   if (Depth) {
4333     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4334     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4335     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4336                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4337                        MachinePointerInfo());
4338   }
4339
4340   // Return LR, which contains the return address. Mark it an implicit live-in.
4341   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4342   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4343 }
4344
4345 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4346   const ARMBaseRegisterInfo &ARI =
4347     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4348   MachineFunction &MF = DAG.getMachineFunction();
4349   MachineFrameInfo *MFI = MF.getFrameInfo();
4350   MFI->setFrameAddressIsTaken(true);
4351
4352   EVT VT = Op.getValueType();
4353   SDLoc dl(Op);  // FIXME probably not meaningful
4354   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4355   unsigned FrameReg = ARI.getFrameRegister(MF);
4356   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4357   while (Depth--)
4358     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4359                             MachinePointerInfo());
4360   return FrameAddr;
4361 }
4362
4363 // FIXME? Maybe this could be a TableGen attribute on some registers and
4364 // this table could be generated automatically from RegInfo.
4365 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4366                                               SelectionDAG &DAG) const {
4367   unsigned Reg = StringSwitch<unsigned>(RegName)
4368                        .Case("sp", ARM::SP)
4369                        .Default(0);
4370   if (Reg)
4371     return Reg;
4372   report_fatal_error(Twine("Invalid register name \""
4373                               + StringRef(RegName)  + "\"."));
4374 }
4375
4376 // Result is 64 bit value so split into two 32 bit values and return as a
4377 // pair of values.
4378 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4379                                 SelectionDAG &DAG) {
4380   SDLoc DL(N);
4381
4382   // This function is only supposed to be called for i64 type destination.
4383   assert(N->getValueType(0) == MVT::i64
4384           && "ExpandREAD_REGISTER called for non-i64 type result.");
4385
4386   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4387                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4388                              N->getOperand(0),
4389                              N->getOperand(1));
4390
4391   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4392                     Read.getValue(1)));
4393   Results.push_back(Read.getOperand(0));
4394 }
4395
4396 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4397 /// When \p DstVT, the destination type of \p BC, is on the vector
4398 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4399 /// it might be possible to combine them, such that everything stays on the
4400 /// vector register bank.
4401 /// \p return The node that would replace \p BT, if the combine
4402 /// is possible.
4403 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4404                                                 SelectionDAG &DAG) {
4405   SDValue Op = BC->getOperand(0);
4406   EVT DstVT = BC->getValueType(0);
4407
4408   // The only vector instruction that can produce a scalar (remember,
4409   // since the bitcast was about to be turned into VMOVDRR, the source
4410   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4411   // Moreover, we can do this combine only if there is one use.
4412   // Finally, if the destination type is not a vector, there is not
4413   // much point on forcing everything on the vector bank.
4414   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4415       !Op.hasOneUse())
4416     return SDValue();
4417
4418   // If the index is not constant, we will introduce an additional
4419   // multiply that will stick.
4420   // Give up in that case.
4421   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4422   if (!Index)
4423     return SDValue();
4424   unsigned DstNumElt = DstVT.getVectorNumElements();
4425
4426   // Compute the new index.
4427   const APInt &APIntIndex = Index->getAPIntValue();
4428   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4429   NewIndex *= APIntIndex;
4430   // Check if the new constant index fits into i32.
4431   if (NewIndex.getBitWidth() > 32)
4432     return SDValue();
4433
4434   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4435   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4436   SDLoc dl(Op);
4437   SDValue ExtractSrc = Op.getOperand(0);
4438   EVT VecVT = EVT::getVectorVT(
4439       *DAG.getContext(), DstVT.getScalarType(),
4440       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4441   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4442   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4443                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4444 }
4445
4446 /// ExpandBITCAST - If the target supports VFP, this function is called to
4447 /// expand a bit convert where either the source or destination type is i64 to
4448 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4449 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4450 /// vectors), since the legalizer won't know what to do with that.
4451 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4453   SDLoc dl(N);
4454   SDValue Op = N->getOperand(0);
4455
4456   // This function is only supposed to be called for i64 types, either as the
4457   // source or destination of the bit convert.
4458   EVT SrcVT = Op.getValueType();
4459   EVT DstVT = N->getValueType(0);
4460   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4461          "ExpandBITCAST called for non-i64 type");
4462
4463   // Turn i64->f64 into VMOVDRR.
4464   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4465     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4466     // if we can combine the bitcast with its source.
4467     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4468       return Val;
4469
4470     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4471                              DAG.getConstant(0, dl, MVT::i32));
4472     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4473                              DAG.getConstant(1, dl, MVT::i32));
4474     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4475                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4476   }
4477
4478   // Turn f64->i64 into VMOVRRD.
4479   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4480     SDValue Cvt;
4481     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4482         SrcVT.getVectorNumElements() > 1)
4483       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4484                         DAG.getVTList(MVT::i32, MVT::i32),
4485                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4486     else
4487       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4488                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4489     // Merge the pieces into a single i64 value.
4490     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4491   }
4492
4493   return SDValue();
4494 }
4495
4496 /// getZeroVector - Returns a vector of specified type with all zero elements.
4497 /// Zero vectors are used to represent vector negation and in those cases
4498 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4499 /// not support i64 elements, so sometimes the zero vectors will need to be
4500 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4501 /// zero vector.
4502 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4503   assert(VT.isVector() && "Expected a vector type");
4504   // The canonical modified immediate encoding of a zero vector is....0!
4505   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4506   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4507   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4508   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4509 }
4510
4511 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4512 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4513 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4514                                                 SelectionDAG &DAG) const {
4515   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4516   EVT VT = Op.getValueType();
4517   unsigned VTBits = VT.getSizeInBits();
4518   SDLoc dl(Op);
4519   SDValue ShOpLo = Op.getOperand(0);
4520   SDValue ShOpHi = Op.getOperand(1);
4521   SDValue ShAmt  = Op.getOperand(2);
4522   SDValue ARMcc;
4523   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4524
4525   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4526
4527   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4528                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4529   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4530   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4531                                    DAG.getConstant(VTBits, dl, MVT::i32));
4532   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4533   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4534   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4535
4536   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4537   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4538                           ISD::SETGE, ARMcc, DAG, dl);
4539   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4540   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4541                            CCR, Cmp);
4542
4543   SDValue Ops[2] = { Lo, Hi };
4544   return DAG.getMergeValues(Ops, dl);
4545 }
4546
4547 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4548 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4549 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4550                                                SelectionDAG &DAG) const {
4551   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4552   EVT VT = Op.getValueType();
4553   unsigned VTBits = VT.getSizeInBits();
4554   SDLoc dl(Op);
4555   SDValue ShOpLo = Op.getOperand(0);
4556   SDValue ShOpHi = Op.getOperand(1);
4557   SDValue ShAmt  = Op.getOperand(2);
4558   SDValue ARMcc;
4559
4560   assert(Op.getOpcode() == ISD::SHL_PARTS);
4561   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4562                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4563   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4564   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4565                                    DAG.getConstant(VTBits, dl, MVT::i32));
4566   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4567   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4568
4569   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4570   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4571   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4572                           ISD::SETGE, ARMcc, DAG, dl);
4573   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4574   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4575                            CCR, Cmp);
4576
4577   SDValue Ops[2] = { Lo, Hi };
4578   return DAG.getMergeValues(Ops, dl);
4579 }
4580
4581 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4582                                             SelectionDAG &DAG) const {
4583   // The rounding mode is in bits 23:22 of the FPSCR.
4584   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4585   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4586   // so that the shift + and get folded into a bitfield extract.
4587   SDLoc dl(Op);
4588   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4589                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4590                                               MVT::i32));
4591   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4592                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4593   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4594                               DAG.getConstant(22, dl, MVT::i32));
4595   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4596                      DAG.getConstant(3, dl, MVT::i32));
4597 }
4598
4599 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4600                          const ARMSubtarget *ST) {
4601   SDLoc dl(N);
4602   EVT VT = N->getValueType(0);
4603   if (VT.isVector()) {
4604     assert(ST->hasNEON());
4605
4606     // Compute the least significant set bit: LSB = X & -X
4607     SDValue X = N->getOperand(0);
4608     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4609     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4610
4611     EVT ElemTy = VT.getVectorElementType();
4612
4613     if (ElemTy == MVT::i8) {
4614       // Compute with: cttz(x) = ctpop(lsb - 1)
4615       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4616                                 DAG.getTargetConstant(1, dl, ElemTy));
4617       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4618       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4619     }
4620
4621     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4622         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4623       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4624       unsigned NumBits = ElemTy.getSizeInBits();
4625       SDValue WidthMinus1 =
4626           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4627                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4628       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4629       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4630     }
4631
4632     // Compute with: cttz(x) = ctpop(lsb - 1)
4633
4634     // Since we can only compute the number of bits in a byte with vcnt.8, we
4635     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4636     // and i64.
4637
4638     // Compute LSB - 1.
4639     SDValue Bits;
4640     if (ElemTy == MVT::i64) {
4641       // Load constant 0xffff'ffff'ffff'ffff to register.
4642       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4643                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4644       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4645     } else {
4646       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4647                                 DAG.getTargetConstant(1, dl, ElemTy));
4648       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4649     }
4650
4651     // Count #bits with vcnt.8.
4652     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4653     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4654     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4655
4656     // Gather the #bits with vpaddl (pairwise add.)
4657     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4658     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4659         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4660         Cnt8);
4661     if (ElemTy == MVT::i16)
4662       return Cnt16;
4663
4664     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4665     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4666         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4667         Cnt16);
4668     if (ElemTy == MVT::i32)
4669       return Cnt32;
4670
4671     assert(ElemTy == MVT::i64);
4672     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4673         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4674         Cnt32);
4675     return Cnt64;
4676   }
4677
4678   if (!ST->hasV6T2Ops())
4679     return SDValue();
4680
4681   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
4682   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4683 }
4684
4685 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4686 /// for each 16-bit element from operand, repeated.  The basic idea is to
4687 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4688 ///
4689 /// Trace for v4i16:
4690 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4691 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4692 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4693 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4694 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4695 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4696 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4697 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4698 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4699   EVT VT = N->getValueType(0);
4700   SDLoc DL(N);
4701
4702   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4703   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4704   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4705   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4706   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4707   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4708 }
4709
4710 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4711 /// bit-count for each 16-bit element from the operand.  We need slightly
4712 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4713 /// 64/128-bit registers.
4714 ///
4715 /// Trace for v4i16:
4716 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4717 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4718 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4719 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4720 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4721   EVT VT = N->getValueType(0);
4722   SDLoc DL(N);
4723
4724   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4725   if (VT.is64BitVector()) {
4726     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4727     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4728                        DAG.getIntPtrConstant(0, DL));
4729   } else {
4730     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4731                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4732     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4733   }
4734 }
4735
4736 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4737 /// bit-count for each 32-bit element from the operand.  The idea here is
4738 /// to split the vector into 16-bit elements, leverage the 16-bit count
4739 /// routine, and then combine the results.
4740 ///
4741 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4742 /// input    = [v0    v1    ] (vi: 32-bit elements)
4743 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4744 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4745 /// vrev: N0 = [k1 k0 k3 k2 ]
4746 ///            [k0 k1 k2 k3 ]
4747 ///       N1 =+[k1 k0 k3 k2 ]
4748 ///            [k0 k2 k1 k3 ]
4749 ///       N2 =+[k1 k3 k0 k2 ]
4750 ///            [k0    k2    k1    k3    ]
4751 /// Extended =+[k1    k3    k0    k2    ]
4752 ///            [k0    k2    ]
4753 /// Extracted=+[k1    k3    ]
4754 ///
4755 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4756   EVT VT = N->getValueType(0);
4757   SDLoc DL(N);
4758
4759   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4760
4761   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4762   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4763   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4764   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4765   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4766
4767   if (VT.is64BitVector()) {
4768     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4769     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4770                        DAG.getIntPtrConstant(0, DL));
4771   } else {
4772     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4773                                     DAG.getIntPtrConstant(0, DL));
4774     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4775   }
4776 }
4777
4778 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4779                           const ARMSubtarget *ST) {
4780   EVT VT = N->getValueType(0);
4781
4782   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4783   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4784           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4785          "Unexpected type for custom ctpop lowering");
4786
4787   if (VT.getVectorElementType() == MVT::i32)
4788     return lowerCTPOP32BitElements(N, DAG);
4789   else
4790     return lowerCTPOP16BitElements(N, DAG);
4791 }
4792
4793 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4794                           const ARMSubtarget *ST) {
4795   EVT VT = N->getValueType(0);
4796   SDLoc dl(N);
4797
4798   if (!VT.isVector())
4799     return SDValue();
4800
4801   // Lower vector shifts on NEON to use VSHL.
4802   assert(ST->hasNEON() && "unexpected vector shift");
4803
4804   // Left shifts translate directly to the vshiftu intrinsic.
4805   if (N->getOpcode() == ISD::SHL)
4806     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4807                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4808                                        MVT::i32),
4809                        N->getOperand(0), N->getOperand(1));
4810
4811   assert((N->getOpcode() == ISD::SRA ||
4812           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4813
4814   // NEON uses the same intrinsics for both left and right shifts.  For
4815   // right shifts, the shift amounts are negative, so negate the vector of
4816   // shift amounts.
4817   EVT ShiftVT = N->getOperand(1).getValueType();
4818   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4819                                      getZeroVector(ShiftVT, DAG, dl),
4820                                      N->getOperand(1));
4821   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4822                              Intrinsic::arm_neon_vshifts :
4823                              Intrinsic::arm_neon_vshiftu);
4824   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4825                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4826                      N->getOperand(0), NegatedCount);
4827 }
4828
4829 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4830                                 const ARMSubtarget *ST) {
4831   EVT VT = N->getValueType(0);
4832   SDLoc dl(N);
4833
4834   // We can get here for a node like i32 = ISD::SHL i32, i64
4835   if (VT != MVT::i64)
4836     return SDValue();
4837
4838   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4839          "Unknown shift to lower!");
4840
4841   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4842   if (!isOneConstant(N->getOperand(1)))
4843     return SDValue();
4844
4845   // If we are in thumb mode, we don't have RRX.
4846   if (ST->isThumb1Only()) return SDValue();
4847
4848   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4849   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4850                            DAG.getConstant(0, dl, MVT::i32));
4851   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4852                            DAG.getConstant(1, dl, MVT::i32));
4853
4854   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4855   // captures the result into a carry flag.
4856   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4857   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4858
4859   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4860   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4861
4862   // Merge the pieces into a single i64 value.
4863  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4864 }
4865
4866 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4867   SDValue TmpOp0, TmpOp1;
4868   bool Invert = false;
4869   bool Swap = false;
4870   unsigned Opc = 0;
4871
4872   SDValue Op0 = Op.getOperand(0);
4873   SDValue Op1 = Op.getOperand(1);
4874   SDValue CC = Op.getOperand(2);
4875   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4876   EVT VT = Op.getValueType();
4877   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4878   SDLoc dl(Op);
4879
4880   if (CmpVT.getVectorElementType() == MVT::i64)
4881     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4882     // but it's possible that our operands are 64-bit but our result is 32-bit.
4883     // Bail in this case.
4884     return SDValue();
4885
4886   if (Op1.getValueType().isFloatingPoint()) {
4887     switch (SetCCOpcode) {
4888     default: llvm_unreachable("Illegal FP comparison");
4889     case ISD::SETUNE:
4890     case ISD::SETNE:  Invert = true; // Fallthrough
4891     case ISD::SETOEQ:
4892     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4893     case ISD::SETOLT:
4894     case ISD::SETLT: Swap = true; // Fallthrough
4895     case ISD::SETOGT:
4896     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4897     case ISD::SETOLE:
4898     case ISD::SETLE:  Swap = true; // Fallthrough
4899     case ISD::SETOGE:
4900     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4901     case ISD::SETUGE: Swap = true; // Fallthrough
4902     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4903     case ISD::SETUGT: Swap = true; // Fallthrough
4904     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4905     case ISD::SETUEQ: Invert = true; // Fallthrough
4906     case ISD::SETONE:
4907       // Expand this to (OLT | OGT).
4908       TmpOp0 = Op0;
4909       TmpOp1 = Op1;
4910       Opc = ISD::OR;
4911       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4912       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4913       break;
4914     case ISD::SETUO: Invert = true; // Fallthrough
4915     case ISD::SETO:
4916       // Expand this to (OLT | OGE).
4917       TmpOp0 = Op0;
4918       TmpOp1 = Op1;
4919       Opc = ISD::OR;
4920       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4921       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4922       break;
4923     }
4924   } else {
4925     // Integer comparisons.
4926     switch (SetCCOpcode) {
4927     default: llvm_unreachable("Illegal integer comparison");
4928     case ISD::SETNE:  Invert = true;
4929     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4930     case ISD::SETLT:  Swap = true;
4931     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4932     case ISD::SETLE:  Swap = true;
4933     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4934     case ISD::SETULT: Swap = true;
4935     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4936     case ISD::SETULE: Swap = true;
4937     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4938     }
4939
4940     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4941     if (Opc == ARMISD::VCEQ) {
4942
4943       SDValue AndOp;
4944       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4945         AndOp = Op0;
4946       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4947         AndOp = Op1;
4948
4949       // Ignore bitconvert.
4950       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4951         AndOp = AndOp.getOperand(0);
4952
4953       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4954         Opc = ARMISD::VTST;
4955         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4956         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4957         Invert = !Invert;
4958       }
4959     }
4960   }
4961
4962   if (Swap)
4963     std::swap(Op0, Op1);
4964
4965   // If one of the operands is a constant vector zero, attempt to fold the
4966   // comparison to a specialized compare-against-zero form.
4967   SDValue SingleOp;
4968   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4969     SingleOp = Op0;
4970   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4971     if (Opc == ARMISD::VCGE)
4972       Opc = ARMISD::VCLEZ;
4973     else if (Opc == ARMISD::VCGT)
4974       Opc = ARMISD::VCLTZ;
4975     SingleOp = Op1;
4976   }
4977
4978   SDValue Result;
4979   if (SingleOp.getNode()) {
4980     switch (Opc) {
4981     case ARMISD::VCEQ:
4982       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4983     case ARMISD::VCGE:
4984       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4985     case ARMISD::VCLEZ:
4986       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4987     case ARMISD::VCGT:
4988       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4989     case ARMISD::VCLTZ:
4990       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4991     default:
4992       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4993     }
4994   } else {
4995      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4996   }
4997
4998   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4999
5000   if (Invert)
5001     Result = DAG.getNOT(dl, Result, VT);
5002
5003   return Result;
5004 }
5005
5006 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5007   SDValue LHS = Op.getOperand(0);
5008   SDValue RHS = Op.getOperand(1);
5009   SDValue Carry = Op.getOperand(2);
5010   SDValue Cond = Op.getOperand(3);
5011   SDLoc DL(Op);
5012
5013   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5014
5015   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5016   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5017   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5018
5019   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5020   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5021   SDValue ARMcc = DAG.getConstant(
5022       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5023   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5024   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5025                                    Cmp.getValue(1), SDValue());
5026   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5027                      CCR, Chain.getValue(1));
5028 }
5029
5030 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5031 /// valid vector constant for a NEON instruction with a "modified immediate"
5032 /// operand (e.g., VMOV).  If so, return the encoded value.
5033 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5034                                  unsigned SplatBitSize, SelectionDAG &DAG,
5035                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5036                                  NEONModImmType type) {
5037   unsigned OpCmode, Imm;
5038
5039   // SplatBitSize is set to the smallest size that splats the vector, so a
5040   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5041   // immediate instructions others than VMOV do not support the 8-bit encoding
5042   // of a zero vector, and the default encoding of zero is supposed to be the
5043   // 32-bit version.
5044   if (SplatBits == 0)
5045     SplatBitSize = 32;
5046
5047   switch (SplatBitSize) {
5048   case 8:
5049     if (type != VMOVModImm)
5050       return SDValue();
5051     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5052     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5053     OpCmode = 0xe;
5054     Imm = SplatBits;
5055     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5056     break;
5057
5058   case 16:
5059     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5060     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5061     if ((SplatBits & ~0xff) == 0) {
5062       // Value = 0x00nn: Op=x, Cmode=100x.
5063       OpCmode = 0x8;
5064       Imm = SplatBits;
5065       break;
5066     }
5067     if ((SplatBits & ~0xff00) == 0) {
5068       // Value = 0xnn00: Op=x, Cmode=101x.
5069       OpCmode = 0xa;
5070       Imm = SplatBits >> 8;
5071       break;
5072     }
5073     return SDValue();
5074
5075   case 32:
5076     // NEON's 32-bit VMOV supports splat values where:
5077     // * only one byte is nonzero, or
5078     // * the least significant byte is 0xff and the second byte is nonzero, or
5079     // * the least significant 2 bytes are 0xff and the third is nonzero.
5080     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5081     if ((SplatBits & ~0xff) == 0) {
5082       // Value = 0x000000nn: Op=x, Cmode=000x.
5083       OpCmode = 0;
5084       Imm = SplatBits;
5085       break;
5086     }
5087     if ((SplatBits & ~0xff00) == 0) {
5088       // Value = 0x0000nn00: Op=x, Cmode=001x.
5089       OpCmode = 0x2;
5090       Imm = SplatBits >> 8;
5091       break;
5092     }
5093     if ((SplatBits & ~0xff0000) == 0) {
5094       // Value = 0x00nn0000: Op=x, Cmode=010x.
5095       OpCmode = 0x4;
5096       Imm = SplatBits >> 16;
5097       break;
5098     }
5099     if ((SplatBits & ~0xff000000) == 0) {
5100       // Value = 0xnn000000: Op=x, Cmode=011x.
5101       OpCmode = 0x6;
5102       Imm = SplatBits >> 24;
5103       break;
5104     }
5105
5106     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5107     if (type == OtherModImm) return SDValue();
5108
5109     if ((SplatBits & ~0xffff) == 0 &&
5110         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5111       // Value = 0x0000nnff: Op=x, Cmode=1100.
5112       OpCmode = 0xc;
5113       Imm = SplatBits >> 8;
5114       break;
5115     }
5116
5117     if ((SplatBits & ~0xffffff) == 0 &&
5118         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5119       // Value = 0x00nnffff: Op=x, Cmode=1101.
5120       OpCmode = 0xd;
5121       Imm = SplatBits >> 16;
5122       break;
5123     }
5124
5125     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5126     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5127     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5128     // and fall through here to test for a valid 64-bit splat.  But, then the
5129     // caller would also need to check and handle the change in size.
5130     return SDValue();
5131
5132   case 64: {
5133     if (type != VMOVModImm)
5134       return SDValue();
5135     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5136     uint64_t BitMask = 0xff;
5137     uint64_t Val = 0;
5138     unsigned ImmMask = 1;
5139     Imm = 0;
5140     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5141       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5142         Val |= BitMask;
5143         Imm |= ImmMask;
5144       } else if ((SplatBits & BitMask) != 0) {
5145         return SDValue();
5146       }
5147       BitMask <<= 8;
5148       ImmMask <<= 1;
5149     }
5150
5151     if (DAG.getDataLayout().isBigEndian())
5152       // swap higher and lower 32 bit word
5153       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5154
5155     // Op=1, Cmode=1110.
5156     OpCmode = 0x1e;
5157     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5158     break;
5159   }
5160
5161   default:
5162     llvm_unreachable("unexpected size for isNEONModifiedImm");
5163   }
5164
5165   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5166   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5167 }
5168
5169 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5170                                            const ARMSubtarget *ST) const {
5171   if (!ST->hasVFP3())
5172     return SDValue();
5173
5174   bool IsDouble = Op.getValueType() == MVT::f64;
5175   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5176
5177   // Use the default (constant pool) lowering for double constants when we have
5178   // an SP-only FPU
5179   if (IsDouble && Subtarget->isFPOnlySP())
5180     return SDValue();
5181
5182   // Try splatting with a VMOV.f32...
5183   const APFloat &FPVal = CFP->getValueAPF();
5184   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5185
5186   if (ImmVal != -1) {
5187     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5188       // We have code in place to select a valid ConstantFP already, no need to
5189       // do any mangling.
5190       return Op;
5191     }
5192
5193     // It's a float and we are trying to use NEON operations where
5194     // possible. Lower it to a splat followed by an extract.
5195     SDLoc DL(Op);
5196     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5197     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5198                                       NewVal);
5199     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5200                        DAG.getConstant(0, DL, MVT::i32));
5201   }
5202
5203   // The rest of our options are NEON only, make sure that's allowed before
5204   // proceeding..
5205   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5206     return SDValue();
5207
5208   EVT VMovVT;
5209   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5210
5211   // It wouldn't really be worth bothering for doubles except for one very
5212   // important value, which does happen to match: 0.0. So make sure we don't do
5213   // anything stupid.
5214   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5215     return SDValue();
5216
5217   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5218   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5219                                      VMovVT, false, VMOVModImm);
5220   if (NewVal != SDValue()) {
5221     SDLoc DL(Op);
5222     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5223                                       NewVal);
5224     if (IsDouble)
5225       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5226
5227     // It's a float: cast and extract a vector element.
5228     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5229                                        VecConstant);
5230     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5231                        DAG.getConstant(0, DL, MVT::i32));
5232   }
5233
5234   // Finally, try a VMVN.i32
5235   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5236                              false, VMVNModImm);
5237   if (NewVal != SDValue()) {
5238     SDLoc DL(Op);
5239     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5240
5241     if (IsDouble)
5242       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5243
5244     // It's a float: cast and extract a vector element.
5245     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5246                                        VecConstant);
5247     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5248                        DAG.getConstant(0, DL, MVT::i32));
5249   }
5250
5251   return SDValue();
5252 }
5253
5254 // check if an VEXT instruction can handle the shuffle mask when the
5255 // vector sources of the shuffle are the same.
5256 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5257   unsigned NumElts = VT.getVectorNumElements();
5258
5259   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5260   if (M[0] < 0)
5261     return false;
5262
5263   Imm = M[0];
5264
5265   // If this is a VEXT shuffle, the immediate value is the index of the first
5266   // element.  The other shuffle indices must be the successive elements after
5267   // the first one.
5268   unsigned ExpectedElt = Imm;
5269   for (unsigned i = 1; i < NumElts; ++i) {
5270     // Increment the expected index.  If it wraps around, just follow it
5271     // back to index zero and keep going.
5272     ++ExpectedElt;
5273     if (ExpectedElt == NumElts)
5274       ExpectedElt = 0;
5275
5276     if (M[i] < 0) continue; // ignore UNDEF indices
5277     if (ExpectedElt != static_cast<unsigned>(M[i]))
5278       return false;
5279   }
5280
5281   return true;
5282 }
5283
5284
5285 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5286                        bool &ReverseVEXT, unsigned &Imm) {
5287   unsigned NumElts = VT.getVectorNumElements();
5288   ReverseVEXT = false;
5289
5290   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5291   if (M[0] < 0)
5292     return false;
5293
5294   Imm = M[0];
5295
5296   // If this is a VEXT shuffle, the immediate value is the index of the first
5297   // element.  The other shuffle indices must be the successive elements after
5298   // the first one.
5299   unsigned ExpectedElt = Imm;
5300   for (unsigned i = 1; i < NumElts; ++i) {
5301     // Increment the expected index.  If it wraps around, it may still be
5302     // a VEXT but the source vectors must be swapped.
5303     ExpectedElt += 1;
5304     if (ExpectedElt == NumElts * 2) {
5305       ExpectedElt = 0;
5306       ReverseVEXT = true;
5307     }
5308
5309     if (M[i] < 0) continue; // ignore UNDEF indices
5310     if (ExpectedElt != static_cast<unsigned>(M[i]))
5311       return false;
5312   }
5313
5314   // Adjust the index value if the source operands will be swapped.
5315   if (ReverseVEXT)
5316     Imm -= NumElts;
5317
5318   return true;
5319 }
5320
5321 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5322 /// instruction with the specified blocksize.  (The order of the elements
5323 /// within each block of the vector is reversed.)
5324 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5325   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5326          "Only possible block sizes for VREV are: 16, 32, 64");
5327
5328   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5329   if (EltSz == 64)
5330     return false;
5331
5332   unsigned NumElts = VT.getVectorNumElements();
5333   unsigned BlockElts = M[0] + 1;
5334   // If the first shuffle index is UNDEF, be optimistic.
5335   if (M[0] < 0)
5336     BlockElts = BlockSize / EltSz;
5337
5338   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5339     return false;
5340
5341   for (unsigned i = 0; i < NumElts; ++i) {
5342     if (M[i] < 0) continue; // ignore UNDEF indices
5343     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5344       return false;
5345   }
5346
5347   return true;
5348 }
5349
5350 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5351   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5352   // range, then 0 is placed into the resulting vector. So pretty much any mask
5353   // of 8 elements can work here.
5354   return VT == MVT::v8i8 && M.size() == 8;
5355 }
5356
5357 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5358 // checking that pairs of elements in the shuffle mask represent the same index
5359 // in each vector, incrementing the expected index by 2 at each step.
5360 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5361 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5362 //  v2={e,f,g,h}
5363 // WhichResult gives the offset for each element in the mask based on which
5364 // of the two results it belongs to.
5365 //
5366 // The transpose can be represented either as:
5367 // result1 = shufflevector v1, v2, result1_shuffle_mask
5368 // result2 = shufflevector v1, v2, result2_shuffle_mask
5369 // where v1/v2 and the shuffle masks have the same number of elements
5370 // (here WhichResult (see below) indicates which result is being checked)
5371 //
5372 // or as:
5373 // results = shufflevector v1, v2, shuffle_mask
5374 // where both results are returned in one vector and the shuffle mask has twice
5375 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5376 // want to check the low half and high half of the shuffle mask as if it were
5377 // the other case
5378 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5379   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5380   if (EltSz == 64)
5381     return false;
5382
5383   unsigned NumElts = VT.getVectorNumElements();
5384   if (M.size() != NumElts && M.size() != NumElts*2)
5385     return false;
5386
5387   // If the mask is twice as long as the input vector then we need to check the
5388   // upper and lower parts of the mask with a matching value for WhichResult
5389   // FIXME: A mask with only even values will be rejected in case the first
5390   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5391   // M[0] is used to determine WhichResult
5392   for (unsigned i = 0; i < M.size(); i += NumElts) {
5393     if (M.size() == NumElts * 2)
5394       WhichResult = i / NumElts;
5395     else
5396       WhichResult = M[i] == 0 ? 0 : 1;
5397     for (unsigned j = 0; j < NumElts; j += 2) {
5398       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5399           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5400         return false;
5401     }
5402   }
5403
5404   if (M.size() == NumElts*2)
5405     WhichResult = 0;
5406
5407   return true;
5408 }
5409
5410 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5411 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5412 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5413 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5414   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5415   if (EltSz == 64)
5416     return false;
5417
5418   unsigned NumElts = VT.getVectorNumElements();
5419   if (M.size() != NumElts && M.size() != NumElts*2)
5420     return false;
5421
5422   for (unsigned i = 0; i < M.size(); i += NumElts) {
5423     if (M.size() == NumElts * 2)
5424       WhichResult = i / NumElts;
5425     else
5426       WhichResult = M[i] == 0 ? 0 : 1;
5427     for (unsigned j = 0; j < NumElts; j += 2) {
5428       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5429           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5430         return false;
5431     }
5432   }
5433
5434   if (M.size() == NumElts*2)
5435     WhichResult = 0;
5436
5437   return true;
5438 }
5439
5440 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5441 // that the mask elements are either all even and in steps of size 2 or all odd
5442 // and in steps of size 2.
5443 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5444 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5445 //  v2={e,f,g,h}
5446 // Requires similar checks to that of isVTRNMask with
5447 // respect the how results are returned.
5448 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5449   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5450   if (EltSz == 64)
5451     return false;
5452
5453   unsigned NumElts = VT.getVectorNumElements();
5454   if (M.size() != NumElts && M.size() != NumElts*2)
5455     return false;
5456
5457   for (unsigned i = 0; i < M.size(); i += NumElts) {
5458     WhichResult = M[i] == 0 ? 0 : 1;
5459     for (unsigned j = 0; j < NumElts; ++j) {
5460       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5461         return false;
5462     }
5463   }
5464
5465   if (M.size() == NumElts*2)
5466     WhichResult = 0;
5467
5468   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5469   if (VT.is64BitVector() && EltSz == 32)
5470     return false;
5471
5472   return true;
5473 }
5474
5475 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5476 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5477 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5478 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5479   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5480   if (EltSz == 64)
5481     return false;
5482
5483   unsigned NumElts = VT.getVectorNumElements();
5484   if (M.size() != NumElts && M.size() != NumElts*2)
5485     return false;
5486
5487   unsigned Half = NumElts / 2;
5488   for (unsigned i = 0; i < M.size(); i += NumElts) {
5489     WhichResult = M[i] == 0 ? 0 : 1;
5490     for (unsigned j = 0; j < NumElts; j += Half) {
5491       unsigned Idx = WhichResult;
5492       for (unsigned k = 0; k < Half; ++k) {
5493         int MIdx = M[i + j + k];
5494         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5495           return false;
5496         Idx += 2;
5497       }
5498     }
5499   }
5500
5501   if (M.size() == NumElts*2)
5502     WhichResult = 0;
5503
5504   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5505   if (VT.is64BitVector() && EltSz == 32)
5506     return false;
5507
5508   return true;
5509 }
5510
5511 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5512 // that pairs of elements of the shufflemask represent the same index in each
5513 // vector incrementing sequentially through the vectors.
5514 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5515 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5516 //  v2={e,f,g,h}
5517 // Requires similar checks to that of isVTRNMask with respect the how results
5518 // are returned.
5519 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5520   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5521   if (EltSz == 64)
5522     return false;
5523
5524   unsigned NumElts = VT.getVectorNumElements();
5525   if (M.size() != NumElts && M.size() != NumElts*2)
5526     return false;
5527
5528   for (unsigned i = 0; i < M.size(); i += NumElts) {
5529     WhichResult = M[i] == 0 ? 0 : 1;
5530     unsigned Idx = WhichResult * NumElts / 2;
5531     for (unsigned j = 0; j < NumElts; j += 2) {
5532       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5533           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5534         return false;
5535       Idx += 1;
5536     }
5537   }
5538
5539   if (M.size() == NumElts*2)
5540     WhichResult = 0;
5541
5542   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5543   if (VT.is64BitVector() && EltSz == 32)
5544     return false;
5545
5546   return true;
5547 }
5548
5549 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5550 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5551 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5552 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5553   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5554   if (EltSz == 64)
5555     return false;
5556
5557   unsigned NumElts = VT.getVectorNumElements();
5558   if (M.size() != NumElts && M.size() != NumElts*2)
5559     return false;
5560
5561   for (unsigned i = 0; i < M.size(); i += NumElts) {
5562     WhichResult = M[i] == 0 ? 0 : 1;
5563     unsigned Idx = WhichResult * NumElts / 2;
5564     for (unsigned j = 0; j < NumElts; j += 2) {
5565       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5566           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5567         return false;
5568       Idx += 1;
5569     }
5570   }
5571
5572   if (M.size() == NumElts*2)
5573     WhichResult = 0;
5574
5575   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5576   if (VT.is64BitVector() && EltSz == 32)
5577     return false;
5578
5579   return true;
5580 }
5581
5582 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5583 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5584 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5585                                            unsigned &WhichResult,
5586                                            bool &isV_UNDEF) {
5587   isV_UNDEF = false;
5588   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5589     return ARMISD::VTRN;
5590   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5591     return ARMISD::VUZP;
5592   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5593     return ARMISD::VZIP;
5594
5595   isV_UNDEF = true;
5596   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5597     return ARMISD::VTRN;
5598   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5599     return ARMISD::VUZP;
5600   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5601     return ARMISD::VZIP;
5602
5603   return 0;
5604 }
5605
5606 /// \return true if this is a reverse operation on an vector.
5607 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5608   unsigned NumElts = VT.getVectorNumElements();
5609   // Make sure the mask has the right size.
5610   if (NumElts != M.size())
5611       return false;
5612
5613   // Look for <15, ..., 3, -1, 1, 0>.
5614   for (unsigned i = 0; i != NumElts; ++i)
5615     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5616       return false;
5617
5618   return true;
5619 }
5620
5621 // If N is an integer constant that can be moved into a register in one
5622 // instruction, return an SDValue of such a constant (will become a MOV
5623 // instruction).  Otherwise return null.
5624 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5625                                      const ARMSubtarget *ST, const SDLoc &dl) {
5626   uint64_t Val;
5627   if (!isa<ConstantSDNode>(N))
5628     return SDValue();
5629   Val = cast<ConstantSDNode>(N)->getZExtValue();
5630
5631   if (ST->isThumb1Only()) {
5632     if (Val <= 255 || ~Val <= 255)
5633       return DAG.getConstant(Val, dl, MVT::i32);
5634   } else {
5635     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5636       return DAG.getConstant(Val, dl, MVT::i32);
5637   }
5638   return SDValue();
5639 }
5640
5641 // If this is a case we can't handle, return null and let the default
5642 // expansion code take care of it.
5643 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5644                                              const ARMSubtarget *ST) const {
5645   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5646   SDLoc dl(Op);
5647   EVT VT = Op.getValueType();
5648
5649   APInt SplatBits, SplatUndef;
5650   unsigned SplatBitSize;
5651   bool HasAnyUndefs;
5652   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5653     if (SplatBitSize <= 64) {
5654       // Check if an immediate VMOV works.
5655       EVT VmovVT;
5656       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5657                                       SplatUndef.getZExtValue(), SplatBitSize,
5658                                       DAG, dl, VmovVT, VT.is128BitVector(),
5659                                       VMOVModImm);
5660       if (Val.getNode()) {
5661         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5662         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5663       }
5664
5665       // Try an immediate VMVN.
5666       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5667       Val = isNEONModifiedImm(NegatedImm,
5668                                       SplatUndef.getZExtValue(), SplatBitSize,
5669                                       DAG, dl, VmovVT, VT.is128BitVector(),
5670                                       VMVNModImm);
5671       if (Val.getNode()) {
5672         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5673         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5674       }
5675
5676       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5677       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5678         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5679         if (ImmVal != -1) {
5680           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5681           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5682         }
5683       }
5684     }
5685   }
5686
5687   // Scan through the operands to see if only one value is used.
5688   //
5689   // As an optimisation, even if more than one value is used it may be more
5690   // profitable to splat with one value then change some lanes.
5691   //
5692   // Heuristically we decide to do this if the vector has a "dominant" value,
5693   // defined as splatted to more than half of the lanes.
5694   unsigned NumElts = VT.getVectorNumElements();
5695   bool isOnlyLowElement = true;
5696   bool usesOnlyOneValue = true;
5697   bool hasDominantValue = false;
5698   bool isConstant = true;
5699
5700   // Map of the number of times a particular SDValue appears in the
5701   // element list.
5702   DenseMap<SDValue, unsigned> ValueCounts;
5703   SDValue Value;
5704   for (unsigned i = 0; i < NumElts; ++i) {
5705     SDValue V = Op.getOperand(i);
5706     if (V.isUndef())
5707       continue;
5708     if (i > 0)
5709       isOnlyLowElement = false;
5710     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5711       isConstant = false;
5712
5713     ValueCounts.insert(std::make_pair(V, 0));
5714     unsigned &Count = ValueCounts[V];
5715
5716     // Is this value dominant? (takes up more than half of the lanes)
5717     if (++Count > (NumElts / 2)) {
5718       hasDominantValue = true;
5719       Value = V;
5720     }
5721   }
5722   if (ValueCounts.size() != 1)
5723     usesOnlyOneValue = false;
5724   if (!Value.getNode() && ValueCounts.size() > 0)
5725     Value = ValueCounts.begin()->first;
5726
5727   if (ValueCounts.size() == 0)
5728     return DAG.getUNDEF(VT);
5729
5730   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5731   // Keep going if we are hitting this case.
5732   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5733     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5734
5735   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5736
5737   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5738   // i32 and try again.
5739   if (hasDominantValue && EltSize <= 32) {
5740     if (!isConstant) {
5741       SDValue N;
5742
5743       // If we are VDUPing a value that comes directly from a vector, that will
5744       // cause an unnecessary move to and from a GPR, where instead we could
5745       // just use VDUPLANE. We can only do this if the lane being extracted
5746       // is at a constant index, as the VDUP from lane instructions only have
5747       // constant-index forms.
5748       ConstantSDNode *constIndex;
5749       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5750           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
5751         // We need to create a new undef vector to use for the VDUPLANE if the
5752         // size of the vector from which we get the value is different than the
5753         // size of the vector that we need to create. We will insert the element
5754         // such that the register coalescer will remove unnecessary copies.
5755         if (VT != Value->getOperand(0).getValueType()) {
5756           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5757                              VT.getVectorNumElements();
5758           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5759                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5760                         Value, DAG.getConstant(index, dl, MVT::i32)),
5761                            DAG.getConstant(index, dl, MVT::i32));
5762         } else
5763           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5764                         Value->getOperand(0), Value->getOperand(1));
5765       } else
5766         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5767
5768       if (!usesOnlyOneValue) {
5769         // The dominant value was splatted as 'N', but we now have to insert
5770         // all differing elements.
5771         for (unsigned I = 0; I < NumElts; ++I) {
5772           if (Op.getOperand(I) == Value)
5773             continue;
5774           SmallVector<SDValue, 3> Ops;
5775           Ops.push_back(N);
5776           Ops.push_back(Op.getOperand(I));
5777           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5778           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5779         }
5780       }
5781       return N;
5782     }
5783     if (VT.getVectorElementType().isFloatingPoint()) {
5784       SmallVector<SDValue, 8> Ops;
5785       for (unsigned i = 0; i < NumElts; ++i)
5786         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5787                                   Op.getOperand(i)));
5788       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5789       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
5790       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5791       if (Val.getNode())
5792         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5793     }
5794     if (usesOnlyOneValue) {
5795       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5796       if (isConstant && Val.getNode())
5797         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5798     }
5799   }
5800
5801   // If all elements are constants and the case above didn't get hit, fall back
5802   // to the default expansion, which will generate a load from the constant
5803   // pool.
5804   if (isConstant)
5805     return SDValue();
5806
5807   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5808   if (NumElts >= 4) {
5809     SDValue shuffle = ReconstructShuffle(Op, DAG);
5810     if (shuffle != SDValue())
5811       return shuffle;
5812   }
5813
5814   // Vectors with 32- or 64-bit elements can be built by directly assigning
5815   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5816   // will be legalized.
5817   if (EltSize >= 32) {
5818     // Do the expansion with floating-point types, since that is what the VFP
5819     // registers are defined to use, and since i64 is not legal.
5820     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5821     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5822     SmallVector<SDValue, 8> Ops;
5823     for (unsigned i = 0; i < NumElts; ++i)
5824       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5825     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5826     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5827   }
5828
5829   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5830   // know the default expansion would otherwise fall back on something even
5831   // worse. For a vector with one or two non-undef values, that's
5832   // scalar_to_vector for the elements followed by a shuffle (provided the
5833   // shuffle is valid for the target) and materialization element by element
5834   // on the stack followed by a load for everything else.
5835   if (!isConstant && !usesOnlyOneValue) {
5836     SDValue Vec = DAG.getUNDEF(VT);
5837     for (unsigned i = 0 ; i < NumElts; ++i) {
5838       SDValue V = Op.getOperand(i);
5839       if (V.isUndef())
5840         continue;
5841       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5842       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5843     }
5844     return Vec;
5845   }
5846
5847   return SDValue();
5848 }
5849
5850 // Gather data to see if the operation can be modelled as a
5851 // shuffle in combination with VEXTs.
5852 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5853                                               SelectionDAG &DAG) const {
5854   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5855   SDLoc dl(Op);
5856   EVT VT = Op.getValueType();
5857   unsigned NumElts = VT.getVectorNumElements();
5858
5859   struct ShuffleSourceInfo {
5860     SDValue Vec;
5861     unsigned MinElt;
5862     unsigned MaxElt;
5863
5864     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5865     // be compatible with the shuffle we intend to construct. As a result
5866     // ShuffleVec will be some sliding window into the original Vec.
5867     SDValue ShuffleVec;
5868
5869     // Code should guarantee that element i in Vec starts at element "WindowBase
5870     // + i * WindowScale in ShuffleVec".
5871     int WindowBase;
5872     int WindowScale;
5873
5874     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5875     ShuffleSourceInfo(SDValue Vec)
5876         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5877           WindowScale(1) {}
5878   };
5879
5880   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5881   // node.
5882   SmallVector<ShuffleSourceInfo, 2> Sources;
5883   for (unsigned i = 0; i < NumElts; ++i) {
5884     SDValue V = Op.getOperand(i);
5885     if (V.isUndef())
5886       continue;
5887     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5888       // A shuffle can only come from building a vector from various
5889       // elements of other vectors.
5890       return SDValue();
5891     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5892       // Furthermore, shuffles require a constant mask, whereas extractelts
5893       // accept variable indices.
5894       return SDValue();
5895     }
5896
5897     // Add this element source to the list if it's not already there.
5898     SDValue SourceVec = V.getOperand(0);
5899     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5900     if (Source == Sources.end())
5901       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5902
5903     // Update the minimum and maximum lane number seen.
5904     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5905     Source->MinElt = std::min(Source->MinElt, EltNo);
5906     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5907   }
5908
5909   // Currently only do something sane when at most two source vectors
5910   // are involved.
5911   if (Sources.size() > 2)
5912     return SDValue();
5913
5914   // Find out the smallest element size among result and two sources, and use
5915   // it as element size to build the shuffle_vector.
5916   EVT SmallestEltTy = VT.getVectorElementType();
5917   for (auto &Source : Sources) {
5918     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5919     if (SrcEltTy.bitsLT(SmallestEltTy))
5920       SmallestEltTy = SrcEltTy;
5921   }
5922   unsigned ResMultiplier =
5923       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5924   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5925   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5926
5927   // If the source vector is too wide or too narrow, we may nevertheless be able
5928   // to construct a compatible shuffle either by concatenating it with UNDEF or
5929   // extracting a suitable range of elements.
5930   for (auto &Src : Sources) {
5931     EVT SrcVT = Src.ShuffleVec.getValueType();
5932
5933     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5934       continue;
5935
5936     // This stage of the search produces a source with the same element type as
5937     // the original, but with a total width matching the BUILD_VECTOR output.
5938     EVT EltVT = SrcVT.getVectorElementType();
5939     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5940     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5941
5942     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5943       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5944         return SDValue();
5945       // We can pad out the smaller vector for free, so if it's part of a
5946       // shuffle...
5947       Src.ShuffleVec =
5948           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5949                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5950       continue;
5951     }
5952
5953     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5954       return SDValue();
5955
5956     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5957       // Span too large for a VEXT to cope
5958       return SDValue();
5959     }
5960
5961     if (Src.MinElt >= NumSrcElts) {
5962       // The extraction can just take the second half
5963       Src.ShuffleVec =
5964           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5965                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5966       Src.WindowBase = -NumSrcElts;
5967     } else if (Src.MaxElt < NumSrcElts) {
5968       // The extraction can just take the first half
5969       Src.ShuffleVec =
5970           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5971                       DAG.getConstant(0, dl, MVT::i32));
5972     } else {
5973       // An actual VEXT is needed
5974       SDValue VEXTSrc1 =
5975           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5976                       DAG.getConstant(0, dl, MVT::i32));
5977       SDValue VEXTSrc2 =
5978           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5979                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5980
5981       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5982                                    VEXTSrc2,
5983                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5984       Src.WindowBase = -Src.MinElt;
5985     }
5986   }
5987
5988   // Another possible incompatibility occurs from the vector element types. We
5989   // can fix this by bitcasting the source vectors to the same type we intend
5990   // for the shuffle.
5991   for (auto &Src : Sources) {
5992     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5993     if (SrcEltTy == SmallestEltTy)
5994       continue;
5995     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5996     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5997     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5998     Src.WindowBase *= Src.WindowScale;
5999   }
6000
6001   // Final sanity check before we try to actually produce a shuffle.
6002   DEBUG(
6003     for (auto Src : Sources)
6004       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6005   );
6006
6007   // The stars all align, our next step is to produce the mask for the shuffle.
6008   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6009   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
6010   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6011     SDValue Entry = Op.getOperand(i);
6012     if (Entry.isUndef())
6013       continue;
6014
6015     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
6016     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6017
6018     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6019     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6020     // segment.
6021     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6022     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6023                                VT.getVectorElementType().getSizeInBits());
6024     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6025
6026     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6027     // starting at the appropriate offset.
6028     int *LaneMask = &Mask[i * ResMultiplier];
6029
6030     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6031     ExtractBase += NumElts * (Src - Sources.begin());
6032     for (int j = 0; j < LanesDefined; ++j)
6033       LaneMask[j] = ExtractBase + j;
6034   }
6035
6036   // Final check before we try to produce nonsense...
6037   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6038     return SDValue();
6039
6040   // We can't handle more than two sources. This should have already
6041   // been checked before this point.
6042   assert(Sources.size() <= 2 && "Too many sources!");
6043
6044   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6045   for (unsigned i = 0; i < Sources.size(); ++i)
6046     ShuffleOps[i] = Sources[i].ShuffleVec;
6047
6048   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6049                                          ShuffleOps[1], Mask);
6050   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6051 }
6052
6053 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6054 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6055 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6056 /// are assumed to be legal.
6057 bool
6058 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6059                                       EVT VT) const {
6060   if (VT.getVectorNumElements() == 4 &&
6061       (VT.is128BitVector() || VT.is64BitVector())) {
6062     unsigned PFIndexes[4];
6063     for (unsigned i = 0; i != 4; ++i) {
6064       if (M[i] < 0)
6065         PFIndexes[i] = 8;
6066       else
6067         PFIndexes[i] = M[i];
6068     }
6069
6070     // Compute the index in the perfect shuffle table.
6071     unsigned PFTableIndex =
6072       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6073     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6074     unsigned Cost = (PFEntry >> 30);
6075
6076     if (Cost <= 4)
6077       return true;
6078   }
6079
6080   bool ReverseVEXT, isV_UNDEF;
6081   unsigned Imm, WhichResult;
6082
6083   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6084   return (EltSize >= 32 ||
6085           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6086           isVREVMask(M, VT, 64) ||
6087           isVREVMask(M, VT, 32) ||
6088           isVREVMask(M, VT, 16) ||
6089           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6090           isVTBLMask(M, VT) ||
6091           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6092           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6093 }
6094
6095 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6096 /// the specified operations to build the shuffle.
6097 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6098                                       SDValue RHS, SelectionDAG &DAG,
6099                                       const SDLoc &dl) {
6100   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6101   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6102   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6103
6104   enum {
6105     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6106     OP_VREV,
6107     OP_VDUP0,
6108     OP_VDUP1,
6109     OP_VDUP2,
6110     OP_VDUP3,
6111     OP_VEXT1,
6112     OP_VEXT2,
6113     OP_VEXT3,
6114     OP_VUZPL, // VUZP, left result
6115     OP_VUZPR, // VUZP, right result
6116     OP_VZIPL, // VZIP, left result
6117     OP_VZIPR, // VZIP, right result
6118     OP_VTRNL, // VTRN, left result
6119     OP_VTRNR  // VTRN, right result
6120   };
6121
6122   if (OpNum == OP_COPY) {
6123     if (LHSID == (1*9+2)*9+3) return LHS;
6124     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6125     return RHS;
6126   }
6127
6128   SDValue OpLHS, OpRHS;
6129   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6130   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6131   EVT VT = OpLHS.getValueType();
6132
6133   switch (OpNum) {
6134   default: llvm_unreachable("Unknown shuffle opcode!");
6135   case OP_VREV:
6136     // VREV divides the vector in half and swaps within the half.
6137     if (VT.getVectorElementType() == MVT::i32 ||
6138         VT.getVectorElementType() == MVT::f32)
6139       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6140     // vrev <4 x i16> -> VREV32
6141     if (VT.getVectorElementType() == MVT::i16)
6142       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6143     // vrev <4 x i8> -> VREV16
6144     assert(VT.getVectorElementType() == MVT::i8);
6145     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6146   case OP_VDUP0:
6147   case OP_VDUP1:
6148   case OP_VDUP2:
6149   case OP_VDUP3:
6150     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6151                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6152   case OP_VEXT1:
6153   case OP_VEXT2:
6154   case OP_VEXT3:
6155     return DAG.getNode(ARMISD::VEXT, dl, VT,
6156                        OpLHS, OpRHS,
6157                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6158   case OP_VUZPL:
6159   case OP_VUZPR:
6160     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6161                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6162   case OP_VZIPL:
6163   case OP_VZIPR:
6164     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6165                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6166   case OP_VTRNL:
6167   case OP_VTRNR:
6168     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6169                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6170   }
6171 }
6172
6173 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6174                                        ArrayRef<int> ShuffleMask,
6175                                        SelectionDAG &DAG) {
6176   // Check to see if we can use the VTBL instruction.
6177   SDValue V1 = Op.getOperand(0);
6178   SDValue V2 = Op.getOperand(1);
6179   SDLoc DL(Op);
6180
6181   SmallVector<SDValue, 8> VTBLMask;
6182   for (ArrayRef<int>::iterator
6183          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6184     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6185
6186   if (V2.getNode()->isUndef())
6187     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6188                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6189
6190   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6191                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6192 }
6193
6194 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6195                                                       SelectionDAG &DAG) {
6196   SDLoc DL(Op);
6197   SDValue OpLHS = Op.getOperand(0);
6198   EVT VT = OpLHS.getValueType();
6199
6200   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6201          "Expect an v8i16/v16i8 type");
6202   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6203   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6204   // extract the first 8 bytes into the top double word and the last 8 bytes
6205   // into the bottom double word. The v8i16 case is similar.
6206   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6207   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6208                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6209 }
6210
6211 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6212   SDValue V1 = Op.getOperand(0);
6213   SDValue V2 = Op.getOperand(1);
6214   SDLoc dl(Op);
6215   EVT VT = Op.getValueType();
6216   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6217
6218   // Convert shuffles that are directly supported on NEON to target-specific
6219   // DAG nodes, instead of keeping them as shuffles and matching them again
6220   // during code selection.  This is more efficient and avoids the possibility
6221   // of inconsistencies between legalization and selection.
6222   // FIXME: floating-point vectors should be canonicalized to integer vectors
6223   // of the same time so that they get CSEd properly.
6224   ArrayRef<int> ShuffleMask = SVN->getMask();
6225
6226   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6227   if (EltSize <= 32) {
6228     if (SVN->isSplat()) {
6229       int Lane = SVN->getSplatIndex();
6230       // If this is undef splat, generate it via "just" vdup, if possible.
6231       if (Lane == -1) Lane = 0;
6232
6233       // Test if V1 is a SCALAR_TO_VECTOR.
6234       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6235         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6236       }
6237       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6238       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6239       // reaches it).
6240       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6241           !isa<ConstantSDNode>(V1.getOperand(0))) {
6242         bool IsScalarToVector = true;
6243         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6244           if (!V1.getOperand(i).isUndef()) {
6245             IsScalarToVector = false;
6246             break;
6247           }
6248         if (IsScalarToVector)
6249           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6250       }
6251       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6252                          DAG.getConstant(Lane, dl, MVT::i32));
6253     }
6254
6255     bool ReverseVEXT;
6256     unsigned Imm;
6257     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6258       if (ReverseVEXT)
6259         std::swap(V1, V2);
6260       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6261                          DAG.getConstant(Imm, dl, MVT::i32));
6262     }
6263
6264     if (isVREVMask(ShuffleMask, VT, 64))
6265       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6266     if (isVREVMask(ShuffleMask, VT, 32))
6267       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6268     if (isVREVMask(ShuffleMask, VT, 16))
6269       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6270
6271     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6272       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6273                          DAG.getConstant(Imm, dl, MVT::i32));
6274     }
6275
6276     // Check for Neon shuffles that modify both input vectors in place.
6277     // If both results are used, i.e., if there are two shuffles with the same
6278     // source operands and with masks corresponding to both results of one of
6279     // these operations, DAG memoization will ensure that a single node is
6280     // used for both shuffles.
6281     unsigned WhichResult;
6282     bool isV_UNDEF;
6283     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6284             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6285       if (isV_UNDEF)
6286         V2 = V1;
6287       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6288           .getValue(WhichResult);
6289     }
6290
6291     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6292     // shuffles that produce a result larger than their operands with:
6293     //   shuffle(concat(v1, undef), concat(v2, undef))
6294     // ->
6295     //   shuffle(concat(v1, v2), undef)
6296     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6297     //
6298     // This is useful in the general case, but there are special cases where
6299     // native shuffles produce larger results: the two-result ops.
6300     //
6301     // Look through the concat when lowering them:
6302     //   shuffle(concat(v1, v2), undef)
6303     // ->
6304     //   concat(VZIP(v1, v2):0, :1)
6305     //
6306     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6307       SDValue SubV1 = V1->getOperand(0);
6308       SDValue SubV2 = V1->getOperand(1);
6309       EVT SubVT = SubV1.getValueType();
6310
6311       // We expect these to have been canonicalized to -1.
6312       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6313         return i < (int)VT.getVectorNumElements();
6314       }) && "Unexpected shuffle index into UNDEF operand!");
6315
6316       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6317               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6318         if (isV_UNDEF)
6319           SubV2 = SubV1;
6320         assert((WhichResult == 0) &&
6321                "In-place shuffle of concat can only have one result!");
6322         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6323                                   SubV1, SubV2);
6324         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6325                            Res.getValue(1));
6326       }
6327     }
6328   }
6329
6330   // If the shuffle is not directly supported and it has 4 elements, use
6331   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6332   unsigned NumElts = VT.getVectorNumElements();
6333   if (NumElts == 4) {
6334     unsigned PFIndexes[4];
6335     for (unsigned i = 0; i != 4; ++i) {
6336       if (ShuffleMask[i] < 0)
6337         PFIndexes[i] = 8;
6338       else
6339         PFIndexes[i] = ShuffleMask[i];
6340     }
6341
6342     // Compute the index in the perfect shuffle table.
6343     unsigned PFTableIndex =
6344       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6345     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6346     unsigned Cost = (PFEntry >> 30);
6347
6348     if (Cost <= 4)
6349       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6350   }
6351
6352   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6353   if (EltSize >= 32) {
6354     // Do the expansion with floating-point types, since that is what the VFP
6355     // registers are defined to use, and since i64 is not legal.
6356     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6357     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6358     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6359     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6360     SmallVector<SDValue, 8> Ops;
6361     for (unsigned i = 0; i < NumElts; ++i) {
6362       if (ShuffleMask[i] < 0)
6363         Ops.push_back(DAG.getUNDEF(EltVT));
6364       else
6365         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6366                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6367                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6368                                                   dl, MVT::i32)));
6369     }
6370     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6371     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6372   }
6373
6374   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6375     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6376
6377   if (VT == MVT::v8i8)
6378     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6379       return NewOp;
6380
6381   return SDValue();
6382 }
6383
6384 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6385   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6386   SDValue Lane = Op.getOperand(2);
6387   if (!isa<ConstantSDNode>(Lane))
6388     return SDValue();
6389
6390   return Op;
6391 }
6392
6393 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6394   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6395   SDValue Lane = Op.getOperand(1);
6396   if (!isa<ConstantSDNode>(Lane))
6397     return SDValue();
6398
6399   SDValue Vec = Op.getOperand(0);
6400   if (Op.getValueType() == MVT::i32 &&
6401       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6402     SDLoc dl(Op);
6403     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6404   }
6405
6406   return Op;
6407 }
6408
6409 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6410   // The only time a CONCAT_VECTORS operation can have legal types is when
6411   // two 64-bit vectors are concatenated to a 128-bit vector.
6412   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6413          "unexpected CONCAT_VECTORS");
6414   SDLoc dl(Op);
6415   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6416   SDValue Op0 = Op.getOperand(0);
6417   SDValue Op1 = Op.getOperand(1);
6418   if (!Op0.isUndef())
6419     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6420                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6421                       DAG.getIntPtrConstant(0, dl));
6422   if (!Op1.isUndef())
6423     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6424                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6425                       DAG.getIntPtrConstant(1, dl));
6426   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6427 }
6428
6429 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6430 /// element has been zero/sign-extended, depending on the isSigned parameter,
6431 /// from an integer type half its size.
6432 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6433                                    bool isSigned) {
6434   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6435   EVT VT = N->getValueType(0);
6436   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6437     SDNode *BVN = N->getOperand(0).getNode();
6438     if (BVN->getValueType(0) != MVT::v4i32 ||
6439         BVN->getOpcode() != ISD::BUILD_VECTOR)
6440       return false;
6441     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6442     unsigned HiElt = 1 - LoElt;
6443     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6444     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6445     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6446     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6447     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6448       return false;
6449     if (isSigned) {
6450       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6451           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6452         return true;
6453     } else {
6454       if (Hi0->isNullValue() && Hi1->isNullValue())
6455         return true;
6456     }
6457     return false;
6458   }
6459
6460   if (N->getOpcode() != ISD::BUILD_VECTOR)
6461     return false;
6462
6463   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6464     SDNode *Elt = N->getOperand(i).getNode();
6465     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6466       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6467       unsigned HalfSize = EltSize / 2;
6468       if (isSigned) {
6469         if (!isIntN(HalfSize, C->getSExtValue()))
6470           return false;
6471       } else {
6472         if (!isUIntN(HalfSize, C->getZExtValue()))
6473           return false;
6474       }
6475       continue;
6476     }
6477     return false;
6478   }
6479
6480   return true;
6481 }
6482
6483 /// isSignExtended - Check if a node is a vector value that is sign-extended
6484 /// or a constant BUILD_VECTOR with sign-extended elements.
6485 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6486   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6487     return true;
6488   if (isExtendedBUILD_VECTOR(N, DAG, true))
6489     return true;
6490   return false;
6491 }
6492
6493 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6494 /// or a constant BUILD_VECTOR with zero-extended elements.
6495 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6496   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6497     return true;
6498   if (isExtendedBUILD_VECTOR(N, DAG, false))
6499     return true;
6500   return false;
6501 }
6502
6503 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6504   if (OrigVT.getSizeInBits() >= 64)
6505     return OrigVT;
6506
6507   assert(OrigVT.isSimple() && "Expecting a simple value type");
6508
6509   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6510   switch (OrigSimpleTy) {
6511   default: llvm_unreachable("Unexpected Vector Type");
6512   case MVT::v2i8:
6513   case MVT::v2i16:
6514      return MVT::v2i32;
6515   case MVT::v4i8:
6516     return  MVT::v4i16;
6517   }
6518 }
6519
6520 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6521 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6522 /// We insert the required extension here to get the vector to fill a D register.
6523 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6524                                             const EVT &OrigTy,
6525                                             const EVT &ExtTy,
6526                                             unsigned ExtOpcode) {
6527   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6528   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6529   // 64-bits we need to insert a new extension so that it will be 64-bits.
6530   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6531   if (OrigTy.getSizeInBits() >= 64)
6532     return N;
6533
6534   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6535   EVT NewVT = getExtensionTo64Bits(OrigTy);
6536
6537   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6538 }
6539
6540 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6541 /// does not do any sign/zero extension. If the original vector is less
6542 /// than 64 bits, an appropriate extension will be added after the load to
6543 /// reach a total size of 64 bits. We have to add the extension separately
6544 /// because ARM does not have a sign/zero extending load for vectors.
6545 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6546   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6547
6548   // The load already has the right type.
6549   if (ExtendedTy == LD->getMemoryVT())
6550     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6551                        LD->getBasePtr(), LD->getPointerInfo(),
6552                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6553
6554   // We need to create a zextload/sextload. We cannot just create a load
6555   // followed by a zext/zext node because LowerMUL is also run during normal
6556   // operation legalization where we can't create illegal types.
6557   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6558                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6559                         LD->getMemoryVT(), LD->getAlignment(),
6560                         LD->getMemOperand()->getFlags());
6561 }
6562
6563 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6564 /// extending load, or BUILD_VECTOR with extended elements, return the
6565 /// unextended value. The unextended vector should be 64 bits so that it can
6566 /// be used as an operand to a VMULL instruction. If the original vector size
6567 /// before extension is less than 64 bits we add a an extension to resize
6568 /// the vector to 64 bits.
6569 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6570   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6571     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6572                                         N->getOperand(0)->getValueType(0),
6573                                         N->getValueType(0),
6574                                         N->getOpcode());
6575
6576   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6577     return SkipLoadExtensionForVMULL(LD, DAG);
6578
6579   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6580   // have been legalized as a BITCAST from v4i32.
6581   if (N->getOpcode() == ISD::BITCAST) {
6582     SDNode *BVN = N->getOperand(0).getNode();
6583     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6584            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6585     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6586     return DAG.getBuildVector(
6587         MVT::v2i32, SDLoc(N),
6588         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
6589   }
6590   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6591   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6592   EVT VT = N->getValueType(0);
6593   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6594   unsigned NumElts = VT.getVectorNumElements();
6595   MVT TruncVT = MVT::getIntegerVT(EltSize);
6596   SmallVector<SDValue, 8> Ops;
6597   SDLoc dl(N);
6598   for (unsigned i = 0; i != NumElts; ++i) {
6599     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6600     const APInt &CInt = C->getAPIntValue();
6601     // Element types smaller than 32 bits are not legal, so use i32 elements.
6602     // The values are implicitly truncated so sext vs. zext doesn't matter.
6603     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6604   }
6605   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
6606 }
6607
6608 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6609   unsigned Opcode = N->getOpcode();
6610   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6611     SDNode *N0 = N->getOperand(0).getNode();
6612     SDNode *N1 = N->getOperand(1).getNode();
6613     return N0->hasOneUse() && N1->hasOneUse() &&
6614       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6615   }
6616   return false;
6617 }
6618
6619 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6620   unsigned Opcode = N->getOpcode();
6621   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6622     SDNode *N0 = N->getOperand(0).getNode();
6623     SDNode *N1 = N->getOperand(1).getNode();
6624     return N0->hasOneUse() && N1->hasOneUse() &&
6625       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6626   }
6627   return false;
6628 }
6629
6630 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6631   // Multiplications are only custom-lowered for 128-bit vectors so that
6632   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6633   EVT VT = Op.getValueType();
6634   assert(VT.is128BitVector() && VT.isInteger() &&
6635          "unexpected type for custom-lowering ISD::MUL");
6636   SDNode *N0 = Op.getOperand(0).getNode();
6637   SDNode *N1 = Op.getOperand(1).getNode();
6638   unsigned NewOpc = 0;
6639   bool isMLA = false;
6640   bool isN0SExt = isSignExtended(N0, DAG);
6641   bool isN1SExt = isSignExtended(N1, DAG);
6642   if (isN0SExt && isN1SExt)
6643     NewOpc = ARMISD::VMULLs;
6644   else {
6645     bool isN0ZExt = isZeroExtended(N0, DAG);
6646     bool isN1ZExt = isZeroExtended(N1, DAG);
6647     if (isN0ZExt && isN1ZExt)
6648       NewOpc = ARMISD::VMULLu;
6649     else if (isN1SExt || isN1ZExt) {
6650       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6651       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6652       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6653         NewOpc = ARMISD::VMULLs;
6654         isMLA = true;
6655       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6656         NewOpc = ARMISD::VMULLu;
6657         isMLA = true;
6658       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6659         std::swap(N0, N1);
6660         NewOpc = ARMISD::VMULLu;
6661         isMLA = true;
6662       }
6663     }
6664
6665     if (!NewOpc) {
6666       if (VT == MVT::v2i64)
6667         // Fall through to expand this.  It is not legal.
6668         return SDValue();
6669       else
6670         // Other vector multiplications are legal.
6671         return Op;
6672     }
6673   }
6674
6675   // Legalize to a VMULL instruction.
6676   SDLoc DL(Op);
6677   SDValue Op0;
6678   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6679   if (!isMLA) {
6680     Op0 = SkipExtensionForVMULL(N0, DAG);
6681     assert(Op0.getValueType().is64BitVector() &&
6682            Op1.getValueType().is64BitVector() &&
6683            "unexpected types for extended operands to VMULL");
6684     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6685   }
6686
6687   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6688   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6689   //   vmull q0, d4, d6
6690   //   vmlal q0, d5, d6
6691   // is faster than
6692   //   vaddl q0, d4, d5
6693   //   vmovl q1, d6
6694   //   vmul  q0, q0, q1
6695   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6696   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6697   EVT Op1VT = Op1.getValueType();
6698   return DAG.getNode(N0->getOpcode(), DL, VT,
6699                      DAG.getNode(NewOpc, DL, VT,
6700                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6701                      DAG.getNode(NewOpc, DL, VT,
6702                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6703 }
6704
6705 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
6706                               SelectionDAG &DAG) {
6707   // TODO: Should this propagate fast-math-flags?
6708
6709   // Convert to float
6710   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6711   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6712   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6713   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6714   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6715   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6716   // Get reciprocal estimate.
6717   // float4 recip = vrecpeq_f32(yf);
6718   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6719                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6720                    Y);
6721   // Because char has a smaller range than uchar, we can actually get away
6722   // without any newton steps.  This requires that we use a weird bias
6723   // of 0xb000, however (again, this has been exhaustively tested).
6724   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6725   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6726   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6727   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
6728   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6729   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6730   // Convert back to short.
6731   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6732   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6733   return X;
6734 }
6735
6736 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
6737                                SelectionDAG &DAG) {
6738   // TODO: Should this propagate fast-math-flags?
6739
6740   SDValue N2;
6741   // Convert to float.
6742   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6743   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6744   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6745   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6746   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6747   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6748
6749   // Use reciprocal estimate and one refinement step.
6750   // float4 recip = vrecpeq_f32(yf);
6751   // recip *= vrecpsq_f32(yf, recip);
6752   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6753                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6754                    N1);
6755   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6756                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6757                    N1, N2);
6758   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6759   // Because short has a smaller range than ushort, we can actually get away
6760   // with only a single newton step.  This requires that we use a weird bias
6761   // of 89, however (again, this has been exhaustively tested).
6762   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6763   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6764   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6765   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
6766   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6767   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6768   // Convert back to integer and return.
6769   // return vmovn_s32(vcvt_s32_f32(result));
6770   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6771   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6772   return N0;
6773 }
6774
6775 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6776   EVT VT = Op.getValueType();
6777   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6778          "unexpected type for custom-lowering ISD::SDIV");
6779
6780   SDLoc dl(Op);
6781   SDValue N0 = Op.getOperand(0);
6782   SDValue N1 = Op.getOperand(1);
6783   SDValue N2, N3;
6784
6785   if (VT == MVT::v8i8) {
6786     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6787     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6788
6789     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6790                      DAG.getIntPtrConstant(4, dl));
6791     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6792                      DAG.getIntPtrConstant(4, dl));
6793     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6794                      DAG.getIntPtrConstant(0, dl));
6795     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6796                      DAG.getIntPtrConstant(0, dl));
6797
6798     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6799     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6800
6801     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6802     N0 = LowerCONCAT_VECTORS(N0, DAG);
6803
6804     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6805     return N0;
6806   }
6807   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6808 }
6809
6810 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6811   // TODO: Should this propagate fast-math-flags?
6812   EVT VT = Op.getValueType();
6813   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6814          "unexpected type for custom-lowering ISD::UDIV");
6815
6816   SDLoc dl(Op);
6817   SDValue N0 = Op.getOperand(0);
6818   SDValue N1 = Op.getOperand(1);
6819   SDValue N2, N3;
6820
6821   if (VT == MVT::v8i8) {
6822     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6823     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6824
6825     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6826                      DAG.getIntPtrConstant(4, dl));
6827     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6828                      DAG.getIntPtrConstant(4, dl));
6829     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6830                      DAG.getIntPtrConstant(0, dl));
6831     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6832                      DAG.getIntPtrConstant(0, dl));
6833
6834     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6835     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6836
6837     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6838     N0 = LowerCONCAT_VECTORS(N0, DAG);
6839
6840     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6841                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6842                                      MVT::i32),
6843                      N0);
6844     return N0;
6845   }
6846
6847   // v4i16 sdiv ... Convert to float.
6848   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6849   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6850   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6851   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6852   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6853   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6854
6855   // Use reciprocal estimate and two refinement steps.
6856   // float4 recip = vrecpeq_f32(yf);
6857   // recip *= vrecpsq_f32(yf, recip);
6858   // recip *= vrecpsq_f32(yf, recip);
6859   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6860                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6861                    BN1);
6862   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6863                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6864                    BN1, N2);
6865   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6866   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6867                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6868                    BN1, N2);
6869   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6870   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6871   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6872   // and that it will never cause us to return an answer too large).
6873   // float4 result = as_float4(as_int4(xf*recip) + 2);
6874   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6875   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6876   N1 = DAG.getConstant(2, dl, MVT::v4i32);
6877   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6878   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6879   // Convert back to integer and return.
6880   // return vmovn_u32(vcvt_s32_f32(result));
6881   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6882   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6883   return N0;
6884 }
6885
6886 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6887   EVT VT = Op.getNode()->getValueType(0);
6888   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6889
6890   unsigned Opc;
6891   bool ExtraOp = false;
6892   switch (Op.getOpcode()) {
6893   default: llvm_unreachable("Invalid code");
6894   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6895   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6896   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6897   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6898   }
6899
6900   if (!ExtraOp)
6901     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6902                        Op.getOperand(1));
6903   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6904                      Op.getOperand(1), Op.getOperand(2));
6905 }
6906
6907 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6908   assert(Subtarget->isTargetDarwin());
6909
6910   // For iOS, we want to call an alternative entry point: __sincos_stret,
6911   // return values are passed via sret.
6912   SDLoc dl(Op);
6913   SDValue Arg = Op.getOperand(0);
6914   EVT ArgVT = Arg.getValueType();
6915   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6916   auto PtrVT = getPointerTy(DAG.getDataLayout());
6917
6918   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6920
6921   // Pair of floats / doubles used to pass the result.
6922   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6923   auto &DL = DAG.getDataLayout();
6924
6925   ArgListTy Args;
6926   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6927   SDValue SRet;
6928   if (ShouldUseSRet) {
6929     // Create stack object for sret.
6930     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6931     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6932     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6933     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6934
6935     ArgListEntry Entry;
6936     Entry.Node = SRet;
6937     Entry.Ty = RetTy->getPointerTo();
6938     Entry.isSExt = false;
6939     Entry.isZExt = false;
6940     Entry.isSRet = true;
6941     Args.push_back(Entry);
6942     RetTy = Type::getVoidTy(*DAG.getContext());
6943   }
6944
6945   ArgListEntry Entry;
6946   Entry.Node = Arg;
6947   Entry.Ty = ArgTy;
6948   Entry.isSExt = false;
6949   Entry.isZExt = false;
6950   Args.push_back(Entry);
6951
6952   const char *LibcallName =
6953       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6954   RTLIB::Libcall LC =
6955       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6956   CallingConv::ID CC = getLibcallCallingConv(LC);
6957   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6958
6959   TargetLowering::CallLoweringInfo CLI(DAG);
6960   CLI.setDebugLoc(dl)
6961       .setChain(DAG.getEntryNode())
6962       .setCallee(CC, RetTy, Callee, std::move(Args))
6963       .setDiscardResult(ShouldUseSRet);
6964   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6965
6966   if (!ShouldUseSRet)
6967     return CallResult.first;
6968
6969   SDValue LoadSin =
6970       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
6971
6972   // Address of cos field.
6973   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6974                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6975   SDValue LoadCos =
6976       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
6977
6978   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6979   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6980                      LoadSin.getValue(0), LoadCos.getValue(0));
6981 }
6982
6983 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6984                                                   bool Signed,
6985                                                   SDValue &Chain) const {
6986   EVT VT = Op.getValueType();
6987   assert((VT == MVT::i32 || VT == MVT::i64) &&
6988          "unexpected type for custom lowering DIV");
6989   SDLoc dl(Op);
6990
6991   const auto &DL = DAG.getDataLayout();
6992   const auto &TLI = DAG.getTargetLoweringInfo();
6993
6994   const char *Name = nullptr;
6995   if (Signed)
6996     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6997   else
6998     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6999
7000   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7001
7002   ARMTargetLowering::ArgListTy Args;
7003
7004   for (auto AI : {1, 0}) {
7005     ArgListEntry Arg;
7006     Arg.Node = Op.getOperand(AI);
7007     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7008     Args.push_back(Arg);
7009   }
7010
7011   CallLoweringInfo CLI(DAG);
7012   CLI.setDebugLoc(dl)
7013     .setChain(Chain)
7014     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7015                ES, std::move(Args));
7016
7017   return LowerCallTo(CLI).first;
7018 }
7019
7020 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7021                                             bool Signed) const {
7022   assert(Op.getValueType() == MVT::i32 &&
7023          "unexpected type for custom lowering DIV");
7024   SDLoc dl(Op);
7025
7026   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7027                                DAG.getEntryNode(), Op.getOperand(1));
7028
7029   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7030 }
7031
7032 void ARMTargetLowering::ExpandDIV_Windows(
7033     SDValue Op, SelectionDAG &DAG, bool Signed,
7034     SmallVectorImpl<SDValue> &Results) const {
7035   const auto &DL = DAG.getDataLayout();
7036   const auto &TLI = DAG.getTargetLoweringInfo();
7037
7038   assert(Op.getValueType() == MVT::i64 &&
7039          "unexpected type for custom lowering DIV");
7040   SDLoc dl(Op);
7041
7042   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
7043                            DAG.getConstant(0, dl, MVT::i32));
7044   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
7045                            DAG.getConstant(1, dl, MVT::i32));
7046   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
7047
7048   SDValue DBZCHK =
7049       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
7050
7051   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7052
7053   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7054   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7055                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7056   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7057
7058   Results.push_back(Lower);
7059   Results.push_back(Upper);
7060 }
7061
7062 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7063   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7064     // Acquire/Release load/store is not legal for targets without a dmb or
7065     // equivalent available.
7066     return SDValue();
7067
7068   // Monotonic load/store is legal for all targets.
7069   return Op;
7070 }
7071
7072 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7073                                     SmallVectorImpl<SDValue> &Results,
7074                                     SelectionDAG &DAG,
7075                                     const ARMSubtarget *Subtarget) {
7076   SDLoc DL(N);
7077   // Under Power Management extensions, the cycle-count is:
7078   //    mrc p15, #0, <Rt>, c9, c13, #0
7079   SDValue Ops[] = { N->getOperand(0), // Chain
7080                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7081                     DAG.getConstant(15, DL, MVT::i32),
7082                     DAG.getConstant(0, DL, MVT::i32),
7083                     DAG.getConstant(9, DL, MVT::i32),
7084                     DAG.getConstant(13, DL, MVT::i32),
7085                     DAG.getConstant(0, DL, MVT::i32)
7086   };
7087
7088   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7089                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7090   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7091                                 DAG.getConstant(0, DL, MVT::i32)));
7092   Results.push_back(Cycles32.getValue(1));
7093 }
7094
7095 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7096   SDLoc dl(V.getNode());
7097   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7098   SDValue VHi = DAG.getAnyExtOrTrunc(
7099       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7100       dl, MVT::i32);
7101   SDValue RegClass =
7102       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7103   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7104   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7105   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7106   return SDValue(
7107       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7108 }
7109
7110 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7111                                        SmallVectorImpl<SDValue> & Results,
7112                                        SelectionDAG &DAG) {
7113   assert(N->getValueType(0) == MVT::i64 &&
7114          "AtomicCmpSwap on types less than 64 should be legal");
7115   SDValue Ops[] = {N->getOperand(1),
7116                    createGPRPairNode(DAG, N->getOperand(2)),
7117                    createGPRPairNode(DAG, N->getOperand(3)),
7118                    N->getOperand(0)};
7119   SDNode *CmpSwap = DAG.getMachineNode(
7120       ARM::CMP_SWAP_64, SDLoc(N),
7121       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7122
7123   MachineFunction &MF = DAG.getMachineFunction();
7124   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7125   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7126   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7127
7128   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7129                                                SDValue(CmpSwap, 0)));
7130   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7131                                                SDValue(CmpSwap, 0)));
7132   Results.push_back(SDValue(CmpSwap, 2));
7133 }
7134
7135 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7136   switch (Op.getOpcode()) {
7137   default: llvm_unreachable("Don't know how to custom lower this!");
7138   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7139   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
7140   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7141   case ISD::GlobalAddress:
7142     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7143     default: llvm_unreachable("unknown object format");
7144     case Triple::COFF:
7145       return LowerGlobalAddressWindows(Op, DAG);
7146     case Triple::ELF:
7147       return LowerGlobalAddressELF(Op, DAG);
7148     case Triple::MachO:
7149       return LowerGlobalAddressDarwin(Op, DAG);
7150     }
7151   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7152   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7153   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7154   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7155   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7156   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7157   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7158   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7159   case ISD::SINT_TO_FP:
7160   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7161   case ISD::FP_TO_SINT:
7162   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7163   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7164   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7165   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7166   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7167   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7168   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7169   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7170                                                                Subtarget);
7171   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7172   case ISD::SHL:
7173   case ISD::SRL:
7174   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7175   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7176   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7177   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7178   case ISD::SRL_PARTS:
7179   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7180   case ISD::CTTZ:
7181   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7182   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7183   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7184   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7185   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7186   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7187   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7188   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7189   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7190   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7191   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7192   case ISD::MUL:           return LowerMUL(Op, DAG);
7193   case ISD::SDIV:
7194     if (Subtarget->isTargetWindows())
7195       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7196     return LowerSDIV(Op, DAG);
7197   case ISD::UDIV:
7198     if (Subtarget->isTargetWindows())
7199       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7200     return LowerUDIV(Op, DAG);
7201   case ISD::ADDC:
7202   case ISD::ADDE:
7203   case ISD::SUBC:
7204   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7205   case ISD::SADDO:
7206   case ISD::UADDO:
7207   case ISD::SSUBO:
7208   case ISD::USUBO:
7209     return LowerXALUO(Op, DAG);
7210   case ISD::ATOMIC_LOAD:
7211   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7212   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7213   case ISD::SDIVREM:
7214   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7215   case ISD::DYNAMIC_STACKALLOC:
7216     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7217       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7218     llvm_unreachable("Don't know how to custom lower this!");
7219   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7220   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7221   case ARMISD::WIN__DBZCHK: return SDValue();
7222   }
7223 }
7224
7225 /// ReplaceNodeResults - Replace the results of node with an illegal result
7226 /// type with new values built out of custom code.
7227 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7228                                            SmallVectorImpl<SDValue> &Results,
7229                                            SelectionDAG &DAG) const {
7230   SDValue Res;
7231   switch (N->getOpcode()) {
7232   default:
7233     llvm_unreachable("Don't know how to custom expand this!");
7234   case ISD::READ_REGISTER:
7235     ExpandREAD_REGISTER(N, Results, DAG);
7236     break;
7237   case ISD::BITCAST:
7238     Res = ExpandBITCAST(N, DAG);
7239     break;
7240   case ISD::SRL:
7241   case ISD::SRA:
7242     Res = Expand64BitShift(N, DAG, Subtarget);
7243     break;
7244   case ISD::SREM:
7245   case ISD::UREM:
7246     Res = LowerREM(N, DAG);
7247     break;
7248   case ISD::SDIVREM:
7249   case ISD::UDIVREM:
7250     Res = LowerDivRem(SDValue(N, 0), DAG);
7251     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7252     Results.push_back(Res.getValue(0));
7253     Results.push_back(Res.getValue(1));
7254     return;
7255   case ISD::READCYCLECOUNTER:
7256     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7257     return;
7258   case ISD::UDIV:
7259   case ISD::SDIV:
7260     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7261     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7262                              Results);
7263   case ISD::ATOMIC_CMP_SWAP:
7264     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7265     return;
7266   }
7267   if (Res.getNode())
7268     Results.push_back(Res);
7269 }
7270
7271 //===----------------------------------------------------------------------===//
7272 //                           ARM Scheduler Hooks
7273 //===----------------------------------------------------------------------===//
7274
7275 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7276 /// registers the function context.
7277 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7278                                                MachineBasicBlock *MBB,
7279                                                MachineBasicBlock *DispatchBB,
7280                                                int FI) const {
7281   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7282   DebugLoc dl = MI.getDebugLoc();
7283   MachineFunction *MF = MBB->getParent();
7284   MachineRegisterInfo *MRI = &MF->getRegInfo();
7285   MachineConstantPool *MCP = MF->getConstantPool();
7286   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7287   const Function *F = MF->getFunction();
7288
7289   bool isThumb = Subtarget->isThumb();
7290   bool isThumb2 = Subtarget->isThumb2();
7291
7292   unsigned PCLabelId = AFI->createPICLabelUId();
7293   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7294   ARMConstantPoolValue *CPV =
7295     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7296   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7297
7298   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7299                                            : &ARM::GPRRegClass;
7300
7301   // Grab constant pool and fixed stack memory operands.
7302   MachineMemOperand *CPMMO =
7303       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7304                                MachineMemOperand::MOLoad, 4, 4);
7305
7306   MachineMemOperand *FIMMOSt =
7307       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7308                                MachineMemOperand::MOStore, 4, 4);
7309
7310   // Load the address of the dispatch MBB into the jump buffer.
7311   if (isThumb2) {
7312     // Incoming value: jbuf
7313     //   ldr.n  r5, LCPI1_1
7314     //   orr    r5, r5, #1
7315     //   add    r5, pc
7316     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7317     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7318     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7319                    .addConstantPoolIndex(CPI)
7320                    .addMemOperand(CPMMO));
7321     // Set the low bit because of thumb mode.
7322     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7323     AddDefaultCC(
7324       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7325                      .addReg(NewVReg1, RegState::Kill)
7326                      .addImm(0x01)));
7327     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7328     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7329       .addReg(NewVReg2, RegState::Kill)
7330       .addImm(PCLabelId);
7331     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7332                    .addReg(NewVReg3, RegState::Kill)
7333                    .addFrameIndex(FI)
7334                    .addImm(36)  // &jbuf[1] :: pc
7335                    .addMemOperand(FIMMOSt));
7336   } else if (isThumb) {
7337     // Incoming value: jbuf
7338     //   ldr.n  r1, LCPI1_4
7339     //   add    r1, pc
7340     //   mov    r2, #1
7341     //   orrs   r1, r2
7342     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7343     //   str    r1, [r2]
7344     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7345     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7346                    .addConstantPoolIndex(CPI)
7347                    .addMemOperand(CPMMO));
7348     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7349     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7350       .addReg(NewVReg1, RegState::Kill)
7351       .addImm(PCLabelId);
7352     // Set the low bit because of thumb mode.
7353     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7354     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7355                    .addReg(ARM::CPSR, RegState::Define)
7356                    .addImm(1));
7357     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7358     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7359                    .addReg(ARM::CPSR, RegState::Define)
7360                    .addReg(NewVReg2, RegState::Kill)
7361                    .addReg(NewVReg3, RegState::Kill));
7362     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7363     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7364             .addFrameIndex(FI)
7365             .addImm(36); // &jbuf[1] :: pc
7366     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7367                    .addReg(NewVReg4, RegState::Kill)
7368                    .addReg(NewVReg5, RegState::Kill)
7369                    .addImm(0)
7370                    .addMemOperand(FIMMOSt));
7371   } else {
7372     // Incoming value: jbuf
7373     //   ldr  r1, LCPI1_1
7374     //   add  r1, pc, r1
7375     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7376     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7377     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7378                    .addConstantPoolIndex(CPI)
7379                    .addImm(0)
7380                    .addMemOperand(CPMMO));
7381     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7382     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7383                    .addReg(NewVReg1, RegState::Kill)
7384                    .addImm(PCLabelId));
7385     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7386                    .addReg(NewVReg2, RegState::Kill)
7387                    .addFrameIndex(FI)
7388                    .addImm(36)  // &jbuf[1] :: pc
7389                    .addMemOperand(FIMMOSt));
7390   }
7391 }
7392
7393 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7394                                               MachineBasicBlock *MBB) const {
7395   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7396   DebugLoc dl = MI.getDebugLoc();
7397   MachineFunction *MF = MBB->getParent();
7398   MachineRegisterInfo *MRI = &MF->getRegInfo();
7399   MachineFrameInfo *MFI = MF->getFrameInfo();
7400   int FI = MFI->getFunctionContextIndex();
7401
7402   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7403                                                         : &ARM::GPRnopcRegClass;
7404
7405   // Get a mapping of the call site numbers to all of the landing pads they're
7406   // associated with.
7407   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7408   unsigned MaxCSNum = 0;
7409   MachineModuleInfo &MMI = MF->getMMI();
7410   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7411        ++BB) {
7412     if (!BB->isEHPad()) continue;
7413
7414     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7415     // pad.
7416     for (MachineBasicBlock::iterator
7417            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7418       if (!II->isEHLabel()) continue;
7419
7420       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7421       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7422
7423       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7424       for (SmallVectorImpl<unsigned>::iterator
7425              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7426            CSI != CSE; ++CSI) {
7427         CallSiteNumToLPad[*CSI].push_back(&*BB);
7428         MaxCSNum = std::max(MaxCSNum, *CSI);
7429       }
7430       break;
7431     }
7432   }
7433
7434   // Get an ordered list of the machine basic blocks for the jump table.
7435   std::vector<MachineBasicBlock*> LPadList;
7436   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7437   LPadList.reserve(CallSiteNumToLPad.size());
7438   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7439     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7440     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7441            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7442       LPadList.push_back(*II);
7443       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7444     }
7445   }
7446
7447   assert(!LPadList.empty() &&
7448          "No landing pad destinations for the dispatch jump table!");
7449
7450   // Create the jump table and associated information.
7451   MachineJumpTableInfo *JTI =
7452     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7453   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7454
7455   // Create the MBBs for the dispatch code.
7456
7457   // Shove the dispatch's address into the return slot in the function context.
7458   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7459   DispatchBB->setIsEHPad();
7460
7461   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7462   unsigned trap_opcode;
7463   if (Subtarget->isThumb())
7464     trap_opcode = ARM::tTRAP;
7465   else
7466     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7467
7468   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7469   DispatchBB->addSuccessor(TrapBB);
7470
7471   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7472   DispatchBB->addSuccessor(DispContBB);
7473
7474   // Insert and MBBs.
7475   MF->insert(MF->end(), DispatchBB);
7476   MF->insert(MF->end(), DispContBB);
7477   MF->insert(MF->end(), TrapBB);
7478
7479   // Insert code into the entry block that creates and registers the function
7480   // context.
7481   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7482
7483   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7484       MachinePointerInfo::getFixedStack(*MF, FI),
7485       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7486
7487   MachineInstrBuilder MIB;
7488   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7489
7490   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7491   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7492
7493   // Add a register mask with no preserved registers.  This results in all
7494   // registers being marked as clobbered.
7495   MIB.addRegMask(RI.getNoPreservedMask());
7496
7497   bool IsPositionIndependent = isPositionIndependent();
7498   unsigned NumLPads = LPadList.size();
7499   if (Subtarget->isThumb2()) {
7500     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7501     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7502                    .addFrameIndex(FI)
7503                    .addImm(4)
7504                    .addMemOperand(FIMMOLd));
7505
7506     if (NumLPads < 256) {
7507       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7508                      .addReg(NewVReg1)
7509                      .addImm(LPadList.size()));
7510     } else {
7511       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7512       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7513                      .addImm(NumLPads & 0xFFFF));
7514
7515       unsigned VReg2 = VReg1;
7516       if ((NumLPads & 0xFFFF0000) != 0) {
7517         VReg2 = MRI->createVirtualRegister(TRC);
7518         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7519                        .addReg(VReg1)
7520                        .addImm(NumLPads >> 16));
7521       }
7522
7523       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7524                      .addReg(NewVReg1)
7525                      .addReg(VReg2));
7526     }
7527
7528     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7529       .addMBB(TrapBB)
7530       .addImm(ARMCC::HI)
7531       .addReg(ARM::CPSR);
7532
7533     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7534     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7535                    .addJumpTableIndex(MJTI));
7536
7537     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7538     AddDefaultCC(
7539       AddDefaultPred(
7540         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7541         .addReg(NewVReg3, RegState::Kill)
7542         .addReg(NewVReg1)
7543         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7544
7545     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7546       .addReg(NewVReg4, RegState::Kill)
7547       .addReg(NewVReg1)
7548       .addJumpTableIndex(MJTI);
7549   } else if (Subtarget->isThumb()) {
7550     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7551     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7552                    .addFrameIndex(FI)
7553                    .addImm(1)
7554                    .addMemOperand(FIMMOLd));
7555
7556     if (NumLPads < 256) {
7557       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7558                      .addReg(NewVReg1)
7559                      .addImm(NumLPads));
7560     } else {
7561       MachineConstantPool *ConstantPool = MF->getConstantPool();
7562       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7563       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7564
7565       // MachineConstantPool wants an explicit alignment.
7566       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7567       if (Align == 0)
7568         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7569       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7570
7571       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7572       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7573                      .addReg(VReg1, RegState::Define)
7574                      .addConstantPoolIndex(Idx));
7575       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7576                      .addReg(NewVReg1)
7577                      .addReg(VReg1));
7578     }
7579
7580     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7581       .addMBB(TrapBB)
7582       .addImm(ARMCC::HI)
7583       .addReg(ARM::CPSR);
7584
7585     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7586     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7587                    .addReg(ARM::CPSR, RegState::Define)
7588                    .addReg(NewVReg1)
7589                    .addImm(2));
7590
7591     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7592     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7593                    .addJumpTableIndex(MJTI));
7594
7595     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7596     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7597                    .addReg(ARM::CPSR, RegState::Define)
7598                    .addReg(NewVReg2, RegState::Kill)
7599                    .addReg(NewVReg3));
7600
7601     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7602         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7603
7604     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7605     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7606                    .addReg(NewVReg4, RegState::Kill)
7607                    .addImm(0)
7608                    .addMemOperand(JTMMOLd));
7609
7610     unsigned NewVReg6 = NewVReg5;
7611     if (IsPositionIndependent) {
7612       NewVReg6 = MRI->createVirtualRegister(TRC);
7613       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7614                      .addReg(ARM::CPSR, RegState::Define)
7615                      .addReg(NewVReg5, RegState::Kill)
7616                      .addReg(NewVReg3));
7617     }
7618
7619     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7620       .addReg(NewVReg6, RegState::Kill)
7621       .addJumpTableIndex(MJTI);
7622   } else {
7623     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7624     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7625                    .addFrameIndex(FI)
7626                    .addImm(4)
7627                    .addMemOperand(FIMMOLd));
7628
7629     if (NumLPads < 256) {
7630       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7631                      .addReg(NewVReg1)
7632                      .addImm(NumLPads));
7633     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7634       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7635       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7636                      .addImm(NumLPads & 0xFFFF));
7637
7638       unsigned VReg2 = VReg1;
7639       if ((NumLPads & 0xFFFF0000) != 0) {
7640         VReg2 = MRI->createVirtualRegister(TRC);
7641         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7642                        .addReg(VReg1)
7643                        .addImm(NumLPads >> 16));
7644       }
7645
7646       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7647                      .addReg(NewVReg1)
7648                      .addReg(VReg2));
7649     } else {
7650       MachineConstantPool *ConstantPool = MF->getConstantPool();
7651       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7652       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7653
7654       // MachineConstantPool wants an explicit alignment.
7655       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7656       if (Align == 0)
7657         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7658       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7659
7660       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7661       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7662                      .addReg(VReg1, RegState::Define)
7663                      .addConstantPoolIndex(Idx)
7664                      .addImm(0));
7665       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7666                      .addReg(NewVReg1)
7667                      .addReg(VReg1, RegState::Kill));
7668     }
7669
7670     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7671       .addMBB(TrapBB)
7672       .addImm(ARMCC::HI)
7673       .addReg(ARM::CPSR);
7674
7675     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7676     AddDefaultCC(
7677       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7678                      .addReg(NewVReg1)
7679                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7680     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7681     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7682                    .addJumpTableIndex(MJTI));
7683
7684     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7685         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7686     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7687     AddDefaultPred(
7688       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7689       .addReg(NewVReg3, RegState::Kill)
7690       .addReg(NewVReg4)
7691       .addImm(0)
7692       .addMemOperand(JTMMOLd));
7693
7694     if (IsPositionIndependent) {
7695       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7696         .addReg(NewVReg5, RegState::Kill)
7697         .addReg(NewVReg4)
7698         .addJumpTableIndex(MJTI);
7699     } else {
7700       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7701         .addReg(NewVReg5, RegState::Kill)
7702         .addJumpTableIndex(MJTI);
7703     }
7704   }
7705
7706   // Add the jump table entries as successors to the MBB.
7707   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7708   for (std::vector<MachineBasicBlock*>::iterator
7709          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7710     MachineBasicBlock *CurMBB = *I;
7711     if (SeenMBBs.insert(CurMBB).second)
7712       DispContBB->addSuccessor(CurMBB);
7713   }
7714
7715   // N.B. the order the invoke BBs are processed in doesn't matter here.
7716   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7717   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7718   for (MachineBasicBlock *BB : InvokeBBs) {
7719
7720     // Remove the landing pad successor from the invoke block and replace it
7721     // with the new dispatch block.
7722     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7723                                                   BB->succ_end());
7724     while (!Successors.empty()) {
7725       MachineBasicBlock *SMBB = Successors.pop_back_val();
7726       if (SMBB->isEHPad()) {
7727         BB->removeSuccessor(SMBB);
7728         MBBLPads.push_back(SMBB);
7729       }
7730     }
7731
7732     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
7733     BB->normalizeSuccProbs();
7734
7735     // Find the invoke call and mark all of the callee-saved registers as
7736     // 'implicit defined' so that they're spilled. This prevents code from
7737     // moving instructions to before the EH block, where they will never be
7738     // executed.
7739     for (MachineBasicBlock::reverse_iterator
7740            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7741       if (!II->isCall()) continue;
7742
7743       DenseMap<unsigned, bool> DefRegs;
7744       for (MachineInstr::mop_iterator
7745              OI = II->operands_begin(), OE = II->operands_end();
7746            OI != OE; ++OI) {
7747         if (!OI->isReg()) continue;
7748         DefRegs[OI->getReg()] = true;
7749       }
7750
7751       MachineInstrBuilder MIB(*MF, &*II);
7752
7753       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7754         unsigned Reg = SavedRegs[i];
7755         if (Subtarget->isThumb2() &&
7756             !ARM::tGPRRegClass.contains(Reg) &&
7757             !ARM::hGPRRegClass.contains(Reg))
7758           continue;
7759         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7760           continue;
7761         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7762           continue;
7763         if (!DefRegs[Reg])
7764           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7765       }
7766
7767       break;
7768     }
7769   }
7770
7771   // Mark all former landing pads as non-landing pads. The dispatch is the only
7772   // landing pad now.
7773   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7774          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7775     (*I)->setIsEHPad(false);
7776
7777   // The instruction is gone now.
7778   MI.eraseFromParent();
7779 }
7780
7781 static
7782 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7783   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7784        E = MBB->succ_end(); I != E; ++I)
7785     if (*I != Succ)
7786       return *I;
7787   llvm_unreachable("Expecting a BB with two successors!");
7788 }
7789
7790 /// Return the load opcode for a given load size. If load size >= 8,
7791 /// neon opcode will be returned.
7792 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7793   if (LdSize >= 8)
7794     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7795                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7796   if (IsThumb1)
7797     return LdSize == 4 ? ARM::tLDRi
7798                        : LdSize == 2 ? ARM::tLDRHi
7799                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7800   if (IsThumb2)
7801     return LdSize == 4 ? ARM::t2LDR_POST
7802                        : LdSize == 2 ? ARM::t2LDRH_POST
7803                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7804   return LdSize == 4 ? ARM::LDR_POST_IMM
7805                      : LdSize == 2 ? ARM::LDRH_POST
7806                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7807 }
7808
7809 /// Return the store opcode for a given store size. If store size >= 8,
7810 /// neon opcode will be returned.
7811 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7812   if (StSize >= 8)
7813     return StSize == 16 ? ARM::VST1q32wb_fixed
7814                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7815   if (IsThumb1)
7816     return StSize == 4 ? ARM::tSTRi
7817                        : StSize == 2 ? ARM::tSTRHi
7818                                      : StSize == 1 ? ARM::tSTRBi : 0;
7819   if (IsThumb2)
7820     return StSize == 4 ? ARM::t2STR_POST
7821                        : StSize == 2 ? ARM::t2STRH_POST
7822                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7823   return StSize == 4 ? ARM::STR_POST_IMM
7824                      : StSize == 2 ? ARM::STRH_POST
7825                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7826 }
7827
7828 /// Emit a post-increment load operation with given size. The instructions
7829 /// will be added to BB at Pos.
7830 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
7831                        const TargetInstrInfo *TII, const DebugLoc &dl,
7832                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7833                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7834   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7835   assert(LdOpc != 0 && "Should have a load opcode");
7836   if (LdSize >= 8) {
7837     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7838                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7839                        .addImm(0));
7840   } else if (IsThumb1) {
7841     // load + update AddrIn
7842     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7843                        .addReg(AddrIn).addImm(0));
7844     MachineInstrBuilder MIB =
7845         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7846     MIB = AddDefaultT1CC(MIB);
7847     MIB.addReg(AddrIn).addImm(LdSize);
7848     AddDefaultPred(MIB);
7849   } else if (IsThumb2) {
7850     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7851                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7852                        .addImm(LdSize));
7853   } else { // arm
7854     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7855                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7856                        .addReg(0).addImm(LdSize));
7857   }
7858 }
7859
7860 /// Emit a post-increment store operation with given size. The instructions
7861 /// will be added to BB at Pos.
7862 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
7863                        const TargetInstrInfo *TII, const DebugLoc &dl,
7864                        unsigned StSize, unsigned Data, unsigned AddrIn,
7865                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7866   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7867   assert(StOpc != 0 && "Should have a store opcode");
7868   if (StSize >= 8) {
7869     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7870                        .addReg(AddrIn).addImm(0).addReg(Data));
7871   } else if (IsThumb1) {
7872     // store + update AddrIn
7873     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7874                        .addReg(AddrIn).addImm(0));
7875     MachineInstrBuilder MIB =
7876         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7877     MIB = AddDefaultT1CC(MIB);
7878     MIB.addReg(AddrIn).addImm(StSize);
7879     AddDefaultPred(MIB);
7880   } else if (IsThumb2) {
7881     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7882                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7883   } else { // arm
7884     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7885                        .addReg(Data).addReg(AddrIn).addReg(0)
7886                        .addImm(StSize));
7887   }
7888 }
7889
7890 MachineBasicBlock *
7891 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
7892                                    MachineBasicBlock *BB) const {
7893   // This pseudo instruction has 3 operands: dst, src, size
7894   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7895   // Otherwise, we will generate unrolled scalar copies.
7896   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7897   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7898   MachineFunction::iterator It = ++BB->getIterator();
7899
7900   unsigned dest = MI.getOperand(0).getReg();
7901   unsigned src = MI.getOperand(1).getReg();
7902   unsigned SizeVal = MI.getOperand(2).getImm();
7903   unsigned Align = MI.getOperand(3).getImm();
7904   DebugLoc dl = MI.getDebugLoc();
7905
7906   MachineFunction *MF = BB->getParent();
7907   MachineRegisterInfo &MRI = MF->getRegInfo();
7908   unsigned UnitSize = 0;
7909   const TargetRegisterClass *TRC = nullptr;
7910   const TargetRegisterClass *VecTRC = nullptr;
7911
7912   bool IsThumb1 = Subtarget->isThumb1Only();
7913   bool IsThumb2 = Subtarget->isThumb2();
7914
7915   if (Align & 1) {
7916     UnitSize = 1;
7917   } else if (Align & 2) {
7918     UnitSize = 2;
7919   } else {
7920     // Check whether we can use NEON instructions.
7921     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7922         Subtarget->hasNEON()) {
7923       if ((Align % 16 == 0) && SizeVal >= 16)
7924         UnitSize = 16;
7925       else if ((Align % 8 == 0) && SizeVal >= 8)
7926         UnitSize = 8;
7927     }
7928     // Can't use NEON instructions.
7929     if (UnitSize == 0)
7930       UnitSize = 4;
7931   }
7932
7933   // Select the correct opcode and register class for unit size load/store
7934   bool IsNeon = UnitSize >= 8;
7935   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7936   if (IsNeon)
7937     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7938                             : UnitSize == 8 ? &ARM::DPRRegClass
7939                                             : nullptr;
7940
7941   unsigned BytesLeft = SizeVal % UnitSize;
7942   unsigned LoopSize = SizeVal - BytesLeft;
7943
7944   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7945     // Use LDR and STR to copy.
7946     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7947     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7948     unsigned srcIn = src;
7949     unsigned destIn = dest;
7950     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7951       unsigned srcOut = MRI.createVirtualRegister(TRC);
7952       unsigned destOut = MRI.createVirtualRegister(TRC);
7953       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7954       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7955                  IsThumb1, IsThumb2);
7956       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7957                  IsThumb1, IsThumb2);
7958       srcIn = srcOut;
7959       destIn = destOut;
7960     }
7961
7962     // Handle the leftover bytes with LDRB and STRB.
7963     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7964     // [destOut] = STRB_POST(scratch, destIn, 1)
7965     for (unsigned i = 0; i < BytesLeft; i++) {
7966       unsigned srcOut = MRI.createVirtualRegister(TRC);
7967       unsigned destOut = MRI.createVirtualRegister(TRC);
7968       unsigned scratch = MRI.createVirtualRegister(TRC);
7969       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7970                  IsThumb1, IsThumb2);
7971       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7972                  IsThumb1, IsThumb2);
7973       srcIn = srcOut;
7974       destIn = destOut;
7975     }
7976     MI.eraseFromParent(); // The instruction is gone now.
7977     return BB;
7978   }
7979
7980   // Expand the pseudo op to a loop.
7981   // thisMBB:
7982   //   ...
7983   //   movw varEnd, # --> with thumb2
7984   //   movt varEnd, #
7985   //   ldrcp varEnd, idx --> without thumb2
7986   //   fallthrough --> loopMBB
7987   // loopMBB:
7988   //   PHI varPhi, varEnd, varLoop
7989   //   PHI srcPhi, src, srcLoop
7990   //   PHI destPhi, dst, destLoop
7991   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7992   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7993   //   subs varLoop, varPhi, #UnitSize
7994   //   bne loopMBB
7995   //   fallthrough --> exitMBB
7996   // exitMBB:
7997   //   epilogue to handle left-over bytes
7998   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7999   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8000   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8001   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8002   MF->insert(It, loopMBB);
8003   MF->insert(It, exitMBB);
8004
8005   // Transfer the remainder of BB and its successor edges to exitMBB.
8006   exitMBB->splice(exitMBB->begin(), BB,
8007                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8008   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8009
8010   // Load an immediate to varEnd.
8011   unsigned varEnd = MRI.createVirtualRegister(TRC);
8012   if (Subtarget->useMovt(*MF)) {
8013     unsigned Vtmp = varEnd;
8014     if ((LoopSize & 0xFFFF0000) != 0)
8015       Vtmp = MRI.createVirtualRegister(TRC);
8016     AddDefaultPred(BuildMI(BB, dl,
8017                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
8018                            Vtmp).addImm(LoopSize & 0xFFFF));
8019
8020     if ((LoopSize & 0xFFFF0000) != 0)
8021       AddDefaultPred(BuildMI(BB, dl,
8022                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
8023                              varEnd)
8024                          .addReg(Vtmp)
8025                          .addImm(LoopSize >> 16));
8026   } else {
8027     MachineConstantPool *ConstantPool = MF->getConstantPool();
8028     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8029     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8030
8031     // MachineConstantPool wants an explicit alignment.
8032     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8033     if (Align == 0)
8034       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8035     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8036
8037     if (IsThumb1)
8038       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
8039           varEnd, RegState::Define).addConstantPoolIndex(Idx));
8040     else
8041       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
8042           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
8043   }
8044   BB->addSuccessor(loopMBB);
8045
8046   // Generate the loop body:
8047   //   varPhi = PHI(varLoop, varEnd)
8048   //   srcPhi = PHI(srcLoop, src)
8049   //   destPhi = PHI(destLoop, dst)
8050   MachineBasicBlock *entryBB = BB;
8051   BB = loopMBB;
8052   unsigned varLoop = MRI.createVirtualRegister(TRC);
8053   unsigned varPhi = MRI.createVirtualRegister(TRC);
8054   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8055   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8056   unsigned destLoop = MRI.createVirtualRegister(TRC);
8057   unsigned destPhi = MRI.createVirtualRegister(TRC);
8058
8059   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8060     .addReg(varLoop).addMBB(loopMBB)
8061     .addReg(varEnd).addMBB(entryBB);
8062   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8063     .addReg(srcLoop).addMBB(loopMBB)
8064     .addReg(src).addMBB(entryBB);
8065   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8066     .addReg(destLoop).addMBB(loopMBB)
8067     .addReg(dest).addMBB(entryBB);
8068
8069   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8070   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8071   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8072   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8073              IsThumb1, IsThumb2);
8074   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8075              IsThumb1, IsThumb2);
8076
8077   // Decrement loop variable by UnitSize.
8078   if (IsThumb1) {
8079     MachineInstrBuilder MIB =
8080         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
8081     MIB = AddDefaultT1CC(MIB);
8082     MIB.addReg(varPhi).addImm(UnitSize);
8083     AddDefaultPred(MIB);
8084   } else {
8085     MachineInstrBuilder MIB =
8086         BuildMI(*BB, BB->end(), dl,
8087                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8088     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
8089     MIB->getOperand(5).setReg(ARM::CPSR);
8090     MIB->getOperand(5).setIsDef(true);
8091   }
8092   BuildMI(*BB, BB->end(), dl,
8093           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8094       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8095
8096   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8097   BB->addSuccessor(loopMBB);
8098   BB->addSuccessor(exitMBB);
8099
8100   // Add epilogue to handle BytesLeft.
8101   BB = exitMBB;
8102   auto StartOfExit = exitMBB->begin();
8103
8104   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8105   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8106   unsigned srcIn = srcLoop;
8107   unsigned destIn = destLoop;
8108   for (unsigned i = 0; i < BytesLeft; i++) {
8109     unsigned srcOut = MRI.createVirtualRegister(TRC);
8110     unsigned destOut = MRI.createVirtualRegister(TRC);
8111     unsigned scratch = MRI.createVirtualRegister(TRC);
8112     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8113                IsThumb1, IsThumb2);
8114     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8115                IsThumb1, IsThumb2);
8116     srcIn = srcOut;
8117     destIn = destOut;
8118   }
8119
8120   MI.eraseFromParent(); // The instruction is gone now.
8121   return BB;
8122 }
8123
8124 MachineBasicBlock *
8125 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8126                                        MachineBasicBlock *MBB) const {
8127   const TargetMachine &TM = getTargetMachine();
8128   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8129   DebugLoc DL = MI.getDebugLoc();
8130
8131   assert(Subtarget->isTargetWindows() &&
8132          "__chkstk is only supported on Windows");
8133   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8134
8135   // __chkstk takes the number of words to allocate on the stack in R4, and
8136   // returns the stack adjustment in number of bytes in R4.  This will not
8137   // clober any other registers (other than the obvious lr).
8138   //
8139   // Although, technically, IP should be considered a register which may be
8140   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8141   // thumb-2 environment, so there is no interworking required.  As a result, we
8142   // do not expect a veneer to be emitted by the linker, clobbering IP.
8143   //
8144   // Each module receives its own copy of __chkstk, so no import thunk is
8145   // required, again, ensuring that IP is not clobbered.
8146   //
8147   // Finally, although some linkers may theoretically provide a trampoline for
8148   // out of range calls (which is quite common due to a 32M range limitation of
8149   // branches for Thumb), we can generate the long-call version via
8150   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8151   // IP.
8152
8153   switch (TM.getCodeModel()) {
8154   case CodeModel::Small:
8155   case CodeModel::Medium:
8156   case CodeModel::Default:
8157   case CodeModel::Kernel:
8158     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8159       .addImm((unsigned)ARMCC::AL).addReg(0)
8160       .addExternalSymbol("__chkstk")
8161       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8162       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8163       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8164     break;
8165   case CodeModel::Large:
8166   case CodeModel::JITDefault: {
8167     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8168     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8169
8170     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8171       .addExternalSymbol("__chkstk");
8172     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8173       .addImm((unsigned)ARMCC::AL).addReg(0)
8174       .addReg(Reg, RegState::Kill)
8175       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8176       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8177       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8178     break;
8179   }
8180   }
8181
8182   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
8183                                       ARM::SP)
8184                          .addReg(ARM::SP, RegState::Kill)
8185                          .addReg(ARM::R4, RegState::Kill)
8186                          .setMIFlags(MachineInstr::FrameSetup)));
8187
8188   MI.eraseFromParent();
8189   return MBB;
8190 }
8191
8192 MachineBasicBlock *
8193 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8194                                        MachineBasicBlock *MBB) const {
8195   DebugLoc DL = MI.getDebugLoc();
8196   MachineFunction *MF = MBB->getParent();
8197   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8198
8199   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8200   MF->insert(++MBB->getIterator(), ContBB);
8201   ContBB->splice(ContBB->begin(), MBB,
8202                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8203   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8204
8205   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8206   MF->push_back(TrapBB);
8207   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
8208   MBB->addSuccessor(TrapBB);
8209
8210   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
8211       .addReg(MI.getOperand(0).getReg())
8212       .addMBB(TrapBB);
8213   AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::t2B)).addMBB(ContBB));
8214   MBB->addSuccessor(ContBB);
8215
8216   MI.eraseFromParent();
8217   return ContBB;
8218 }
8219
8220 MachineBasicBlock *
8221 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8222                                                MachineBasicBlock *BB) const {
8223   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8224   DebugLoc dl = MI.getDebugLoc();
8225   bool isThumb2 = Subtarget->isThumb2();
8226   switch (MI.getOpcode()) {
8227   default: {
8228     MI.dump();
8229     llvm_unreachable("Unexpected instr type to insert");
8230   }
8231
8232   // Thumb1 post-indexed loads are really just single-register LDMs.
8233   case ARM::tLDR_postidx: {
8234     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8235       .addOperand(MI.getOperand(1)) // Rn_wb
8236       .addOperand(MI.getOperand(2)) // Rn
8237       .addOperand(MI.getOperand(3)) // PredImm
8238       .addOperand(MI.getOperand(4)) // PredReg
8239       .addOperand(MI.getOperand(0)); // Rt
8240     MI.eraseFromParent();
8241     return BB;
8242   }
8243
8244   // The Thumb2 pre-indexed stores have the same MI operands, they just
8245   // define them differently in the .td files from the isel patterns, so
8246   // they need pseudos.
8247   case ARM::t2STR_preidx:
8248     MI.setDesc(TII->get(ARM::t2STR_PRE));
8249     return BB;
8250   case ARM::t2STRB_preidx:
8251     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8252     return BB;
8253   case ARM::t2STRH_preidx:
8254     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8255     return BB;
8256
8257   case ARM::STRi_preidx:
8258   case ARM::STRBi_preidx: {
8259     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8260                                                          : ARM::STRB_PRE_IMM;
8261     // Decode the offset.
8262     unsigned Offset = MI.getOperand(4).getImm();
8263     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8264     Offset = ARM_AM::getAM2Offset(Offset);
8265     if (isSub)
8266       Offset = -Offset;
8267
8268     MachineMemOperand *MMO = *MI.memoperands_begin();
8269     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8270         .addOperand(MI.getOperand(0)) // Rn_wb
8271         .addOperand(MI.getOperand(1)) // Rt
8272         .addOperand(MI.getOperand(2)) // Rn
8273         .addImm(Offset)               // offset (skip GPR==zero_reg)
8274         .addOperand(MI.getOperand(5)) // pred
8275         .addOperand(MI.getOperand(6))
8276         .addMemOperand(MMO);
8277     MI.eraseFromParent();
8278     return BB;
8279   }
8280   case ARM::STRr_preidx:
8281   case ARM::STRBr_preidx:
8282   case ARM::STRH_preidx: {
8283     unsigned NewOpc;
8284     switch (MI.getOpcode()) {
8285     default: llvm_unreachable("unexpected opcode!");
8286     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8287     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8288     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8289     }
8290     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8291     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8292       MIB.addOperand(MI.getOperand(i));
8293     MI.eraseFromParent();
8294     return BB;
8295   }
8296
8297   case ARM::tMOVCCr_pseudo: {
8298     // To "insert" a SELECT_CC instruction, we actually have to insert the
8299     // diamond control-flow pattern.  The incoming instruction knows the
8300     // destination vreg to set, the condition code register to branch on, the
8301     // true/false values to select between, and a branch opcode to use.
8302     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8303     MachineFunction::iterator It = ++BB->getIterator();
8304
8305     //  thisMBB:
8306     //  ...
8307     //   TrueVal = ...
8308     //   cmpTY ccX, r1, r2
8309     //   bCC copy1MBB
8310     //   fallthrough --> copy0MBB
8311     MachineBasicBlock *thisMBB  = BB;
8312     MachineFunction *F = BB->getParent();
8313     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8314     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8315     F->insert(It, copy0MBB);
8316     F->insert(It, sinkMBB);
8317
8318     // Transfer the remainder of BB and its successor edges to sinkMBB.
8319     sinkMBB->splice(sinkMBB->begin(), BB,
8320                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8321     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8322
8323     BB->addSuccessor(copy0MBB);
8324     BB->addSuccessor(sinkMBB);
8325
8326     BuildMI(BB, dl, TII->get(ARM::tBcc))
8327         .addMBB(sinkMBB)
8328         .addImm(MI.getOperand(3).getImm())
8329         .addReg(MI.getOperand(4).getReg());
8330
8331     //  copy0MBB:
8332     //   %FalseValue = ...
8333     //   # fallthrough to sinkMBB
8334     BB = copy0MBB;
8335
8336     // Update machine-CFG edges
8337     BB->addSuccessor(sinkMBB);
8338
8339     //  sinkMBB:
8340     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8341     //  ...
8342     BB = sinkMBB;
8343     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8344         .addReg(MI.getOperand(1).getReg())
8345         .addMBB(copy0MBB)
8346         .addReg(MI.getOperand(2).getReg())
8347         .addMBB(thisMBB);
8348
8349     MI.eraseFromParent(); // The pseudo instruction is gone now.
8350     return BB;
8351   }
8352
8353   case ARM::BCCi64:
8354   case ARM::BCCZi64: {
8355     // If there is an unconditional branch to the other successor, remove it.
8356     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8357
8358     // Compare both parts that make up the double comparison separately for
8359     // equality.
8360     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8361
8362     unsigned LHS1 = MI.getOperand(1).getReg();
8363     unsigned LHS2 = MI.getOperand(2).getReg();
8364     if (RHSisZero) {
8365       AddDefaultPred(BuildMI(BB, dl,
8366                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8367                      .addReg(LHS1).addImm(0));
8368       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8369         .addReg(LHS2).addImm(0)
8370         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8371     } else {
8372       unsigned RHS1 = MI.getOperand(3).getReg();
8373       unsigned RHS2 = MI.getOperand(4).getReg();
8374       AddDefaultPred(BuildMI(BB, dl,
8375                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8376                      .addReg(LHS1).addReg(RHS1));
8377       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8378         .addReg(LHS2).addReg(RHS2)
8379         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8380     }
8381
8382     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8383     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8384     if (MI.getOperand(0).getImm() == ARMCC::NE)
8385       std::swap(destMBB, exitMBB);
8386
8387     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8388       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8389     if (isThumb2)
8390       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8391     else
8392       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8393
8394     MI.eraseFromParent(); // The pseudo instruction is gone now.
8395     return BB;
8396   }
8397
8398   case ARM::Int_eh_sjlj_setjmp:
8399   case ARM::Int_eh_sjlj_setjmp_nofp:
8400   case ARM::tInt_eh_sjlj_setjmp:
8401   case ARM::t2Int_eh_sjlj_setjmp:
8402   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8403     return BB;
8404
8405   case ARM::Int_eh_sjlj_setup_dispatch:
8406     EmitSjLjDispatchBlock(MI, BB);
8407     return BB;
8408
8409   case ARM::ABS:
8410   case ARM::t2ABS: {
8411     // To insert an ABS instruction, we have to insert the
8412     // diamond control-flow pattern.  The incoming instruction knows the
8413     // source vreg to test against 0, the destination vreg to set,
8414     // the condition code register to branch on, the
8415     // true/false values to select between, and a branch opcode to use.
8416     // It transforms
8417     //     V1 = ABS V0
8418     // into
8419     //     V2 = MOVS V0
8420     //     BCC                      (branch to SinkBB if V0 >= 0)
8421     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8422     //     SinkBB: V1 = PHI(V2, V3)
8423     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8424     MachineFunction::iterator BBI = ++BB->getIterator();
8425     MachineFunction *Fn = BB->getParent();
8426     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8427     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8428     Fn->insert(BBI, RSBBB);
8429     Fn->insert(BBI, SinkBB);
8430
8431     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8432     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8433     bool ABSSrcKIll = MI.getOperand(1).isKill();
8434     bool isThumb2 = Subtarget->isThumb2();
8435     MachineRegisterInfo &MRI = Fn->getRegInfo();
8436     // In Thumb mode S must not be specified if source register is the SP or
8437     // PC and if destination register is the SP, so restrict register class
8438     unsigned NewRsbDstReg =
8439       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8440
8441     // Transfer the remainder of BB and its successor edges to sinkMBB.
8442     SinkBB->splice(SinkBB->begin(), BB,
8443                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8444     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8445
8446     BB->addSuccessor(RSBBB);
8447     BB->addSuccessor(SinkBB);
8448
8449     // fall through to SinkMBB
8450     RSBBB->addSuccessor(SinkBB);
8451
8452     // insert a cmp at the end of BB
8453     AddDefaultPred(BuildMI(BB, dl,
8454                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8455                    .addReg(ABSSrcReg).addImm(0));
8456
8457     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8458     BuildMI(BB, dl,
8459       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8460       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8461
8462     // insert rsbri in RSBBB
8463     // Note: BCC and rsbri will be converted into predicated rsbmi
8464     // by if-conversion pass
8465     BuildMI(*RSBBB, RSBBB->begin(), dl,
8466       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8467       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8468       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8469
8470     // insert PHI in SinkBB,
8471     // reuse ABSDstReg to not change uses of ABS instruction
8472     BuildMI(*SinkBB, SinkBB->begin(), dl,
8473       TII->get(ARM::PHI), ABSDstReg)
8474       .addReg(NewRsbDstReg).addMBB(RSBBB)
8475       .addReg(ABSSrcReg).addMBB(BB);
8476
8477     // remove ABS instruction
8478     MI.eraseFromParent();
8479
8480     // return last added BB
8481     return SinkBB;
8482   }
8483   case ARM::COPY_STRUCT_BYVAL_I32:
8484     ++NumLoopByVals;
8485     return EmitStructByval(MI, BB);
8486   case ARM::WIN__CHKSTK:
8487     return EmitLowered__chkstk(MI, BB);
8488   case ARM::WIN__DBZCHK:
8489     return EmitLowered__dbzchk(MI, BB);
8490   }
8491 }
8492
8493 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8494 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8495 /// instead of as a custom inserter because we need the use list from the SDNode.
8496 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8497                                     MachineInstr &MI, const SDNode *Node) {
8498   bool isThumb1 = Subtarget->isThumb1Only();
8499
8500   DebugLoc DL = MI.getDebugLoc();
8501   MachineFunction *MF = MI.getParent()->getParent();
8502   MachineRegisterInfo &MRI = MF->getRegInfo();
8503   MachineInstrBuilder MIB(*MF, MI);
8504
8505   // If the new dst/src is unused mark it as dead.
8506   if (!Node->hasAnyUseOfValue(0)) {
8507     MI.getOperand(0).setIsDead(true);
8508   }
8509   if (!Node->hasAnyUseOfValue(1)) {
8510     MI.getOperand(1).setIsDead(true);
8511   }
8512
8513   // The MEMCPY both defines and kills the scratch registers.
8514   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
8515     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8516                                                          : &ARM::GPRRegClass);
8517     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8518   }
8519 }
8520
8521 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8522                                                       SDNode *Node) const {
8523   if (MI.getOpcode() == ARM::MEMCPY) {
8524     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8525     return;
8526   }
8527
8528   const MCInstrDesc *MCID = &MI.getDesc();
8529   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8530   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8531   // operand is still set to noreg. If needed, set the optional operand's
8532   // register to CPSR, and remove the redundant implicit def.
8533   //
8534   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8535
8536   // Rename pseudo opcodes.
8537   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
8538   if (NewOpc) {
8539     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8540     MCID = &TII->get(NewOpc);
8541
8542     assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
8543            "converted opcode should be the same except for cc_out");
8544
8545     MI.setDesc(*MCID);
8546
8547     // Add the optional cc_out operand
8548     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8549   }
8550   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8551
8552   // Any ARM instruction that sets the 's' bit should specify an optional
8553   // "cc_out" operand in the last operand position.
8554   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8555     assert(!NewOpc && "Optional cc_out operand required");
8556     return;
8557   }
8558   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8559   // since we already have an optional CPSR def.
8560   bool definesCPSR = false;
8561   bool deadCPSR = false;
8562   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
8563        ++i) {
8564     const MachineOperand &MO = MI.getOperand(i);
8565     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8566       definesCPSR = true;
8567       if (MO.isDead())
8568         deadCPSR = true;
8569       MI.RemoveOperand(i);
8570       break;
8571     }
8572   }
8573   if (!definesCPSR) {
8574     assert(!NewOpc && "Optional cc_out operand required");
8575     return;
8576   }
8577   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8578   if (deadCPSR) {
8579     assert(!MI.getOperand(ccOutIdx).getReg() &&
8580            "expect uninitialized optional cc_out operand");
8581     return;
8582   }
8583
8584   // If this instruction was defined with an optional CPSR def and its dag node
8585   // had a live implicit CPSR def, then activate the optional CPSR def.
8586   MachineOperand &MO = MI.getOperand(ccOutIdx);
8587   MO.setReg(ARM::CPSR);
8588   MO.setIsDef(true);
8589 }
8590
8591 //===----------------------------------------------------------------------===//
8592 //                           ARM Optimization Hooks
8593 //===----------------------------------------------------------------------===//
8594
8595 // Helper function that checks if N is a null or all ones constant.
8596 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8597   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8598 }
8599
8600 // Return true if N is conditionally 0 or all ones.
8601 // Detects these expressions where cc is an i1 value:
8602 //
8603 //   (select cc 0, y)   [AllOnes=0]
8604 //   (select cc y, 0)   [AllOnes=0]
8605 //   (zext cc)          [AllOnes=0]
8606 //   (sext cc)          [AllOnes=0/1]
8607 //   (select cc -1, y)  [AllOnes=1]
8608 //   (select cc y, -1)  [AllOnes=1]
8609 //
8610 // Invert is set when N is the null/all ones constant when CC is false.
8611 // OtherOp is set to the alternative value of N.
8612 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8613                                        SDValue &CC, bool &Invert,
8614                                        SDValue &OtherOp,
8615                                        SelectionDAG &DAG) {
8616   switch (N->getOpcode()) {
8617   default: return false;
8618   case ISD::SELECT: {
8619     CC = N->getOperand(0);
8620     SDValue N1 = N->getOperand(1);
8621     SDValue N2 = N->getOperand(2);
8622     if (isZeroOrAllOnes(N1, AllOnes)) {
8623       Invert = false;
8624       OtherOp = N2;
8625       return true;
8626     }
8627     if (isZeroOrAllOnes(N2, AllOnes)) {
8628       Invert = true;
8629       OtherOp = N1;
8630       return true;
8631     }
8632     return false;
8633   }
8634   case ISD::ZERO_EXTEND:
8635     // (zext cc) can never be the all ones value.
8636     if (AllOnes)
8637       return false;
8638     // Fall through.
8639   case ISD::SIGN_EXTEND: {
8640     SDLoc dl(N);
8641     EVT VT = N->getValueType(0);
8642     CC = N->getOperand(0);
8643     if (CC.getValueType() != MVT::i1)
8644       return false;
8645     Invert = !AllOnes;
8646     if (AllOnes)
8647       // When looking for an AllOnes constant, N is an sext, and the 'other'
8648       // value is 0.
8649       OtherOp = DAG.getConstant(0, dl, VT);
8650     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8651       // When looking for a 0 constant, N can be zext or sext.
8652       OtherOp = DAG.getConstant(1, dl, VT);
8653     else
8654       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8655                                 VT);
8656     return true;
8657   }
8658   }
8659 }
8660
8661 // Combine a constant select operand into its use:
8662 //
8663 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8664 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8665 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8666 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8667 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8668 //
8669 // The transform is rejected if the select doesn't have a constant operand that
8670 // is null, or all ones when AllOnes is set.
8671 //
8672 // Also recognize sext/zext from i1:
8673 //
8674 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8675 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8676 //
8677 // These transformations eventually create predicated instructions.
8678 //
8679 // @param N       The node to transform.
8680 // @param Slct    The N operand that is a select.
8681 // @param OtherOp The other N operand (x above).
8682 // @param DCI     Context.
8683 // @param AllOnes Require the select constant to be all ones instead of null.
8684 // @returns The new node, or SDValue() on failure.
8685 static
8686 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8687                             TargetLowering::DAGCombinerInfo &DCI,
8688                             bool AllOnes = false) {
8689   SelectionDAG &DAG = DCI.DAG;
8690   EVT VT = N->getValueType(0);
8691   SDValue NonConstantVal;
8692   SDValue CCOp;
8693   bool SwapSelectOps;
8694   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8695                                   NonConstantVal, DAG))
8696     return SDValue();
8697
8698   // Slct is now know to be the desired identity constant when CC is true.
8699   SDValue TrueVal = OtherOp;
8700   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8701                                  OtherOp, NonConstantVal);
8702   // Unless SwapSelectOps says CC should be false.
8703   if (SwapSelectOps)
8704     std::swap(TrueVal, FalseVal);
8705
8706   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8707                      CCOp, TrueVal, FalseVal);
8708 }
8709
8710 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8711 static
8712 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8713                                        TargetLowering::DAGCombinerInfo &DCI) {
8714   SDValue N0 = N->getOperand(0);
8715   SDValue N1 = N->getOperand(1);
8716   if (N0.getNode()->hasOneUse())
8717     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
8718       return Result;
8719   if (N1.getNode()->hasOneUse())
8720     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
8721       return Result;
8722   return SDValue();
8723 }
8724
8725 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8726 // (only after legalization).
8727 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8728                                  TargetLowering::DAGCombinerInfo &DCI,
8729                                  const ARMSubtarget *Subtarget) {
8730
8731   // Only perform optimization if after legalize, and if NEON is available. We
8732   // also expected both operands to be BUILD_VECTORs.
8733   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8734       || N0.getOpcode() != ISD::BUILD_VECTOR
8735       || N1.getOpcode() != ISD::BUILD_VECTOR)
8736     return SDValue();
8737
8738   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8739   EVT VT = N->getValueType(0);
8740   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8741     return SDValue();
8742
8743   // Check that the vector operands are of the right form.
8744   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8745   // operands, where N is the size of the formed vector.
8746   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8747   // index such that we have a pair wise add pattern.
8748
8749   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8750   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8751     return SDValue();
8752   SDValue Vec = N0->getOperand(0)->getOperand(0);
8753   SDNode *V = Vec.getNode();
8754   unsigned nextIndex = 0;
8755
8756   // For each operands to the ADD which are BUILD_VECTORs,
8757   // check to see if each of their operands are an EXTRACT_VECTOR with
8758   // the same vector and appropriate index.
8759   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8760     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8761         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8762
8763       SDValue ExtVec0 = N0->getOperand(i);
8764       SDValue ExtVec1 = N1->getOperand(i);
8765
8766       // First operand is the vector, verify its the same.
8767       if (V != ExtVec0->getOperand(0).getNode() ||
8768           V != ExtVec1->getOperand(0).getNode())
8769         return SDValue();
8770
8771       // Second is the constant, verify its correct.
8772       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8773       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8774
8775       // For the constant, we want to see all the even or all the odd.
8776       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8777           || C1->getZExtValue() != nextIndex+1)
8778         return SDValue();
8779
8780       // Increment index.
8781       nextIndex+=2;
8782     } else
8783       return SDValue();
8784   }
8785
8786   // Create VPADDL node.
8787   SelectionDAG &DAG = DCI.DAG;
8788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8789
8790   SDLoc dl(N);
8791
8792   // Build operand list.
8793   SmallVector<SDValue, 8> Ops;
8794   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8795                                 TLI.getPointerTy(DAG.getDataLayout())));
8796
8797   // Input is the vector.
8798   Ops.push_back(Vec);
8799
8800   // Get widened type and narrowed type.
8801   MVT widenType;
8802   unsigned numElem = VT.getVectorNumElements();
8803
8804   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8805   switch (inputLaneType.getSimpleVT().SimpleTy) {
8806     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8807     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8808     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8809     default:
8810       llvm_unreachable("Invalid vector element type for padd optimization.");
8811   }
8812
8813   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8814   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8815   return DAG.getNode(ExtOp, dl, VT, tmp);
8816 }
8817
8818 static SDValue findMUL_LOHI(SDValue V) {
8819   if (V->getOpcode() == ISD::UMUL_LOHI ||
8820       V->getOpcode() == ISD::SMUL_LOHI)
8821     return V;
8822   return SDValue();
8823 }
8824
8825 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8826                                      TargetLowering::DAGCombinerInfo &DCI,
8827                                      const ARMSubtarget *Subtarget) {
8828
8829   // Look for multiply add opportunities.
8830   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8831   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8832   // a glue link from the first add to the second add.
8833   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8834   // a S/UMLAL instruction.
8835   //                  UMUL_LOHI
8836   //                 / :lo    \ :hi
8837   //                /          \          [no multiline comment]
8838   //    loAdd ->  ADDE         |
8839   //                 \ :glue  /
8840   //                  \      /
8841   //                    ADDC   <- hiAdd
8842   //
8843   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8844   SDValue AddcOp0 = AddcNode->getOperand(0);
8845   SDValue AddcOp1 = AddcNode->getOperand(1);
8846
8847   // Check if the two operands are from the same mul_lohi node.
8848   if (AddcOp0.getNode() == AddcOp1.getNode())
8849     return SDValue();
8850
8851   assert(AddcNode->getNumValues() == 2 &&
8852          AddcNode->getValueType(0) == MVT::i32 &&
8853          "Expect ADDC with two result values. First: i32");
8854
8855   // Check that we have a glued ADDC node.
8856   if (AddcNode->getValueType(1) != MVT::Glue)
8857     return SDValue();
8858
8859   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8860   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8861       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8862       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8863       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8864     return SDValue();
8865
8866   // Look for the glued ADDE.
8867   SDNode* AddeNode = AddcNode->getGluedUser();
8868   if (!AddeNode)
8869     return SDValue();
8870
8871   // Make sure it is really an ADDE.
8872   if (AddeNode->getOpcode() != ISD::ADDE)
8873     return SDValue();
8874
8875   assert(AddeNode->getNumOperands() == 3 &&
8876          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8877          "ADDE node has the wrong inputs");
8878
8879   // Check for the triangle shape.
8880   SDValue AddeOp0 = AddeNode->getOperand(0);
8881   SDValue AddeOp1 = AddeNode->getOperand(1);
8882
8883   // Make sure that the ADDE operands are not coming from the same node.
8884   if (AddeOp0.getNode() == AddeOp1.getNode())
8885     return SDValue();
8886
8887   // Find the MUL_LOHI node walking up ADDE's operands.
8888   bool IsLeftOperandMUL = false;
8889   SDValue MULOp = findMUL_LOHI(AddeOp0);
8890   if (MULOp == SDValue())
8891    MULOp = findMUL_LOHI(AddeOp1);
8892   else
8893     IsLeftOperandMUL = true;
8894   if (MULOp == SDValue())
8895     return SDValue();
8896
8897   // Figure out the right opcode.
8898   unsigned Opc = MULOp->getOpcode();
8899   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8900
8901   // Figure out the high and low input values to the MLAL node.
8902   SDValue* HiAdd = nullptr;
8903   SDValue* LoMul = nullptr;
8904   SDValue* LowAdd = nullptr;
8905
8906   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8907   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8908     return SDValue();
8909
8910   if (IsLeftOperandMUL)
8911     HiAdd = &AddeOp1;
8912   else
8913     HiAdd = &AddeOp0;
8914
8915
8916   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8917   // whose low result is fed to the ADDC we are checking.
8918
8919   if (AddcOp0 == MULOp.getValue(0)) {
8920     LoMul = &AddcOp0;
8921     LowAdd = &AddcOp1;
8922   }
8923   if (AddcOp1 == MULOp.getValue(0)) {
8924     LoMul = &AddcOp1;
8925     LowAdd = &AddcOp0;
8926   }
8927
8928   if (!LoMul)
8929     return SDValue();
8930
8931   // Create the merged node.
8932   SelectionDAG &DAG = DCI.DAG;
8933
8934   // Build operand list.
8935   SmallVector<SDValue, 8> Ops;
8936   Ops.push_back(LoMul->getOperand(0));
8937   Ops.push_back(LoMul->getOperand(1));
8938   Ops.push_back(*LowAdd);
8939   Ops.push_back(*HiAdd);
8940
8941   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8942                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8943
8944   // Replace the ADDs' nodes uses by the MLA node's values.
8945   SDValue HiMLALResult(MLALNode.getNode(), 1);
8946   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8947
8948   SDValue LoMLALResult(MLALNode.getNode(), 0);
8949   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8950
8951   // Return original node to notify the driver to stop replacing.
8952   SDValue resNode(AddcNode, 0);
8953   return resNode;
8954 }
8955
8956 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode,
8957                                       TargetLowering::DAGCombinerInfo &DCI,
8958                                       const ARMSubtarget *Subtarget) {
8959   // UMAAL is similar to UMLAL except that it adds two unsigned values.
8960   // While trying to combine for the other MLAL nodes, first search for the
8961   // chance to use UMAAL. Check if Addc uses another addc node which can first
8962   // be combined into a UMLAL. The other pattern is AddcNode being combined
8963   // into an UMLAL and then using another addc is handled in ISelDAGToDAG.
8964
8965   if (!Subtarget->hasV6Ops())
8966     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8967
8968   SDNode *PrevAddc = nullptr;
8969   if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC)
8970     PrevAddc = AddcNode->getOperand(0).getNode();
8971   else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC)
8972     PrevAddc = AddcNode->getOperand(1).getNode();
8973
8974   // If there's no addc chains, just return a search for any MLAL.
8975   if (PrevAddc == nullptr)
8976     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8977
8978   // Try to convert the addc operand to an MLAL and if that fails try to
8979   // combine AddcNode.
8980   SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget);
8981   if (MLAL != SDValue(PrevAddc, 0))
8982     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
8983
8984   // Find the converted UMAAL or quit if it doesn't exist.
8985   SDNode *UmlalNode = nullptr;
8986   SDValue AddHi;
8987   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
8988     UmlalNode = AddcNode->getOperand(0).getNode();
8989     AddHi = AddcNode->getOperand(1);
8990   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
8991     UmlalNode = AddcNode->getOperand(1).getNode();
8992     AddHi = AddcNode->getOperand(0);
8993   } else {
8994     return SDValue();
8995   }
8996
8997   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
8998   // the ADDC as well as Zero.
8999   auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3));
9000
9001   if (!Zero || Zero->getZExtValue() != 0)
9002     return SDValue();
9003
9004   // Check that we have a glued ADDC node.
9005   if (AddcNode->getValueType(1) != MVT::Glue)
9006     return SDValue();
9007
9008   // Look for the glued ADDE.
9009   SDNode* AddeNode = AddcNode->getGluedUser();
9010   if (!AddeNode)
9011     return SDValue();
9012
9013   if ((AddeNode->getOperand(0).getNode() == Zero &&
9014        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9015       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9016        AddeNode->getOperand(1).getNode() == Zero)) {
9017
9018     SelectionDAG &DAG = DCI.DAG;
9019     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9020                       UmlalNode->getOperand(2), AddHi };
9021     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9022                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9023
9024     // Replace the ADDs' nodes uses by the UMAAL node's values.
9025     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9026     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9027
9028     // Return original node to notify the driver to stop replacing.
9029     return SDValue(AddcNode, 0);
9030   }
9031   return SDValue();
9032 }
9033
9034 /// PerformADDCCombine - Target-specific dag combine transform from
9035 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or
9036 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9037 static SDValue PerformADDCCombine(SDNode *N,
9038                                  TargetLowering::DAGCombinerInfo &DCI,
9039                                  const ARMSubtarget *Subtarget) {
9040
9041   if (Subtarget->isThumb1Only()) return SDValue();
9042
9043   // Only perform the checks after legalize when the pattern is available.
9044   if (DCI.isBeforeLegalize()) return SDValue();
9045
9046   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9047 }
9048
9049 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9050 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9051 /// called with the default operands, and if that fails, with commuted
9052 /// operands.
9053 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9054                                           TargetLowering::DAGCombinerInfo &DCI,
9055                                           const ARMSubtarget *Subtarget){
9056
9057   // Attempt to create vpaddl for this add.
9058   if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
9059     return Result;
9060
9061   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9062   if (N0.getNode()->hasOneUse())
9063     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9064       return Result;
9065   return SDValue();
9066 }
9067
9068 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9069 ///
9070 static SDValue PerformADDCombine(SDNode *N,
9071                                  TargetLowering::DAGCombinerInfo &DCI,
9072                                  const ARMSubtarget *Subtarget) {
9073   SDValue N0 = N->getOperand(0);
9074   SDValue N1 = N->getOperand(1);
9075
9076   // First try with the default operand order.
9077   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9078     return Result;
9079
9080   // If that didn't work, try again with the operands commuted.
9081   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9082 }
9083
9084 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9085 ///
9086 static SDValue PerformSUBCombine(SDNode *N,
9087                                  TargetLowering::DAGCombinerInfo &DCI) {
9088   SDValue N0 = N->getOperand(0);
9089   SDValue N1 = N->getOperand(1);
9090
9091   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9092   if (N1.getNode()->hasOneUse())
9093     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9094       return Result;
9095
9096   return SDValue();
9097 }
9098
9099 /// PerformVMULCombine
9100 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9101 /// special multiplier accumulator forwarding.
9102 ///   vmul d3, d0, d2
9103 ///   vmla d3, d1, d2
9104 /// is faster than
9105 ///   vadd d3, d0, d1
9106 ///   vmul d3, d3, d2
9107 //  However, for (A + B) * (A + B),
9108 //    vadd d2, d0, d1
9109 //    vmul d3, d0, d2
9110 //    vmla d3, d1, d2
9111 //  is slower than
9112 //    vadd d2, d0, d1
9113 //    vmul d3, d2, d2
9114 static SDValue PerformVMULCombine(SDNode *N,
9115                                   TargetLowering::DAGCombinerInfo &DCI,
9116                                   const ARMSubtarget *Subtarget) {
9117   if (!Subtarget->hasVMLxForwarding())
9118     return SDValue();
9119
9120   SelectionDAG &DAG = DCI.DAG;
9121   SDValue N0 = N->getOperand(0);
9122   SDValue N1 = N->getOperand(1);
9123   unsigned Opcode = N0.getOpcode();
9124   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9125       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9126     Opcode = N1.getOpcode();
9127     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9128         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9129       return SDValue();
9130     std::swap(N0, N1);
9131   }
9132
9133   if (N0 == N1)
9134     return SDValue();
9135
9136   EVT VT = N->getValueType(0);
9137   SDLoc DL(N);
9138   SDValue N00 = N0->getOperand(0);
9139   SDValue N01 = N0->getOperand(1);
9140   return DAG.getNode(Opcode, DL, VT,
9141                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9142                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9143 }
9144
9145 static SDValue PerformMULCombine(SDNode *N,
9146                                  TargetLowering::DAGCombinerInfo &DCI,
9147                                  const ARMSubtarget *Subtarget) {
9148   SelectionDAG &DAG = DCI.DAG;
9149
9150   if (Subtarget->isThumb1Only())
9151     return SDValue();
9152
9153   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9154     return SDValue();
9155
9156   EVT VT = N->getValueType(0);
9157   if (VT.is64BitVector() || VT.is128BitVector())
9158     return PerformVMULCombine(N, DCI, Subtarget);
9159   if (VT != MVT::i32)
9160     return SDValue();
9161
9162   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9163   if (!C)
9164     return SDValue();
9165
9166   int64_t MulAmt = C->getSExtValue();
9167   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9168
9169   ShiftAmt = ShiftAmt & (32 - 1);
9170   SDValue V = N->getOperand(0);
9171   SDLoc DL(N);
9172
9173   SDValue Res;
9174   MulAmt >>= ShiftAmt;
9175
9176   if (MulAmt >= 0) {
9177     if (isPowerOf2_32(MulAmt - 1)) {
9178       // (mul x, 2^N + 1) => (add (shl x, N), x)
9179       Res = DAG.getNode(ISD::ADD, DL, VT,
9180                         V,
9181                         DAG.getNode(ISD::SHL, DL, VT,
9182                                     V,
9183                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9184                                                     MVT::i32)));
9185     } else if (isPowerOf2_32(MulAmt + 1)) {
9186       // (mul x, 2^N - 1) => (sub (shl x, N), x)
9187       Res = DAG.getNode(ISD::SUB, DL, VT,
9188                         DAG.getNode(ISD::SHL, DL, VT,
9189                                     V,
9190                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
9191                                                     MVT::i32)),
9192                         V);
9193     } else
9194       return SDValue();
9195   } else {
9196     uint64_t MulAmtAbs = -MulAmt;
9197     if (isPowerOf2_32(MulAmtAbs + 1)) {
9198       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9199       Res = DAG.getNode(ISD::SUB, DL, VT,
9200                         V,
9201                         DAG.getNode(ISD::SHL, DL, VT,
9202                                     V,
9203                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9204                                                     MVT::i32)));
9205     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9206       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9207       Res = DAG.getNode(ISD::ADD, DL, VT,
9208                         V,
9209                         DAG.getNode(ISD::SHL, DL, VT,
9210                                     V,
9211                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9212                                                     MVT::i32)));
9213       Res = DAG.getNode(ISD::SUB, DL, VT,
9214                         DAG.getConstant(0, DL, MVT::i32), Res);
9215
9216     } else
9217       return SDValue();
9218   }
9219
9220   if (ShiftAmt != 0)
9221     Res = DAG.getNode(ISD::SHL, DL, VT,
9222                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9223
9224   // Do not add new nodes to DAG combiner worklist.
9225   DCI.CombineTo(N, Res, false);
9226   return SDValue();
9227 }
9228
9229 static SDValue PerformANDCombine(SDNode *N,
9230                                  TargetLowering::DAGCombinerInfo &DCI,
9231                                  const ARMSubtarget *Subtarget) {
9232
9233   // Attempt to use immediate-form VBIC
9234   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9235   SDLoc dl(N);
9236   EVT VT = N->getValueType(0);
9237   SelectionDAG &DAG = DCI.DAG;
9238
9239   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9240     return SDValue();
9241
9242   APInt SplatBits, SplatUndef;
9243   unsigned SplatBitSize;
9244   bool HasAnyUndefs;
9245   if (BVN &&
9246       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9247     if (SplatBitSize <= 64) {
9248       EVT VbicVT;
9249       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9250                                       SplatUndef.getZExtValue(), SplatBitSize,
9251                                       DAG, dl, VbicVT, VT.is128BitVector(),
9252                                       OtherModImm);
9253       if (Val.getNode()) {
9254         SDValue Input =
9255           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9256         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9257         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9258       }
9259     }
9260   }
9261
9262   if (!Subtarget->isThumb1Only()) {
9263     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9264     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9265       return Result;
9266   }
9267
9268   return SDValue();
9269 }
9270
9271 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
9272 static SDValue PerformORCombine(SDNode *N,
9273                                 TargetLowering::DAGCombinerInfo &DCI,
9274                                 const ARMSubtarget *Subtarget) {
9275   // Attempt to use immediate-form VORR
9276   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9277   SDLoc dl(N);
9278   EVT VT = N->getValueType(0);
9279   SelectionDAG &DAG = DCI.DAG;
9280
9281   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9282     return SDValue();
9283
9284   APInt SplatBits, SplatUndef;
9285   unsigned SplatBitSize;
9286   bool HasAnyUndefs;
9287   if (BVN && Subtarget->hasNEON() &&
9288       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9289     if (SplatBitSize <= 64) {
9290       EVT VorrVT;
9291       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9292                                       SplatUndef.getZExtValue(), SplatBitSize,
9293                                       DAG, dl, VorrVT, VT.is128BitVector(),
9294                                       OtherModImm);
9295       if (Val.getNode()) {
9296         SDValue Input =
9297           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9298         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9299         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9300       }
9301     }
9302   }
9303
9304   if (!Subtarget->isThumb1Only()) {
9305     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9306     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9307       return Result;
9308   }
9309
9310   // The code below optimizes (or (and X, Y), Z).
9311   // The AND operand needs to have a single user to make these optimizations
9312   // profitable.
9313   SDValue N0 = N->getOperand(0);
9314   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9315     return SDValue();
9316   SDValue N1 = N->getOperand(1);
9317
9318   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9319   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9320       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9321     APInt SplatUndef;
9322     unsigned SplatBitSize;
9323     bool HasAnyUndefs;
9324
9325     APInt SplatBits0, SplatBits1;
9326     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9327     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9328     // Ensure that the second operand of both ands are constants
9329     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9330                                       HasAnyUndefs) && !HasAnyUndefs) {
9331         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9332                                           HasAnyUndefs) && !HasAnyUndefs) {
9333             // Ensure that the bit width of the constants are the same and that
9334             // the splat arguments are logical inverses as per the pattern we
9335             // are trying to simplify.
9336             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9337                 SplatBits0 == ~SplatBits1) {
9338                 // Canonicalize the vector type to make instruction selection
9339                 // simpler.
9340                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9341                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9342                                              N0->getOperand(1),
9343                                              N0->getOperand(0),
9344                                              N1->getOperand(0));
9345                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9346             }
9347         }
9348     }
9349   }
9350
9351   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9352   // reasonable.
9353
9354   // BFI is only available on V6T2+
9355   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9356     return SDValue();
9357
9358   SDLoc DL(N);
9359   // 1) or (and A, mask), val => ARMbfi A, val, mask
9360   //      iff (val & mask) == val
9361   //
9362   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9363   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9364   //          && mask == ~mask2
9365   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9366   //          && ~mask == mask2
9367   //  (i.e., copy a bitfield value into another bitfield of the same width)
9368
9369   if (VT != MVT::i32)
9370     return SDValue();
9371
9372   SDValue N00 = N0.getOperand(0);
9373
9374   // The value and the mask need to be constants so we can verify this is
9375   // actually a bitfield set. If the mask is 0xffff, we can do better
9376   // via a movt instruction, so don't use BFI in that case.
9377   SDValue MaskOp = N0.getOperand(1);
9378   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9379   if (!MaskC)
9380     return SDValue();
9381   unsigned Mask = MaskC->getZExtValue();
9382   if (Mask == 0xffff)
9383     return SDValue();
9384   SDValue Res;
9385   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9386   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9387   if (N1C) {
9388     unsigned Val = N1C->getZExtValue();
9389     if ((Val & ~Mask) != Val)
9390       return SDValue();
9391
9392     if (ARM::isBitFieldInvertedMask(Mask)) {
9393       Val >>= countTrailingZeros(~Mask);
9394
9395       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9396                         DAG.getConstant(Val, DL, MVT::i32),
9397                         DAG.getConstant(Mask, DL, MVT::i32));
9398
9399       // Do not add new nodes to DAG combiner worklist.
9400       DCI.CombineTo(N, Res, false);
9401       return SDValue();
9402     }
9403   } else if (N1.getOpcode() == ISD::AND) {
9404     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9405     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9406     if (!N11C)
9407       return SDValue();
9408     unsigned Mask2 = N11C->getZExtValue();
9409
9410     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9411     // as is to match.
9412     if (ARM::isBitFieldInvertedMask(Mask) &&
9413         (Mask == ~Mask2)) {
9414       // The pack halfword instruction works better for masks that fit it,
9415       // so use that when it's available.
9416       if (Subtarget->hasT2ExtractPack() &&
9417           (Mask == 0xffff || Mask == 0xffff0000))
9418         return SDValue();
9419       // 2a
9420       unsigned amt = countTrailingZeros(Mask2);
9421       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9422                         DAG.getConstant(amt, DL, MVT::i32));
9423       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9424                         DAG.getConstant(Mask, DL, MVT::i32));
9425       // Do not add new nodes to DAG combiner worklist.
9426       DCI.CombineTo(N, Res, false);
9427       return SDValue();
9428     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9429                (~Mask == Mask2)) {
9430       // The pack halfword instruction works better for masks that fit it,
9431       // so use that when it's available.
9432       if (Subtarget->hasT2ExtractPack() &&
9433           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9434         return SDValue();
9435       // 2b
9436       unsigned lsb = countTrailingZeros(Mask);
9437       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9438                         DAG.getConstant(lsb, DL, MVT::i32));
9439       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9440                         DAG.getConstant(Mask2, DL, MVT::i32));
9441       // Do not add new nodes to DAG combiner worklist.
9442       DCI.CombineTo(N, Res, false);
9443       return SDValue();
9444     }
9445   }
9446
9447   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9448       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9449       ARM::isBitFieldInvertedMask(~Mask)) {
9450     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9451     // where lsb(mask) == #shamt and masked bits of B are known zero.
9452     SDValue ShAmt = N00.getOperand(1);
9453     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9454     unsigned LSB = countTrailingZeros(Mask);
9455     if (ShAmtC != LSB)
9456       return SDValue();
9457
9458     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9459                       DAG.getConstant(~Mask, DL, MVT::i32));
9460
9461     // Do not add new nodes to DAG combiner worklist.
9462     DCI.CombineTo(N, Res, false);
9463   }
9464
9465   return SDValue();
9466 }
9467
9468 static SDValue PerformXORCombine(SDNode *N,
9469                                  TargetLowering::DAGCombinerInfo &DCI,
9470                                  const ARMSubtarget *Subtarget) {
9471   EVT VT = N->getValueType(0);
9472   SelectionDAG &DAG = DCI.DAG;
9473
9474   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9475     return SDValue();
9476
9477   if (!Subtarget->isThumb1Only()) {
9478     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9479     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9480       return Result;
9481   }
9482
9483   return SDValue();
9484 }
9485
9486 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9487 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9488 // their position in "to" (Rd).
9489 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9490   assert(N->getOpcode() == ARMISD::BFI);
9491
9492   SDValue From = N->getOperand(1);
9493   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9494   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9495
9496   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9497   // #C in the base of the SHR.
9498   if (From->getOpcode() == ISD::SRL &&
9499       isa<ConstantSDNode>(From->getOperand(1))) {
9500     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9501     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9502     FromMask <<= Shift.getLimitedValue(31);
9503     From = From->getOperand(0);
9504   }
9505
9506   return From;
9507 }
9508
9509 // If A and B contain one contiguous set of bits, does A | B == A . B?
9510 //
9511 // Neither A nor B must be zero.
9512 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9513   unsigned LastActiveBitInA =  A.countTrailingZeros();
9514   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9515   return LastActiveBitInA - 1 == FirstActiveBitInB;
9516 }
9517
9518 static SDValue FindBFIToCombineWith(SDNode *N) {
9519   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9520   // if one exists.
9521   APInt ToMask, FromMask;
9522   SDValue From = ParseBFI(N, ToMask, FromMask);
9523   SDValue To = N->getOperand(0);
9524
9525   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9526   // aren't compatible, but not if they set the same bit in their destination as
9527   // we do (or that of any BFI we're going to combine with).
9528   SDValue V = To;
9529   APInt CombinedToMask = ToMask;
9530   while (V.getOpcode() == ARMISD::BFI) {
9531     APInt NewToMask, NewFromMask;
9532     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9533     if (NewFrom != From) {
9534       // This BFI has a different base. Keep going.
9535       CombinedToMask |= NewToMask;
9536       V = V.getOperand(0);
9537       continue;
9538     }
9539
9540     // Do the written bits conflict with any we've seen so far?
9541     if ((NewToMask & CombinedToMask).getBoolValue())
9542       // Conflicting bits - bail out because going further is unsafe.
9543       return SDValue();
9544
9545     // Are the new bits contiguous when combined with the old bits?
9546     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9547         BitsProperlyConcatenate(FromMask, NewFromMask))
9548       return V;
9549     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9550         BitsProperlyConcatenate(NewFromMask, FromMask))
9551       return V;
9552
9553     // We've seen a write to some bits, so track it.
9554     CombinedToMask |= NewToMask;
9555     // Keep going...
9556     V = V.getOperand(0);
9557   }
9558
9559   return SDValue();
9560 }
9561
9562 static SDValue PerformBFICombine(SDNode *N,
9563                                  TargetLowering::DAGCombinerInfo &DCI) {
9564   SDValue N1 = N->getOperand(1);
9565   if (N1.getOpcode() == ISD::AND) {
9566     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9567     // the bits being cleared by the AND are not demanded by the BFI.
9568     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9569     if (!N11C)
9570       return SDValue();
9571     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9572     unsigned LSB = countTrailingZeros(~InvMask);
9573     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9574     assert(Width <
9575                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9576            "undefined behavior");
9577     unsigned Mask = (1u << Width) - 1;
9578     unsigned Mask2 = N11C->getZExtValue();
9579     if ((Mask & (~Mask2)) == 0)
9580       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9581                              N->getOperand(0), N1.getOperand(0),
9582                              N->getOperand(2));
9583   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9584     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9585     // Keep track of any consecutive bits set that all come from the same base
9586     // value. We can combine these together into a single BFI.
9587     SDValue CombineBFI = FindBFIToCombineWith(N);
9588     if (CombineBFI == SDValue())
9589       return SDValue();
9590
9591     // We've found a BFI.
9592     APInt ToMask1, FromMask1;
9593     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9594
9595     APInt ToMask2, FromMask2;
9596     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9597     assert(From1 == From2);
9598     (void)From2;
9599
9600     // First, unlink CombineBFI.
9601     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9602     // Then create a new BFI, combining the two together.
9603     APInt NewFromMask = FromMask1 | FromMask2;
9604     APInt NewToMask = ToMask1 | ToMask2;
9605
9606     EVT VT = N->getValueType(0);
9607     SDLoc dl(N);
9608
9609     if (NewFromMask[0] == 0)
9610       From1 = DCI.DAG.getNode(
9611         ISD::SRL, dl, VT, From1,
9612         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
9613     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
9614                            DCI.DAG.getConstant(~NewToMask, dl, VT));
9615   }
9616   return SDValue();
9617 }
9618
9619 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9620 /// ARMISD::VMOVRRD.
9621 static SDValue PerformVMOVRRDCombine(SDNode *N,
9622                                      TargetLowering::DAGCombinerInfo &DCI,
9623                                      const ARMSubtarget *Subtarget) {
9624   // vmovrrd(vmovdrr x, y) -> x,y
9625   SDValue InDouble = N->getOperand(0);
9626   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9627     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9628
9629   // vmovrrd(load f64) -> (load i32), (load i32)
9630   SDNode *InNode = InDouble.getNode();
9631   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9632       InNode->getValueType(0) == MVT::f64 &&
9633       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9634       !cast<LoadSDNode>(InNode)->isVolatile()) {
9635     // TODO: Should this be done for non-FrameIndex operands?
9636     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9637
9638     SelectionDAG &DAG = DCI.DAG;
9639     SDLoc DL(LD);
9640     SDValue BasePtr = LD->getBasePtr();
9641     SDValue NewLD1 =
9642         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
9643                     LD->getAlignment(), LD->getMemOperand()->getFlags());
9644
9645     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9646                                     DAG.getConstant(4, DL, MVT::i32));
9647     SDValue NewLD2 = DAG.getLoad(
9648         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
9649         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
9650
9651     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9652     if (DCI.DAG.getDataLayout().isBigEndian())
9653       std::swap (NewLD1, NewLD2);
9654     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9655     return Result;
9656   }
9657
9658   return SDValue();
9659 }
9660
9661 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9662 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9663 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9664   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9665   SDValue Op0 = N->getOperand(0);
9666   SDValue Op1 = N->getOperand(1);
9667   if (Op0.getOpcode() == ISD::BITCAST)
9668     Op0 = Op0.getOperand(0);
9669   if (Op1.getOpcode() == ISD::BITCAST)
9670     Op1 = Op1.getOperand(0);
9671   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9672       Op0.getNode() == Op1.getNode() &&
9673       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9674     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9675                        N->getValueType(0), Op0.getOperand(0));
9676   return SDValue();
9677 }
9678
9679 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9680 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9681 /// i64 vector to have f64 elements, since the value can then be loaded
9682 /// directly into a VFP register.
9683 static bool hasNormalLoadOperand(SDNode *N) {
9684   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9685   for (unsigned i = 0; i < NumElts; ++i) {
9686     SDNode *Elt = N->getOperand(i).getNode();
9687     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9688       return true;
9689   }
9690   return false;
9691 }
9692
9693 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9694 /// ISD::BUILD_VECTOR.
9695 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9696                                           TargetLowering::DAGCombinerInfo &DCI,
9697                                           const ARMSubtarget *Subtarget) {
9698   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9699   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9700   // into a pair of GPRs, which is fine when the value is used as a scalar,
9701   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9702   SelectionDAG &DAG = DCI.DAG;
9703   if (N->getNumOperands() == 2)
9704     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
9705       return RV;
9706
9707   // Load i64 elements as f64 values so that type legalization does not split
9708   // them up into i32 values.
9709   EVT VT = N->getValueType(0);
9710   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9711     return SDValue();
9712   SDLoc dl(N);
9713   SmallVector<SDValue, 8> Ops;
9714   unsigned NumElts = VT.getVectorNumElements();
9715   for (unsigned i = 0; i < NumElts; ++i) {
9716     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9717     Ops.push_back(V);
9718     // Make the DAGCombiner fold the bitcast.
9719     DCI.AddToWorklist(V.getNode());
9720   }
9721   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9722   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
9723   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9724 }
9725
9726 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9727 static SDValue
9728 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9729   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9730   // At that time, we may have inserted bitcasts from integer to float.
9731   // If these bitcasts have survived DAGCombine, change the lowering of this
9732   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9733   // force to use floating point types.
9734
9735   // Make sure we can change the type of the vector.
9736   // This is possible iff:
9737   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9738   //    1.1. Vector is used only once.
9739   //    1.2. Use is a bit convert to an integer type.
9740   // 2. The size of its operands are 32-bits (64-bits are not legal).
9741   EVT VT = N->getValueType(0);
9742   EVT EltVT = VT.getVectorElementType();
9743
9744   // Check 1.1. and 2.
9745   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9746     return SDValue();
9747
9748   // By construction, the input type must be float.
9749   assert(EltVT == MVT::f32 && "Unexpected type!");
9750
9751   // Check 1.2.
9752   SDNode *Use = *N->use_begin();
9753   if (Use->getOpcode() != ISD::BITCAST ||
9754       Use->getValueType(0).isFloatingPoint())
9755     return SDValue();
9756
9757   // Check profitability.
9758   // Model is, if more than half of the relevant operands are bitcast from
9759   // i32, turn the build_vector into a sequence of insert_vector_elt.
9760   // Relevant operands are everything that is not statically
9761   // (i.e., at compile time) bitcasted.
9762   unsigned NumOfBitCastedElts = 0;
9763   unsigned NumElts = VT.getVectorNumElements();
9764   unsigned NumOfRelevantElts = NumElts;
9765   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9766     SDValue Elt = N->getOperand(Idx);
9767     if (Elt->getOpcode() == ISD::BITCAST) {
9768       // Assume only bit cast to i32 will go away.
9769       if (Elt->getOperand(0).getValueType() == MVT::i32)
9770         ++NumOfBitCastedElts;
9771     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
9772       // Constants are statically casted, thus do not count them as
9773       // relevant operands.
9774       --NumOfRelevantElts;
9775   }
9776
9777   // Check if more than half of the elements require a non-free bitcast.
9778   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9779     return SDValue();
9780
9781   SelectionDAG &DAG = DCI.DAG;
9782   // Create the new vector type.
9783   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9784   // Check if the type is legal.
9785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9786   if (!TLI.isTypeLegal(VecVT))
9787     return SDValue();
9788
9789   // Combine:
9790   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9791   // => BITCAST INSERT_VECTOR_ELT
9792   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9793   //                      (BITCAST EN), N.
9794   SDValue Vec = DAG.getUNDEF(VecVT);
9795   SDLoc dl(N);
9796   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9797     SDValue V = N->getOperand(Idx);
9798     if (V.isUndef())
9799       continue;
9800     if (V.getOpcode() == ISD::BITCAST &&
9801         V->getOperand(0).getValueType() == MVT::i32)
9802       // Fold obvious case.
9803       V = V.getOperand(0);
9804     else {
9805       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9806       // Make the DAGCombiner fold the bitcasts.
9807       DCI.AddToWorklist(V.getNode());
9808     }
9809     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9810     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9811   }
9812   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9813   // Make the DAGCombiner fold the bitcasts.
9814   DCI.AddToWorklist(Vec.getNode());
9815   return Vec;
9816 }
9817
9818 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9819 /// ISD::INSERT_VECTOR_ELT.
9820 static SDValue PerformInsertEltCombine(SDNode *N,
9821                                        TargetLowering::DAGCombinerInfo &DCI) {
9822   // Bitcast an i64 load inserted into a vector to f64.
9823   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9824   EVT VT = N->getValueType(0);
9825   SDNode *Elt = N->getOperand(1).getNode();
9826   if (VT.getVectorElementType() != MVT::i64 ||
9827       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9828     return SDValue();
9829
9830   SelectionDAG &DAG = DCI.DAG;
9831   SDLoc dl(N);
9832   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9833                                  VT.getVectorNumElements());
9834   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9835   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9836   // Make the DAGCombiner fold the bitcasts.
9837   DCI.AddToWorklist(Vec.getNode());
9838   DCI.AddToWorklist(V.getNode());
9839   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9840                                Vec, V, N->getOperand(2));
9841   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9842 }
9843
9844 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9845 /// ISD::VECTOR_SHUFFLE.
9846 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9847   // The LLVM shufflevector instruction does not require the shuffle mask
9848   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9849   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9850   // operands do not match the mask length, they are extended by concatenating
9851   // them with undef vectors.  That is probably the right thing for other
9852   // targets, but for NEON it is better to concatenate two double-register
9853   // size vector operands into a single quad-register size vector.  Do that
9854   // transformation here:
9855   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9856   //   shuffle(concat(v1, v2), undef)
9857   SDValue Op0 = N->getOperand(0);
9858   SDValue Op1 = N->getOperand(1);
9859   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9860       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9861       Op0.getNumOperands() != 2 ||
9862       Op1.getNumOperands() != 2)
9863     return SDValue();
9864   SDValue Concat0Op1 = Op0.getOperand(1);
9865   SDValue Concat1Op1 = Op1.getOperand(1);
9866   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
9867     return SDValue();
9868   // Skip the transformation if any of the types are illegal.
9869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9870   EVT VT = N->getValueType(0);
9871   if (!TLI.isTypeLegal(VT) ||
9872       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9873       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9874     return SDValue();
9875
9876   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9877                                   Op0.getOperand(0), Op1.getOperand(0));
9878   // Translate the shuffle mask.
9879   SmallVector<int, 16> NewMask;
9880   unsigned NumElts = VT.getVectorNumElements();
9881   unsigned HalfElts = NumElts/2;
9882   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9883   for (unsigned n = 0; n < NumElts; ++n) {
9884     int MaskElt = SVN->getMaskElt(n);
9885     int NewElt = -1;
9886     if (MaskElt < (int)HalfElts)
9887       NewElt = MaskElt;
9888     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9889       NewElt = HalfElts + MaskElt - NumElts;
9890     NewMask.push_back(NewElt);
9891   }
9892   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9893                               DAG.getUNDEF(VT), NewMask);
9894 }
9895
9896 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9897 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9898 /// base address updates.
9899 /// For generic load/stores, the memory type is assumed to be a vector.
9900 /// The caller is assumed to have checked legality.
9901 static SDValue CombineBaseUpdate(SDNode *N,
9902                                  TargetLowering::DAGCombinerInfo &DCI) {
9903   SelectionDAG &DAG = DCI.DAG;
9904   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9905                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9906   const bool isStore = N->getOpcode() == ISD::STORE;
9907   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9908   SDValue Addr = N->getOperand(AddrOpIdx);
9909   MemSDNode *MemN = cast<MemSDNode>(N);
9910   SDLoc dl(N);
9911
9912   // Search for a use of the address operand that is an increment.
9913   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9914          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9915     SDNode *User = *UI;
9916     if (User->getOpcode() != ISD::ADD ||
9917         UI.getUse().getResNo() != Addr.getResNo())
9918       continue;
9919
9920     // Check that the add is independent of the load/store.  Otherwise, folding
9921     // it would create a cycle.
9922     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9923       continue;
9924
9925     // Find the new opcode for the updating load/store.
9926     bool isLoadOp = true;
9927     bool isLaneOp = false;
9928     unsigned NewOpc = 0;
9929     unsigned NumVecs = 0;
9930     if (isIntrinsic) {
9931       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9932       switch (IntNo) {
9933       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9934       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9935         NumVecs = 1; break;
9936       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9937         NumVecs = 2; break;
9938       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9939         NumVecs = 3; break;
9940       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9941         NumVecs = 4; break;
9942       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9943         NumVecs = 2; isLaneOp = true; break;
9944       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9945         NumVecs = 3; isLaneOp = true; break;
9946       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9947         NumVecs = 4; isLaneOp = true; break;
9948       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9949         NumVecs = 1; isLoadOp = false; break;
9950       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9951         NumVecs = 2; isLoadOp = false; break;
9952       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9953         NumVecs = 3; isLoadOp = false; break;
9954       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9955         NumVecs = 4; isLoadOp = false; break;
9956       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9957         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9958       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9959         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9960       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9961         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9962       }
9963     } else {
9964       isLaneOp = true;
9965       switch (N->getOpcode()) {
9966       default: llvm_unreachable("unexpected opcode for Neon base update");
9967       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9968       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9969       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9970       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9971         NumVecs = 1; isLaneOp = false; break;
9972       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9973         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9974       }
9975     }
9976
9977     // Find the size of memory referenced by the load/store.
9978     EVT VecTy;
9979     if (isLoadOp) {
9980       VecTy = N->getValueType(0);
9981     } else if (isIntrinsic) {
9982       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9983     } else {
9984       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9985       VecTy = N->getOperand(1).getValueType();
9986     }
9987
9988     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9989     if (isLaneOp)
9990       NumBytes /= VecTy.getVectorNumElements();
9991
9992     // If the increment is a constant, it must match the memory ref size.
9993     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9994     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9995       uint64_t IncVal = CInc->getZExtValue();
9996       if (IncVal != NumBytes)
9997         continue;
9998     } else if (NumBytes >= 3 * 16) {
9999       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10000       // separate instructions that make it harder to use a non-constant update.
10001       continue;
10002     }
10003
10004     // OK, we found an ADD we can fold into the base update.
10005     // Now, create a _UPD node, taking care of not breaking alignment.
10006
10007     EVT AlignedVecTy = VecTy;
10008     unsigned Alignment = MemN->getAlignment();
10009
10010     // If this is a less-than-standard-aligned load/store, change the type to
10011     // match the standard alignment.
10012     // The alignment is overlooked when selecting _UPD variants; and it's
10013     // easier to introduce bitcasts here than fix that.
10014     // There are 3 ways to get to this base-update combine:
10015     // - intrinsics: they are assumed to be properly aligned (to the standard
10016     //   alignment of the memory type), so we don't need to do anything.
10017     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10018     //   intrinsics, so, likewise, there's nothing to do.
10019     // - generic load/store instructions: the alignment is specified as an
10020     //   explicit operand, rather than implicitly as the standard alignment
10021     //   of the memory type (like the intrisics).  We need to change the
10022     //   memory type to match the explicit alignment.  That way, we don't
10023     //   generate non-standard-aligned ARMISD::VLDx nodes.
10024     if (isa<LSBaseSDNode>(N)) {
10025       if (Alignment == 0)
10026         Alignment = 1;
10027       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10028         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10029         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10030         assert(!isLaneOp && "Unexpected generic load/store lane.");
10031         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10032         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10033       }
10034       // Don't set an explicit alignment on regular load/stores that we want
10035       // to transform to VLD/VST 1_UPD nodes.
10036       // This matches the behavior of regular load/stores, which only get an
10037       // explicit alignment if the MMO alignment is larger than the standard
10038       // alignment of the memory type.
10039       // Intrinsics, however, always get an explicit alignment, set to the
10040       // alignment of the MMO.
10041       Alignment = 1;
10042     }
10043
10044     // Create the new updating load/store node.
10045     // First, create an SDVTList for the new updating node's results.
10046     EVT Tys[6];
10047     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10048     unsigned n;
10049     for (n = 0; n < NumResultVecs; ++n)
10050       Tys[n] = AlignedVecTy;
10051     Tys[n++] = MVT::i32;
10052     Tys[n] = MVT::Other;
10053     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10054
10055     // Then, gather the new node's operands.
10056     SmallVector<SDValue, 8> Ops;
10057     Ops.push_back(N->getOperand(0)); // incoming chain
10058     Ops.push_back(N->getOperand(AddrOpIdx));
10059     Ops.push_back(Inc);
10060
10061     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10062       // Try to match the intrinsic's signature
10063       Ops.push_back(StN->getValue());
10064     } else {
10065       // Loads (and of course intrinsics) match the intrinsics' signature,
10066       // so just add all but the alignment operand.
10067       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10068         Ops.push_back(N->getOperand(i));
10069     }
10070
10071     // For all node types, the alignment operand is always the last one.
10072     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10073
10074     // If this is a non-standard-aligned STORE, the penultimate operand is the
10075     // stored value.  Bitcast it to the aligned type.
10076     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10077       SDValue &StVal = Ops[Ops.size()-2];
10078       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10079     }
10080
10081     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
10082                                            Ops, AlignedVecTy,
10083                                            MemN->getMemOperand());
10084
10085     // Update the uses.
10086     SmallVector<SDValue, 5> NewResults;
10087     for (unsigned i = 0; i < NumResultVecs; ++i)
10088       NewResults.push_back(SDValue(UpdN.getNode(), i));
10089
10090     // If this is an non-standard-aligned LOAD, the first result is the loaded
10091     // value.  Bitcast it to the expected result type.
10092     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10093       SDValue &LdVal = NewResults[0];
10094       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10095     }
10096
10097     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10098     DCI.CombineTo(N, NewResults);
10099     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10100
10101     break;
10102   }
10103   return SDValue();
10104 }
10105
10106 static SDValue PerformVLDCombine(SDNode *N,
10107                                  TargetLowering::DAGCombinerInfo &DCI) {
10108   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10109     return SDValue();
10110
10111   return CombineBaseUpdate(N, DCI);
10112 }
10113
10114 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10115 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10116 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10117 /// return true.
10118 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10119   SelectionDAG &DAG = DCI.DAG;
10120   EVT VT = N->getValueType(0);
10121   // vldN-dup instructions only support 64-bit vectors for N > 1.
10122   if (!VT.is64BitVector())
10123     return false;
10124
10125   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10126   SDNode *VLD = N->getOperand(0).getNode();
10127   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10128     return false;
10129   unsigned NumVecs = 0;
10130   unsigned NewOpc = 0;
10131   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10132   if (IntNo == Intrinsic::arm_neon_vld2lane) {
10133     NumVecs = 2;
10134     NewOpc = ARMISD::VLD2DUP;
10135   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10136     NumVecs = 3;
10137     NewOpc = ARMISD::VLD3DUP;
10138   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10139     NumVecs = 4;
10140     NewOpc = ARMISD::VLD4DUP;
10141   } else {
10142     return false;
10143   }
10144
10145   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10146   // numbers match the load.
10147   unsigned VLDLaneNo =
10148     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10149   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10150        UI != UE; ++UI) {
10151     // Ignore uses of the chain result.
10152     if (UI.getUse().getResNo() == NumVecs)
10153       continue;
10154     SDNode *User = *UI;
10155     if (User->getOpcode() != ARMISD::VDUPLANE ||
10156         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10157       return false;
10158   }
10159
10160   // Create the vldN-dup node.
10161   EVT Tys[5];
10162   unsigned n;
10163   for (n = 0; n < NumVecs; ++n)
10164     Tys[n] = VT;
10165   Tys[n] = MVT::Other;
10166   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10167   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10168   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10169   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10170                                            Ops, VLDMemInt->getMemoryVT(),
10171                                            VLDMemInt->getMemOperand());
10172
10173   // Update the uses.
10174   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10175        UI != UE; ++UI) {
10176     unsigned ResNo = UI.getUse().getResNo();
10177     // Ignore uses of the chain result.
10178     if (ResNo == NumVecs)
10179       continue;
10180     SDNode *User = *UI;
10181     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10182   }
10183
10184   // Now the vldN-lane intrinsic is dead except for its chain result.
10185   // Update uses of the chain.
10186   std::vector<SDValue> VLDDupResults;
10187   for (unsigned n = 0; n < NumVecs; ++n)
10188     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10189   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10190   DCI.CombineTo(VLD, VLDDupResults);
10191
10192   return true;
10193 }
10194
10195 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10196 /// ARMISD::VDUPLANE.
10197 static SDValue PerformVDUPLANECombine(SDNode *N,
10198                                       TargetLowering::DAGCombinerInfo &DCI) {
10199   SDValue Op = N->getOperand(0);
10200
10201   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
10202   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
10203   if (CombineVLDDUP(N, DCI))
10204     return SDValue(N, 0);
10205
10206   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
10207   // redundant.  Ignore bit_converts for now; element sizes are checked below.
10208   while (Op.getOpcode() == ISD::BITCAST)
10209     Op = Op.getOperand(0);
10210   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
10211     return SDValue();
10212
10213   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
10214   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
10215   // The canonical VMOV for a zero vector uses a 32-bit element size.
10216   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10217   unsigned EltBits;
10218   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
10219     EltSize = 8;
10220   EVT VT = N->getValueType(0);
10221   if (EltSize > VT.getVectorElementType().getSizeInBits())
10222     return SDValue();
10223
10224   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
10225 }
10226
10227 static SDValue PerformLOADCombine(SDNode *N,
10228                                   TargetLowering::DAGCombinerInfo &DCI) {
10229   EVT VT = N->getValueType(0);
10230
10231   // If this is a legal vector load, try to combine it into a VLD1_UPD.
10232   if (ISD::isNormalLoad(N) && VT.isVector() &&
10233       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10234     return CombineBaseUpdate(N, DCI);
10235
10236   return SDValue();
10237 }
10238
10239 /// PerformSTORECombine - Target-specific dag combine xforms for
10240 /// ISD::STORE.
10241 static SDValue PerformSTORECombine(SDNode *N,
10242                                    TargetLowering::DAGCombinerInfo &DCI) {
10243   StoreSDNode *St = cast<StoreSDNode>(N);
10244   if (St->isVolatile())
10245     return SDValue();
10246
10247   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
10248   // pack all of the elements in one place.  Next, store to memory in fewer
10249   // chunks.
10250   SDValue StVal = St->getValue();
10251   EVT VT = StVal.getValueType();
10252   if (St->isTruncatingStore() && VT.isVector()) {
10253     SelectionDAG &DAG = DCI.DAG;
10254     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10255     EVT StVT = St->getMemoryVT();
10256     unsigned NumElems = VT.getVectorNumElements();
10257     assert(StVT != VT && "Cannot truncate to the same type");
10258     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
10259     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
10260
10261     // From, To sizes and ElemCount must be pow of two
10262     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
10263
10264     // We are going to use the original vector elt for storing.
10265     // Accumulated smaller vector elements must be a multiple of the store size.
10266     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
10267
10268     unsigned SizeRatio  = FromEltSz / ToEltSz;
10269     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
10270
10271     // Create a type on which we perform the shuffle.
10272     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
10273                                      NumElems*SizeRatio);
10274     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
10275
10276     SDLoc DL(St);
10277     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
10278     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
10279     for (unsigned i = 0; i < NumElems; ++i)
10280       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
10281                           ? (i + 1) * SizeRatio - 1
10282                           : i * SizeRatio;
10283
10284     // Can't shuffle using an illegal type.
10285     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10286
10287     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10288                                 DAG.getUNDEF(WideVec.getValueType()),
10289                                 ShuffleVec);
10290     // At this point all of the data is stored at the bottom of the
10291     // register. We now need to save it to mem.
10292
10293     // Find the largest store unit
10294     MVT StoreType = MVT::i8;
10295     for (MVT Tp : MVT::integer_valuetypes()) {
10296       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10297         StoreType = Tp;
10298     }
10299     // Didn't find a legal store type.
10300     if (!TLI.isTypeLegal(StoreType))
10301       return SDValue();
10302
10303     // Bitcast the original vector into a vector of store-size units
10304     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10305             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10306     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10307     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10308     SmallVector<SDValue, 8> Chains;
10309     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10310                                         TLI.getPointerTy(DAG.getDataLayout()));
10311     SDValue BasePtr = St->getBasePtr();
10312
10313     // Perform one or more big stores into memory.
10314     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10315     for (unsigned I = 0; I < E; I++) {
10316       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10317                                    StoreType, ShuffWide,
10318                                    DAG.getIntPtrConstant(I, DL));
10319       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10320                                 St->getPointerInfo(), St->getAlignment(),
10321                                 St->getMemOperand()->getFlags());
10322       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10323                             Increment);
10324       Chains.push_back(Ch);
10325     }
10326     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10327   }
10328
10329   if (!ISD::isNormalStore(St))
10330     return SDValue();
10331
10332   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10333   // ARM stores of arguments in the same cache line.
10334   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10335       StVal.getNode()->hasOneUse()) {
10336     SelectionDAG  &DAG = DCI.DAG;
10337     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10338     SDLoc DL(St);
10339     SDValue BasePtr = St->getBasePtr();
10340     SDValue NewST1 = DAG.getStore(
10341         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
10342         BasePtr, St->getPointerInfo(), St->getAlignment(),
10343         St->getMemOperand()->getFlags());
10344
10345     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10346                                     DAG.getConstant(4, DL, MVT::i32));
10347     return DAG.getStore(NewST1.getValue(0), DL,
10348                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10349                         OffsetPtr, St->getPointerInfo(),
10350                         std::min(4U, St->getAlignment() / 2),
10351                         St->getMemOperand()->getFlags());
10352   }
10353
10354   if (StVal.getValueType() == MVT::i64 &&
10355       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10356
10357     // Bitcast an i64 store extracted from a vector to f64.
10358     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10359     SelectionDAG &DAG = DCI.DAG;
10360     SDLoc dl(StVal);
10361     SDValue IntVec = StVal.getOperand(0);
10362     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10363                                    IntVec.getValueType().getVectorNumElements());
10364     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10365     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10366                                  Vec, StVal.getOperand(1));
10367     dl = SDLoc(N);
10368     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10369     // Make the DAGCombiner fold the bitcasts.
10370     DCI.AddToWorklist(Vec.getNode());
10371     DCI.AddToWorklist(ExtElt.getNode());
10372     DCI.AddToWorklist(V.getNode());
10373     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10374                         St->getPointerInfo(), St->getAlignment(),
10375                         St->getMemOperand()->getFlags(), St->getAAInfo());
10376   }
10377
10378   // If this is a legal vector store, try to combine it into a VST1_UPD.
10379   if (ISD::isNormalStore(N) && VT.isVector() &&
10380       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10381     return CombineBaseUpdate(N, DCI);
10382
10383   return SDValue();
10384 }
10385
10386 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10387 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10388 /// when the VMUL has a constant operand that is a power of 2.
10389 ///
10390 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10391 ///  vmul.f32        d16, d17, d16
10392 ///  vcvt.s32.f32    d16, d16
10393 /// becomes:
10394 ///  vcvt.s32.f32    d16, d16, #3
10395 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10396                                   const ARMSubtarget *Subtarget) {
10397   if (!Subtarget->hasNEON())
10398     return SDValue();
10399
10400   SDValue Op = N->getOperand(0);
10401   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10402       Op.getOpcode() != ISD::FMUL)
10403     return SDValue();
10404
10405   SDValue ConstVec = Op->getOperand(1);
10406   if (!isa<BuildVectorSDNode>(ConstVec))
10407     return SDValue();
10408
10409   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10410   uint32_t FloatBits = FloatTy.getSizeInBits();
10411   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10412   uint32_t IntBits = IntTy.getSizeInBits();
10413   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10414   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10415     // These instructions only exist converting from f32 to i32. We can handle
10416     // smaller integers by generating an extra truncate, but larger ones would
10417     // be lossy. We also can't handle more then 4 lanes, since these intructions
10418     // only support v2i32/v4i32 types.
10419     return SDValue();
10420   }
10421
10422   BitVector UndefElements;
10423   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10424   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10425   if (C == -1 || C == 0 || C > 32)
10426     return SDValue();
10427
10428   SDLoc dl(N);
10429   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10430   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10431     Intrinsic::arm_neon_vcvtfp2fxu;
10432   SDValue FixConv = DAG.getNode(
10433       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10434       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10435       DAG.getConstant(C, dl, MVT::i32));
10436
10437   if (IntBits < FloatBits)
10438     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10439
10440   return FixConv;
10441 }
10442
10443 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10444 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10445 /// when the VDIV has a constant operand that is a power of 2.
10446 ///
10447 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10448 ///  vcvt.f32.s32    d16, d16
10449 ///  vdiv.f32        d16, d17, d16
10450 /// becomes:
10451 ///  vcvt.f32.s32    d16, d16, #3
10452 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10453                                   const ARMSubtarget *Subtarget) {
10454   if (!Subtarget->hasNEON())
10455     return SDValue();
10456
10457   SDValue Op = N->getOperand(0);
10458   unsigned OpOpcode = Op.getNode()->getOpcode();
10459   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
10460       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10461     return SDValue();
10462
10463   SDValue ConstVec = N->getOperand(1);
10464   if (!isa<BuildVectorSDNode>(ConstVec))
10465     return SDValue();
10466
10467   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10468   uint32_t FloatBits = FloatTy.getSizeInBits();
10469   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10470   uint32_t IntBits = IntTy.getSizeInBits();
10471   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10472   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10473     // These instructions only exist converting from i32 to f32. We can handle
10474     // smaller integers by generating an extra extend, but larger ones would
10475     // be lossy. We also can't handle more then 4 lanes, since these intructions
10476     // only support v2i32/v4i32 types.
10477     return SDValue();
10478   }
10479
10480   BitVector UndefElements;
10481   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10482   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10483   if (C == -1 || C == 0 || C > 32)
10484     return SDValue();
10485
10486   SDLoc dl(N);
10487   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10488   SDValue ConvInput = Op.getOperand(0);
10489   if (IntBits < FloatBits)
10490     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10491                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10492                             ConvInput);
10493
10494   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10495     Intrinsic::arm_neon_vcvtfxu2fp;
10496   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10497                      Op.getValueType(),
10498                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10499                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10500 }
10501
10502 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10503 /// operand of a vector shift operation, where all the elements of the
10504 /// build_vector must have the same constant integer value.
10505 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10506   // Ignore bit_converts.
10507   while (Op.getOpcode() == ISD::BITCAST)
10508     Op = Op.getOperand(0);
10509   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10510   APInt SplatBits, SplatUndef;
10511   unsigned SplatBitSize;
10512   bool HasAnyUndefs;
10513   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10514                                       HasAnyUndefs, ElementBits) ||
10515       SplatBitSize > ElementBits)
10516     return false;
10517   Cnt = SplatBits.getSExtValue();
10518   return true;
10519 }
10520
10521 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10522 /// operand of a vector shift left operation.  That value must be in the range:
10523 ///   0 <= Value < ElementBits for a left shift; or
10524 ///   0 <= Value <= ElementBits for a long left shift.
10525 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10526   assert(VT.isVector() && "vector shift count is not a vector type");
10527   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10528   if (! getVShiftImm(Op, ElementBits, Cnt))
10529     return false;
10530   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10531 }
10532
10533 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10534 /// operand of a vector shift right operation.  For a shift opcode, the value
10535 /// is positive, but for an intrinsic the value count must be negative. The
10536 /// absolute value must be in the range:
10537 ///   1 <= |Value| <= ElementBits for a right shift; or
10538 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10539 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10540                          int64_t &Cnt) {
10541   assert(VT.isVector() && "vector shift count is not a vector type");
10542   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
10543   if (! getVShiftImm(Op, ElementBits, Cnt))
10544     return false;
10545   if (!isIntrinsic)
10546     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10547   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10548     Cnt = -Cnt;
10549     return true;
10550   }
10551   return false;
10552 }
10553
10554 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10555 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10556   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10557   switch (IntNo) {
10558   default:
10559     // Don't do anything for most intrinsics.
10560     break;
10561
10562   // Vector shifts: check for immediate versions and lower them.
10563   // Note: This is done during DAG combining instead of DAG legalizing because
10564   // the build_vectors for 64-bit vector element shift counts are generally
10565   // not legal, and it is hard to see their values after they get legalized to
10566   // loads from a constant pool.
10567   case Intrinsic::arm_neon_vshifts:
10568   case Intrinsic::arm_neon_vshiftu:
10569   case Intrinsic::arm_neon_vrshifts:
10570   case Intrinsic::arm_neon_vrshiftu:
10571   case Intrinsic::arm_neon_vrshiftn:
10572   case Intrinsic::arm_neon_vqshifts:
10573   case Intrinsic::arm_neon_vqshiftu:
10574   case Intrinsic::arm_neon_vqshiftsu:
10575   case Intrinsic::arm_neon_vqshiftns:
10576   case Intrinsic::arm_neon_vqshiftnu:
10577   case Intrinsic::arm_neon_vqshiftnsu:
10578   case Intrinsic::arm_neon_vqrshiftns:
10579   case Intrinsic::arm_neon_vqrshiftnu:
10580   case Intrinsic::arm_neon_vqrshiftnsu: {
10581     EVT VT = N->getOperand(1).getValueType();
10582     int64_t Cnt;
10583     unsigned VShiftOpc = 0;
10584
10585     switch (IntNo) {
10586     case Intrinsic::arm_neon_vshifts:
10587     case Intrinsic::arm_neon_vshiftu:
10588       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10589         VShiftOpc = ARMISD::VSHL;
10590         break;
10591       }
10592       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10593         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10594                      ARMISD::VSHRs : ARMISD::VSHRu);
10595         break;
10596       }
10597       return SDValue();
10598
10599     case Intrinsic::arm_neon_vrshifts:
10600     case Intrinsic::arm_neon_vrshiftu:
10601       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10602         break;
10603       return SDValue();
10604
10605     case Intrinsic::arm_neon_vqshifts:
10606     case Intrinsic::arm_neon_vqshiftu:
10607       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10608         break;
10609       return SDValue();
10610
10611     case Intrinsic::arm_neon_vqshiftsu:
10612       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10613         break;
10614       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10615
10616     case Intrinsic::arm_neon_vrshiftn:
10617     case Intrinsic::arm_neon_vqshiftns:
10618     case Intrinsic::arm_neon_vqshiftnu:
10619     case Intrinsic::arm_neon_vqshiftnsu:
10620     case Intrinsic::arm_neon_vqrshiftns:
10621     case Intrinsic::arm_neon_vqrshiftnu:
10622     case Intrinsic::arm_neon_vqrshiftnsu:
10623       // Narrowing shifts require an immediate right shift.
10624       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10625         break;
10626       llvm_unreachable("invalid shift count for narrowing vector shift "
10627                        "intrinsic");
10628
10629     default:
10630       llvm_unreachable("unhandled vector shift");
10631     }
10632
10633     switch (IntNo) {
10634     case Intrinsic::arm_neon_vshifts:
10635     case Intrinsic::arm_neon_vshiftu:
10636       // Opcode already set above.
10637       break;
10638     case Intrinsic::arm_neon_vrshifts:
10639       VShiftOpc = ARMISD::VRSHRs; break;
10640     case Intrinsic::arm_neon_vrshiftu:
10641       VShiftOpc = ARMISD::VRSHRu; break;
10642     case Intrinsic::arm_neon_vrshiftn:
10643       VShiftOpc = ARMISD::VRSHRN; break;
10644     case Intrinsic::arm_neon_vqshifts:
10645       VShiftOpc = ARMISD::VQSHLs; break;
10646     case Intrinsic::arm_neon_vqshiftu:
10647       VShiftOpc = ARMISD::VQSHLu; break;
10648     case Intrinsic::arm_neon_vqshiftsu:
10649       VShiftOpc = ARMISD::VQSHLsu; break;
10650     case Intrinsic::arm_neon_vqshiftns:
10651       VShiftOpc = ARMISD::VQSHRNs; break;
10652     case Intrinsic::arm_neon_vqshiftnu:
10653       VShiftOpc = ARMISD::VQSHRNu; break;
10654     case Intrinsic::arm_neon_vqshiftnsu:
10655       VShiftOpc = ARMISD::VQSHRNsu; break;
10656     case Intrinsic::arm_neon_vqrshiftns:
10657       VShiftOpc = ARMISD::VQRSHRNs; break;
10658     case Intrinsic::arm_neon_vqrshiftnu:
10659       VShiftOpc = ARMISD::VQRSHRNu; break;
10660     case Intrinsic::arm_neon_vqrshiftnsu:
10661       VShiftOpc = ARMISD::VQRSHRNsu; break;
10662     }
10663
10664     SDLoc dl(N);
10665     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10666                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10667   }
10668
10669   case Intrinsic::arm_neon_vshiftins: {
10670     EVT VT = N->getOperand(1).getValueType();
10671     int64_t Cnt;
10672     unsigned VShiftOpc = 0;
10673
10674     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10675       VShiftOpc = ARMISD::VSLI;
10676     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10677       VShiftOpc = ARMISD::VSRI;
10678     else {
10679       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10680     }
10681
10682     SDLoc dl(N);
10683     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10684                        N->getOperand(1), N->getOperand(2),
10685                        DAG.getConstant(Cnt, dl, MVT::i32));
10686   }
10687
10688   case Intrinsic::arm_neon_vqrshifts:
10689   case Intrinsic::arm_neon_vqrshiftu:
10690     // No immediate versions of these to check for.
10691     break;
10692   }
10693
10694   return SDValue();
10695 }
10696
10697 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10698 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10699 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10700 /// vector element shift counts are generally not legal, and it is hard to see
10701 /// their values after they get legalized to loads from a constant pool.
10702 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10703                                    const ARMSubtarget *ST) {
10704   EVT VT = N->getValueType(0);
10705   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10706     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10707     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10708     SDValue N1 = N->getOperand(1);
10709     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10710       SDValue N0 = N->getOperand(0);
10711       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10712           DAG.MaskedValueIsZero(N0.getOperand(0),
10713                                 APInt::getHighBitsSet(32, 16)))
10714         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10715     }
10716   }
10717
10718   // Nothing to be done for scalar shifts.
10719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10720   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10721     return SDValue();
10722
10723   assert(ST->hasNEON() && "unexpected vector shift");
10724   int64_t Cnt;
10725
10726   switch (N->getOpcode()) {
10727   default: llvm_unreachable("unexpected shift opcode");
10728
10729   case ISD::SHL:
10730     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10731       SDLoc dl(N);
10732       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10733                          DAG.getConstant(Cnt, dl, MVT::i32));
10734     }
10735     break;
10736
10737   case ISD::SRA:
10738   case ISD::SRL:
10739     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10740       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10741                             ARMISD::VSHRs : ARMISD::VSHRu);
10742       SDLoc dl(N);
10743       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10744                          DAG.getConstant(Cnt, dl, MVT::i32));
10745     }
10746   }
10747   return SDValue();
10748 }
10749
10750 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10751 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10752 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10753                                     const ARMSubtarget *ST) {
10754   SDValue N0 = N->getOperand(0);
10755
10756   // Check for sign- and zero-extensions of vector extract operations of 8-
10757   // and 16-bit vector elements.  NEON supports these directly.  They are
10758   // handled during DAG combining because type legalization will promote them
10759   // to 32-bit types and it is messy to recognize the operations after that.
10760   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10761     SDValue Vec = N0.getOperand(0);
10762     SDValue Lane = N0.getOperand(1);
10763     EVT VT = N->getValueType(0);
10764     EVT EltVT = N0.getValueType();
10765     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10766
10767     if (VT == MVT::i32 &&
10768         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10769         TLI.isTypeLegal(Vec.getValueType()) &&
10770         isa<ConstantSDNode>(Lane)) {
10771
10772       unsigned Opc = 0;
10773       switch (N->getOpcode()) {
10774       default: llvm_unreachable("unexpected opcode");
10775       case ISD::SIGN_EXTEND:
10776         Opc = ARMISD::VGETLANEs;
10777         break;
10778       case ISD::ZERO_EXTEND:
10779       case ISD::ANY_EXTEND:
10780         Opc = ARMISD::VGETLANEu;
10781         break;
10782       }
10783       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10784     }
10785   }
10786
10787   return SDValue();
10788 }
10789
10790 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10791                              APInt &KnownOne) {
10792   if (Op.getOpcode() == ARMISD::BFI) {
10793     // Conservatively, we can recurse down the first operand
10794     // and just mask out all affected bits.
10795     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10796
10797     // The operand to BFI is already a mask suitable for removing the bits it
10798     // sets.
10799     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10800     const APInt &Mask = CI->getAPIntValue();
10801     KnownZero &= Mask;
10802     KnownOne &= Mask;
10803     return;
10804   }
10805   if (Op.getOpcode() == ARMISD::CMOV) {
10806     APInt KZ2(KnownZero.getBitWidth(), 0);
10807     APInt KO2(KnownOne.getBitWidth(), 0);
10808     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10809     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10810
10811     KnownZero &= KZ2;
10812     KnownOne &= KO2;
10813     return;
10814   }
10815   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10816 }
10817
10818 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10819   // If we have a CMOV, OR and AND combination such as:
10820   //   if (x & CN)
10821   //     y |= CM;
10822   //
10823   // And:
10824   //   * CN is a single bit;
10825   //   * All bits covered by CM are known zero in y
10826   //
10827   // Then we can convert this into a sequence of BFI instructions. This will
10828   // always be a win if CM is a single bit, will always be no worse than the
10829   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10830   // three bits (due to the extra IT instruction).
10831
10832   SDValue Op0 = CMOV->getOperand(0);
10833   SDValue Op1 = CMOV->getOperand(1);
10834   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
10835   auto CC = CCNode->getAPIntValue().getLimitedValue();
10836   SDValue CmpZ = CMOV->getOperand(4);
10837
10838   // The compare must be against zero.
10839   if (!isNullConstant(CmpZ->getOperand(1)))
10840     return SDValue();
10841
10842   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10843   SDValue And = CmpZ->getOperand(0);
10844   if (And->getOpcode() != ISD::AND)
10845     return SDValue();
10846   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10847   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10848     return SDValue();
10849   SDValue X = And->getOperand(0);
10850
10851   if (CC == ARMCC::EQ) {
10852     // We're performing an "equal to zero" compare. Swap the operands so we
10853     // canonicalize on a "not equal to zero" compare.
10854     std::swap(Op0, Op1);
10855   } else {
10856     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
10857   }
10858
10859   if (Op1->getOpcode() != ISD::OR)
10860     return SDValue();
10861
10862   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
10863   if (!OrC)
10864     return SDValue();
10865   SDValue Y = Op1->getOperand(0);
10866
10867   if (Op0 != Y)
10868     return SDValue();
10869
10870   // Now, is it profitable to continue?
10871   APInt OrCI = OrC->getAPIntValue();
10872   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10873   if (OrCI.countPopulation() > Heuristic)
10874     return SDValue();
10875
10876   // Lastly, can we determine that the bits defined by OrCI
10877   // are zero in Y?
10878   APInt KnownZero, KnownOne;
10879   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10880   if ((OrCI & KnownZero) != OrCI)
10881     return SDValue();
10882
10883   // OK, we can do the combine.
10884   SDValue V = Y;
10885   SDLoc dl(X);
10886   EVT VT = X.getValueType();
10887   unsigned BitInX = AndC->getAPIntValue().logBase2();
10888
10889   if (BitInX != 0) {
10890     // We must shift X first.
10891     X = DAG.getNode(ISD::SRL, dl, VT, X,
10892                     DAG.getConstant(BitInX, dl, VT));
10893   }
10894
10895   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10896        BitInY < NumActiveBits; ++BitInY) {
10897     if (OrCI[BitInY] == 0)
10898       continue;
10899     APInt Mask(VT.getSizeInBits(), 0);
10900     Mask.setBit(BitInY);
10901     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10902                     // Confusingly, the operand is an *inverted* mask.
10903                     DAG.getConstant(~Mask, dl, VT));
10904   }
10905
10906   return V;
10907 }
10908
10909 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
10910 SDValue
10911 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
10912   SDValue Cmp = N->getOperand(4);
10913   if (Cmp.getOpcode() != ARMISD::CMPZ)
10914     // Only looking at NE cases.
10915     return SDValue();
10916
10917   EVT VT = N->getValueType(0);
10918   SDLoc dl(N);
10919   SDValue LHS = Cmp.getOperand(0);
10920   SDValue RHS = Cmp.getOperand(1);
10921   SDValue Chain = N->getOperand(0);
10922   SDValue BB = N->getOperand(1);
10923   SDValue ARMcc = N->getOperand(2);
10924   ARMCC::CondCodes CC =
10925     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10926
10927   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
10928   // -> (brcond Chain BB CC CPSR Cmp)
10929   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
10930       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
10931       LHS->getOperand(0)->hasOneUse()) {
10932     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
10933     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
10934     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
10935     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
10936     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
10937         (LHS01C && LHS01C->getZExtValue() == 1) &&
10938         (LHS1C && LHS1C->getZExtValue() == 1) &&
10939         (RHSC && RHSC->getZExtValue() == 0)) {
10940       return DAG.getNode(
10941           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
10942           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
10943     }
10944   }
10945
10946   return SDValue();
10947 }
10948
10949 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10950 SDValue
10951 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10952   SDValue Cmp = N->getOperand(4);
10953   if (Cmp.getOpcode() != ARMISD::CMPZ)
10954     // Only looking at EQ and NE cases.
10955     return SDValue();
10956
10957   EVT VT = N->getValueType(0);
10958   SDLoc dl(N);
10959   SDValue LHS = Cmp.getOperand(0);
10960   SDValue RHS = Cmp.getOperand(1);
10961   SDValue FalseVal = N->getOperand(0);
10962   SDValue TrueVal = N->getOperand(1);
10963   SDValue ARMcc = N->getOperand(2);
10964   ARMCC::CondCodes CC =
10965     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10966
10967   // BFI is only available on V6T2+.
10968   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10969     SDValue R = PerformCMOVToBFICombine(N, DAG);
10970     if (R)
10971       return R;
10972   }
10973
10974   // Simplify
10975   //   mov     r1, r0
10976   //   cmp     r1, x
10977   //   mov     r0, y
10978   //   moveq   r0, x
10979   // to
10980   //   cmp     r0, x
10981   //   movne   r0, y
10982   //
10983   //   mov     r1, r0
10984   //   cmp     r1, x
10985   //   mov     r0, x
10986   //   movne   r0, y
10987   // to
10988   //   cmp     r0, x
10989   //   movne   r0, y
10990   /// FIXME: Turn this into a target neutral optimization?
10991   SDValue Res;
10992   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10993     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10994                       N->getOperand(3), Cmp);
10995   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10996     SDValue ARMcc;
10997     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10998     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10999                       N->getOperand(3), NewCmp);
11000   }
11001
11002   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11003   // -> (cmov F T CC CPSR Cmp)
11004   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11005     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11006     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11007     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11008     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11009         (LHS1C && LHS1C->getZExtValue() == 1) &&
11010         (RHSC && RHSC->getZExtValue() == 0)) {
11011       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11012                          LHS->getOperand(2), LHS->getOperand(3),
11013                          LHS->getOperand(4));
11014     }
11015   }
11016
11017   if (Res.getNode()) {
11018     APInt KnownZero, KnownOne;
11019     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11020     // Capture demanded bits information that would be otherwise lost.
11021     if (KnownZero == 0xfffffffe)
11022       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11023                         DAG.getValueType(MVT::i1));
11024     else if (KnownZero == 0xffffff00)
11025       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11026                         DAG.getValueType(MVT::i8));
11027     else if (KnownZero == 0xffff0000)
11028       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11029                         DAG.getValueType(MVT::i16));
11030   }
11031
11032   return Res;
11033 }
11034
11035 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11036                                              DAGCombinerInfo &DCI) const {
11037   switch (N->getOpcode()) {
11038   default: break;
11039   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
11040   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11041   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11042   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11043   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11044   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11045   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11046   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11047   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11048   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11049   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11050   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11051   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11052   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11053   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11054   case ISD::FP_TO_SINT:
11055   case ISD::FP_TO_UINT:
11056     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11057   case ISD::FDIV:
11058     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11059   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11060   case ISD::SHL:
11061   case ISD::SRA:
11062   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11063   case ISD::SIGN_EXTEND:
11064   case ISD::ZERO_EXTEND:
11065   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11066   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11067   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11068   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11069   case ARMISD::VLD2DUP:
11070   case ARMISD::VLD3DUP:
11071   case ARMISD::VLD4DUP:
11072     return PerformVLDCombine(N, DCI);
11073   case ARMISD::BUILD_VECTOR:
11074     return PerformARMBUILD_VECTORCombine(N, DCI);
11075   case ISD::INTRINSIC_VOID:
11076   case ISD::INTRINSIC_W_CHAIN:
11077     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11078     case Intrinsic::arm_neon_vld1:
11079     case Intrinsic::arm_neon_vld2:
11080     case Intrinsic::arm_neon_vld3:
11081     case Intrinsic::arm_neon_vld4:
11082     case Intrinsic::arm_neon_vld2lane:
11083     case Intrinsic::arm_neon_vld3lane:
11084     case Intrinsic::arm_neon_vld4lane:
11085     case Intrinsic::arm_neon_vst1:
11086     case Intrinsic::arm_neon_vst2:
11087     case Intrinsic::arm_neon_vst3:
11088     case Intrinsic::arm_neon_vst4:
11089     case Intrinsic::arm_neon_vst2lane:
11090     case Intrinsic::arm_neon_vst3lane:
11091     case Intrinsic::arm_neon_vst4lane:
11092       return PerformVLDCombine(N, DCI);
11093     default: break;
11094     }
11095     break;
11096   }
11097   return SDValue();
11098 }
11099
11100 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11101                                                           EVT VT) const {
11102   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11103 }
11104
11105 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11106                                                        unsigned,
11107                                                        unsigned,
11108                                                        bool *Fast) const {
11109   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11110   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11111
11112   switch (VT.getSimpleVT().SimpleTy) {
11113   default:
11114     return false;
11115   case MVT::i8:
11116   case MVT::i16:
11117   case MVT::i32: {
11118     // Unaligned access can use (for example) LRDB, LRDH, LDR
11119     if (AllowsUnaligned) {
11120       if (Fast)
11121         *Fast = Subtarget->hasV7Ops();
11122       return true;
11123     }
11124     return false;
11125   }
11126   case MVT::f64:
11127   case MVT::v2f64: {
11128     // For any little-endian targets with neon, we can support unaligned ld/st
11129     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
11130     // A big-endian target may also explicitly support unaligned accesses
11131     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
11132       if (Fast)
11133         *Fast = true;
11134       return true;
11135     }
11136     return false;
11137   }
11138   }
11139 }
11140
11141 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
11142                        unsigned AlignCheck) {
11143   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
11144           (DstAlign == 0 || DstAlign % AlignCheck == 0));
11145 }
11146
11147 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
11148                                            unsigned DstAlign, unsigned SrcAlign,
11149                                            bool IsMemset, bool ZeroMemset,
11150                                            bool MemcpyStrSrc,
11151                                            MachineFunction &MF) const {
11152   const Function *F = MF.getFunction();
11153
11154   // See if we can use NEON instructions for this...
11155   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
11156       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11157     bool Fast;
11158     if (Size >= 16 &&
11159         (memOpAlign(SrcAlign, DstAlign, 16) ||
11160          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
11161       return MVT::v2f64;
11162     } else if (Size >= 8 &&
11163                (memOpAlign(SrcAlign, DstAlign, 8) ||
11164                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
11165                  Fast))) {
11166       return MVT::f64;
11167     }
11168   }
11169
11170   // Lowering to i32/i16 if the size permits.
11171   if (Size >= 4)
11172     return MVT::i32;
11173   else if (Size >= 2)
11174     return MVT::i16;
11175
11176   // Let the target-independent logic figure it out.
11177   return MVT::Other;
11178 }
11179
11180 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11181   if (Val.getOpcode() != ISD::LOAD)
11182     return false;
11183
11184   EVT VT1 = Val.getValueType();
11185   if (!VT1.isSimple() || !VT1.isInteger() ||
11186       !VT2.isSimple() || !VT2.isInteger())
11187     return false;
11188
11189   switch (VT1.getSimpleVT().SimpleTy) {
11190   default: break;
11191   case MVT::i1:
11192   case MVT::i8:
11193   case MVT::i16:
11194     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
11195     return true;
11196   }
11197
11198   return false;
11199 }
11200
11201 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
11202   EVT VT = ExtVal.getValueType();
11203
11204   if (!isTypeLegal(VT))
11205     return false;
11206
11207   // Don't create a loadext if we can fold the extension into a wide/long
11208   // instruction.
11209   // If there's more than one user instruction, the loadext is desirable no
11210   // matter what.  There can be two uses by the same instruction.
11211   if (ExtVal->use_empty() ||
11212       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
11213     return true;
11214
11215   SDNode *U = *ExtVal->use_begin();
11216   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
11217        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
11218     return false;
11219
11220   return true;
11221 }
11222
11223 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
11224   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11225     return false;
11226
11227   if (!isTypeLegal(EVT::getEVT(Ty1)))
11228     return false;
11229
11230   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
11231
11232   // Assuming the caller doesn't have a zeroext or signext return parameter,
11233   // truncation all the way down to i1 is valid.
11234   return true;
11235 }
11236
11237
11238 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
11239   if (V < 0)
11240     return false;
11241
11242   unsigned Scale = 1;
11243   switch (VT.getSimpleVT().SimpleTy) {
11244   default: return false;
11245   case MVT::i1:
11246   case MVT::i8:
11247     // Scale == 1;
11248     break;
11249   case MVT::i16:
11250     // Scale == 2;
11251     Scale = 2;
11252     break;
11253   case MVT::i32:
11254     // Scale == 4;
11255     Scale = 4;
11256     break;
11257   }
11258
11259   if ((V & (Scale - 1)) != 0)
11260     return false;
11261   V /= Scale;
11262   return V == (V & ((1LL << 5) - 1));
11263 }
11264
11265 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
11266                                       const ARMSubtarget *Subtarget) {
11267   bool isNeg = false;
11268   if (V < 0) {
11269     isNeg = true;
11270     V = - V;
11271   }
11272
11273   switch (VT.getSimpleVT().SimpleTy) {
11274   default: return false;
11275   case MVT::i1:
11276   case MVT::i8:
11277   case MVT::i16:
11278   case MVT::i32:
11279     // + imm12 or - imm8
11280     if (isNeg)
11281       return V == (V & ((1LL << 8) - 1));
11282     return V == (V & ((1LL << 12) - 1));
11283   case MVT::f32:
11284   case MVT::f64:
11285     // Same as ARM mode. FIXME: NEON?
11286     if (!Subtarget->hasVFP2())
11287       return false;
11288     if ((V & 3) != 0)
11289       return false;
11290     V >>= 2;
11291     return V == (V & ((1LL << 8) - 1));
11292   }
11293 }
11294
11295 /// isLegalAddressImmediate - Return true if the integer value can be used
11296 /// as the offset of the target addressing mode for load / store of the
11297 /// given type.
11298 static bool isLegalAddressImmediate(int64_t V, EVT VT,
11299                                     const ARMSubtarget *Subtarget) {
11300   if (V == 0)
11301     return true;
11302
11303   if (!VT.isSimple())
11304     return false;
11305
11306   if (Subtarget->isThumb1Only())
11307     return isLegalT1AddressImmediate(V, VT);
11308   else if (Subtarget->isThumb2())
11309     return isLegalT2AddressImmediate(V, VT, Subtarget);
11310
11311   // ARM mode.
11312   if (V < 0)
11313     V = - V;
11314   switch (VT.getSimpleVT().SimpleTy) {
11315   default: return false;
11316   case MVT::i1:
11317   case MVT::i8:
11318   case MVT::i32:
11319     // +- imm12
11320     return V == (V & ((1LL << 12) - 1));
11321   case MVT::i16:
11322     // +- imm8
11323     return V == (V & ((1LL << 8) - 1));
11324   case MVT::f32:
11325   case MVT::f64:
11326     if (!Subtarget->hasVFP2()) // FIXME: NEON?
11327       return false;
11328     if ((V & 3) != 0)
11329       return false;
11330     V >>= 2;
11331     return V == (V & ((1LL << 8) - 1));
11332   }
11333 }
11334
11335 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
11336                                                       EVT VT) const {
11337   int Scale = AM.Scale;
11338   if (Scale < 0)
11339     return false;
11340
11341   switch (VT.getSimpleVT().SimpleTy) {
11342   default: return false;
11343   case MVT::i1:
11344   case MVT::i8:
11345   case MVT::i16:
11346   case MVT::i32:
11347     if (Scale == 1)
11348       return true;
11349     // r + r << imm
11350     Scale = Scale & ~1;
11351     return Scale == 2 || Scale == 4 || Scale == 8;
11352   case MVT::i64:
11353     // r + r
11354     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11355       return true;
11356     return false;
11357   case MVT::isVoid:
11358     // Note, we allow "void" uses (basically, uses that aren't loads or
11359     // stores), because arm allows folding a scale into many arithmetic
11360     // operations.  This should be made more precise and revisited later.
11361
11362     // Allow r << imm, but the imm has to be a multiple of two.
11363     if (Scale & 1) return false;
11364     return isPowerOf2_32(Scale);
11365   }
11366 }
11367
11368 /// isLegalAddressingMode - Return true if the addressing mode represented
11369 /// by AM is legal for this target, for a load/store of the specified type.
11370 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11371                                               const AddrMode &AM, Type *Ty,
11372                                               unsigned AS) const {
11373   EVT VT = getValueType(DL, Ty, true);
11374   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11375     return false;
11376
11377   // Can never fold addr of global into load/store.
11378   if (AM.BaseGV)
11379     return false;
11380
11381   switch (AM.Scale) {
11382   case 0:  // no scale reg, must be "r+i" or "r", or "i".
11383     break;
11384   case 1:
11385     if (Subtarget->isThumb1Only())
11386       return false;
11387     // FALL THROUGH.
11388   default:
11389     // ARM doesn't support any R+R*scale+imm addr modes.
11390     if (AM.BaseOffs)
11391       return false;
11392
11393     if (!VT.isSimple())
11394       return false;
11395
11396     if (Subtarget->isThumb2())
11397       return isLegalT2ScaledAddressingMode(AM, VT);
11398
11399     int Scale = AM.Scale;
11400     switch (VT.getSimpleVT().SimpleTy) {
11401     default: return false;
11402     case MVT::i1:
11403     case MVT::i8:
11404     case MVT::i32:
11405       if (Scale < 0) Scale = -Scale;
11406       if (Scale == 1)
11407         return true;
11408       // r + r << imm
11409       return isPowerOf2_32(Scale & ~1);
11410     case MVT::i16:
11411     case MVT::i64:
11412       // r + r
11413       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11414         return true;
11415       return false;
11416
11417     case MVT::isVoid:
11418       // Note, we allow "void" uses (basically, uses that aren't loads or
11419       // stores), because arm allows folding a scale into many arithmetic
11420       // operations.  This should be made more precise and revisited later.
11421
11422       // Allow r << imm, but the imm has to be a multiple of two.
11423       if (Scale & 1) return false;
11424       return isPowerOf2_32(Scale);
11425     }
11426   }
11427   return true;
11428 }
11429
11430 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11431 /// icmp immediate, that is the target has icmp instructions which can compare
11432 /// a register against the immediate without having to materialize the
11433 /// immediate into a register.
11434 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11435   // Thumb2 and ARM modes can use cmn for negative immediates.
11436   if (!Subtarget->isThumb())
11437     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11438   if (Subtarget->isThumb2())
11439     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11440   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11441   return Imm >= 0 && Imm <= 255;
11442 }
11443
11444 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11445 /// *or sub* immediate, that is the target has add or sub instructions which can
11446 /// add a register with the immediate without having to materialize the
11447 /// immediate into a register.
11448 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11449   // Same encoding for add/sub, just flip the sign.
11450   int64_t AbsImm = std::abs(Imm);
11451   if (!Subtarget->isThumb())
11452     return ARM_AM::getSOImmVal(AbsImm) != -1;
11453   if (Subtarget->isThumb2())
11454     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11455   // Thumb1 only has 8-bit unsigned immediate.
11456   return AbsImm >= 0 && AbsImm <= 255;
11457 }
11458
11459 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11460                                       bool isSEXTLoad, SDValue &Base,
11461                                       SDValue &Offset, bool &isInc,
11462                                       SelectionDAG &DAG) {
11463   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11464     return false;
11465
11466   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11467     // AddressingMode 3
11468     Base = Ptr->getOperand(0);
11469     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11470       int RHSC = (int)RHS->getZExtValue();
11471       if (RHSC < 0 && RHSC > -256) {
11472         assert(Ptr->getOpcode() == ISD::ADD);
11473         isInc = false;
11474         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11475         return true;
11476       }
11477     }
11478     isInc = (Ptr->getOpcode() == ISD::ADD);
11479     Offset = Ptr->getOperand(1);
11480     return true;
11481   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11482     // AddressingMode 2
11483     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11484       int RHSC = (int)RHS->getZExtValue();
11485       if (RHSC < 0 && RHSC > -0x1000) {
11486         assert(Ptr->getOpcode() == ISD::ADD);
11487         isInc = false;
11488         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11489         Base = Ptr->getOperand(0);
11490         return true;
11491       }
11492     }
11493
11494     if (Ptr->getOpcode() == ISD::ADD) {
11495       isInc = true;
11496       ARM_AM::ShiftOpc ShOpcVal=
11497         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11498       if (ShOpcVal != ARM_AM::no_shift) {
11499         Base = Ptr->getOperand(1);
11500         Offset = Ptr->getOperand(0);
11501       } else {
11502         Base = Ptr->getOperand(0);
11503         Offset = Ptr->getOperand(1);
11504       }
11505       return true;
11506     }
11507
11508     isInc = (Ptr->getOpcode() == ISD::ADD);
11509     Base = Ptr->getOperand(0);
11510     Offset = Ptr->getOperand(1);
11511     return true;
11512   }
11513
11514   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11515   return false;
11516 }
11517
11518 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11519                                      bool isSEXTLoad, SDValue &Base,
11520                                      SDValue &Offset, bool &isInc,
11521                                      SelectionDAG &DAG) {
11522   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11523     return false;
11524
11525   Base = Ptr->getOperand(0);
11526   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11527     int RHSC = (int)RHS->getZExtValue();
11528     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11529       assert(Ptr->getOpcode() == ISD::ADD);
11530       isInc = false;
11531       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11532       return true;
11533     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11534       isInc = Ptr->getOpcode() == ISD::ADD;
11535       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11536       return true;
11537     }
11538   }
11539
11540   return false;
11541 }
11542
11543 /// getPreIndexedAddressParts - returns true by value, base pointer and
11544 /// offset pointer and addressing mode by reference if the node's address
11545 /// can be legally represented as pre-indexed load / store address.
11546 bool
11547 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11548                                              SDValue &Offset,
11549                                              ISD::MemIndexedMode &AM,
11550                                              SelectionDAG &DAG) const {
11551   if (Subtarget->isThumb1Only())
11552     return false;
11553
11554   EVT VT;
11555   SDValue Ptr;
11556   bool isSEXTLoad = false;
11557   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11558     Ptr = LD->getBasePtr();
11559     VT  = LD->getMemoryVT();
11560     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11561   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11562     Ptr = ST->getBasePtr();
11563     VT  = ST->getMemoryVT();
11564   } else
11565     return false;
11566
11567   bool isInc;
11568   bool isLegal = false;
11569   if (Subtarget->isThumb2())
11570     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11571                                        Offset, isInc, DAG);
11572   else
11573     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11574                                         Offset, isInc, DAG);
11575   if (!isLegal)
11576     return false;
11577
11578   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11579   return true;
11580 }
11581
11582 /// getPostIndexedAddressParts - returns true by value, base pointer and
11583 /// offset pointer and addressing mode by reference if this node can be
11584 /// combined with a load / store to form a post-indexed load / store.
11585 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11586                                                    SDValue &Base,
11587                                                    SDValue &Offset,
11588                                                    ISD::MemIndexedMode &AM,
11589                                                    SelectionDAG &DAG) const {
11590   EVT VT;
11591   SDValue Ptr;
11592   bool isSEXTLoad = false, isNonExt;
11593   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11594     VT  = LD->getMemoryVT();
11595     Ptr = LD->getBasePtr();
11596     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11597     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
11598   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11599     VT  = ST->getMemoryVT();
11600     Ptr = ST->getBasePtr();
11601     isNonExt = !ST->isTruncatingStore();
11602   } else
11603     return false;
11604
11605   if (Subtarget->isThumb1Only()) {
11606     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
11607     // must be non-extending/truncating, i32, with an offset of 4.
11608     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
11609     if (Op->getOpcode() != ISD::ADD || !isNonExt)
11610       return false;
11611     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11612     if (!RHS || RHS->getZExtValue() != 4)
11613       return false;
11614     
11615     Offset = Op->getOperand(1);
11616     Base = Op->getOperand(0);
11617     AM = ISD::POST_INC;
11618     return true;
11619   }
11620   
11621   bool isInc;
11622   bool isLegal = false;
11623   if (Subtarget->isThumb2())
11624     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11625                                        isInc, DAG);
11626   else
11627     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11628                                         isInc, DAG);
11629   if (!isLegal)
11630     return false;
11631
11632   if (Ptr != Base) {
11633     // Swap base ptr and offset to catch more post-index load / store when
11634     // it's legal. In Thumb2 mode, offset must be an immediate.
11635     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11636         !Subtarget->isThumb2())
11637       std::swap(Base, Offset);
11638
11639     // Post-indexed load / store update the base pointer.
11640     if (Ptr != Base)
11641       return false;
11642   }
11643
11644   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11645   return true;
11646 }
11647
11648 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11649                                                       APInt &KnownZero,
11650                                                       APInt &KnownOne,
11651                                                       const SelectionDAG &DAG,
11652                                                       unsigned Depth) const {
11653   unsigned BitWidth = KnownOne.getBitWidth();
11654   KnownZero = KnownOne = APInt(BitWidth, 0);
11655   switch (Op.getOpcode()) {
11656   default: break;
11657   case ARMISD::ADDC:
11658   case ARMISD::ADDE:
11659   case ARMISD::SUBC:
11660   case ARMISD::SUBE:
11661     // These nodes' second result is a boolean
11662     if (Op.getResNo() == 0)
11663       break;
11664     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11665     break;
11666   case ARMISD::CMOV: {
11667     // Bits are known zero/one if known on the LHS and RHS.
11668     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11669     if (KnownZero == 0 && KnownOne == 0) return;
11670
11671     APInt KnownZeroRHS, KnownOneRHS;
11672     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11673     KnownZero &= KnownZeroRHS;
11674     KnownOne  &= KnownOneRHS;
11675     return;
11676   }
11677   case ISD::INTRINSIC_W_CHAIN: {
11678     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11679     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11680     switch (IntID) {
11681     default: return;
11682     case Intrinsic::arm_ldaex:
11683     case Intrinsic::arm_ldrex: {
11684       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11685       unsigned MemBits = VT.getScalarType().getSizeInBits();
11686       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11687       return;
11688     }
11689     }
11690   }
11691   }
11692 }
11693
11694 //===----------------------------------------------------------------------===//
11695 //                           ARM Inline Assembly Support
11696 //===----------------------------------------------------------------------===//
11697
11698 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11699   // Looking for "rev" which is V6+.
11700   if (!Subtarget->hasV6Ops())
11701     return false;
11702
11703   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11704   std::string AsmStr = IA->getAsmString();
11705   SmallVector<StringRef, 4> AsmPieces;
11706   SplitString(AsmStr, AsmPieces, ";\n");
11707
11708   switch (AsmPieces.size()) {
11709   default: return false;
11710   case 1:
11711     AsmStr = AsmPieces[0];
11712     AsmPieces.clear();
11713     SplitString(AsmStr, AsmPieces, " \t,");
11714
11715     // rev $0, $1
11716     if (AsmPieces.size() == 3 &&
11717         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11718         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11719       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11720       if (Ty && Ty->getBitWidth() == 32)
11721         return IntrinsicLowering::LowerToByteSwap(CI);
11722     }
11723     break;
11724   }
11725
11726   return false;
11727 }
11728
11729 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
11730   // At this point, we have to lower this constraint to something else, so we
11731   // lower it to an "r" or "w". However, by doing this we will force the result
11732   // to be in register, while the X constraint is much more permissive.
11733   //
11734   // Although we are correct (we are free to emit anything, without
11735   // constraints), we might break use cases that would expect us to be more
11736   // efficient and emit something else.
11737   if (!Subtarget->hasVFP2())
11738     return "r";
11739   if (ConstraintVT.isFloatingPoint())
11740     return "w";
11741   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
11742      (ConstraintVT.getSizeInBits() == 64 ||
11743       ConstraintVT.getSizeInBits() == 128))
11744     return "w";
11745
11746   return "r";
11747 }
11748
11749 /// getConstraintType - Given a constraint letter, return the type of
11750 /// constraint it is for this target.
11751 ARMTargetLowering::ConstraintType
11752 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11753   if (Constraint.size() == 1) {
11754     switch (Constraint[0]) {
11755     default:  break;
11756     case 'l': return C_RegisterClass;
11757     case 'w': return C_RegisterClass;
11758     case 'h': return C_RegisterClass;
11759     case 'x': return C_RegisterClass;
11760     case 't': return C_RegisterClass;
11761     case 'j': return C_Other; // Constant for movw.
11762       // An address with a single base register. Due to the way we
11763       // currently handle addresses it is the same as an 'r' memory constraint.
11764     case 'Q': return C_Memory;
11765     }
11766   } else if (Constraint.size() == 2) {
11767     switch (Constraint[0]) {
11768     default: break;
11769     // All 'U+' constraints are addresses.
11770     case 'U': return C_Memory;
11771     }
11772   }
11773   return TargetLowering::getConstraintType(Constraint);
11774 }
11775
11776 /// Examine constraint type and operand type and determine a weight value.
11777 /// This object must already have been set up with the operand type
11778 /// and the current alternative constraint selected.
11779 TargetLowering::ConstraintWeight
11780 ARMTargetLowering::getSingleConstraintMatchWeight(
11781     AsmOperandInfo &info, const char *constraint) const {
11782   ConstraintWeight weight = CW_Invalid;
11783   Value *CallOperandVal = info.CallOperandVal;
11784     // If we don't have a value, we can't do a match,
11785     // but allow it at the lowest weight.
11786   if (!CallOperandVal)
11787     return CW_Default;
11788   Type *type = CallOperandVal->getType();
11789   // Look at the constraint type.
11790   switch (*constraint) {
11791   default:
11792     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11793     break;
11794   case 'l':
11795     if (type->isIntegerTy()) {
11796       if (Subtarget->isThumb())
11797         weight = CW_SpecificReg;
11798       else
11799         weight = CW_Register;
11800     }
11801     break;
11802   case 'w':
11803     if (type->isFloatingPointTy())
11804       weight = CW_Register;
11805     break;
11806   }
11807   return weight;
11808 }
11809
11810 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11811 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11812     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11813   if (Constraint.size() == 1) {
11814     // GCC ARM Constraint Letters
11815     switch (Constraint[0]) {
11816     case 'l': // Low regs or general regs.
11817       if (Subtarget->isThumb())
11818         return RCPair(0U, &ARM::tGPRRegClass);
11819       return RCPair(0U, &ARM::GPRRegClass);
11820     case 'h': // High regs or no regs.
11821       if (Subtarget->isThumb())
11822         return RCPair(0U, &ARM::hGPRRegClass);
11823       break;
11824     case 'r':
11825       if (Subtarget->isThumb1Only())
11826         return RCPair(0U, &ARM::tGPRRegClass);
11827       return RCPair(0U, &ARM::GPRRegClass);
11828     case 'w':
11829       if (VT == MVT::Other)
11830         break;
11831       if (VT == MVT::f32)
11832         return RCPair(0U, &ARM::SPRRegClass);
11833       if (VT.getSizeInBits() == 64)
11834         return RCPair(0U, &ARM::DPRRegClass);
11835       if (VT.getSizeInBits() == 128)
11836         return RCPair(0U, &ARM::QPRRegClass);
11837       break;
11838     case 'x':
11839       if (VT == MVT::Other)
11840         break;
11841       if (VT == MVT::f32)
11842         return RCPair(0U, &ARM::SPR_8RegClass);
11843       if (VT.getSizeInBits() == 64)
11844         return RCPair(0U, &ARM::DPR_8RegClass);
11845       if (VT.getSizeInBits() == 128)
11846         return RCPair(0U, &ARM::QPR_8RegClass);
11847       break;
11848     case 't':
11849       if (VT == MVT::f32)
11850         return RCPair(0U, &ARM::SPRRegClass);
11851       break;
11852     }
11853   }
11854   if (StringRef("{cc}").equals_lower(Constraint))
11855     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11856
11857   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11858 }
11859
11860 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11861 /// vector.  If it is invalid, don't add anything to Ops.
11862 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11863                                                      std::string &Constraint,
11864                                                      std::vector<SDValue>&Ops,
11865                                                      SelectionDAG &DAG) const {
11866   SDValue Result;
11867
11868   // Currently only support length 1 constraints.
11869   if (Constraint.length() != 1) return;
11870
11871   char ConstraintLetter = Constraint[0];
11872   switch (ConstraintLetter) {
11873   default: break;
11874   case 'j':
11875   case 'I': case 'J': case 'K': case 'L':
11876   case 'M': case 'N': case 'O':
11877     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11878     if (!C)
11879       return;
11880
11881     int64_t CVal64 = C->getSExtValue();
11882     int CVal = (int) CVal64;
11883     // None of these constraints allow values larger than 32 bits.  Check
11884     // that the value fits in an int.
11885     if (CVal != CVal64)
11886       return;
11887
11888     switch (ConstraintLetter) {
11889       case 'j':
11890         // Constant suitable for movw, must be between 0 and
11891         // 65535.
11892         if (Subtarget->hasV6T2Ops())
11893           if (CVal >= 0 && CVal <= 65535)
11894             break;
11895         return;
11896       case 'I':
11897         if (Subtarget->isThumb1Only()) {
11898           // This must be a constant between 0 and 255, for ADD
11899           // immediates.
11900           if (CVal >= 0 && CVal <= 255)
11901             break;
11902         } else if (Subtarget->isThumb2()) {
11903           // A constant that can be used as an immediate value in a
11904           // data-processing instruction.
11905           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11906             break;
11907         } else {
11908           // A constant that can be used as an immediate value in a
11909           // data-processing instruction.
11910           if (ARM_AM::getSOImmVal(CVal) != -1)
11911             break;
11912         }
11913         return;
11914
11915       case 'J':
11916         if (Subtarget->isThumb1Only()) {
11917           // This must be a constant between -255 and -1, for negated ADD
11918           // immediates. This can be used in GCC with an "n" modifier that
11919           // prints the negated value, for use with SUB instructions. It is
11920           // not useful otherwise but is implemented for compatibility.
11921           if (CVal >= -255 && CVal <= -1)
11922             break;
11923         } else {
11924           // This must be a constant between -4095 and 4095. It is not clear
11925           // what this constraint is intended for. Implemented for
11926           // compatibility with GCC.
11927           if (CVal >= -4095 && CVal <= 4095)
11928             break;
11929         }
11930         return;
11931
11932       case 'K':
11933         if (Subtarget->isThumb1Only()) {
11934           // A 32-bit value where only one byte has a nonzero value. Exclude
11935           // zero to match GCC. This constraint is used by GCC internally for
11936           // constants that can be loaded with a move/shift combination.
11937           // It is not useful otherwise but is implemented for compatibility.
11938           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11939             break;
11940         } else if (Subtarget->isThumb2()) {
11941           // A constant whose bitwise inverse can be used as an immediate
11942           // value in a data-processing instruction. This can be used in GCC
11943           // with a "B" modifier that prints the inverted value, for use with
11944           // BIC and MVN instructions. It is not useful otherwise but is
11945           // implemented for compatibility.
11946           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11947             break;
11948         } else {
11949           // A constant whose bitwise inverse can be used as an immediate
11950           // value in a data-processing instruction. This can be used in GCC
11951           // with a "B" modifier that prints the inverted value, for use with
11952           // BIC and MVN instructions. It is not useful otherwise but is
11953           // implemented for compatibility.
11954           if (ARM_AM::getSOImmVal(~CVal) != -1)
11955             break;
11956         }
11957         return;
11958
11959       case 'L':
11960         if (Subtarget->isThumb1Only()) {
11961           // This must be a constant between -7 and 7,
11962           // for 3-operand ADD/SUB immediate instructions.
11963           if (CVal >= -7 && CVal < 7)
11964             break;
11965         } else if (Subtarget->isThumb2()) {
11966           // A constant whose negation can be used as an immediate value in a
11967           // data-processing instruction. This can be used in GCC with an "n"
11968           // modifier that prints the negated value, for use with SUB
11969           // instructions. It is not useful otherwise but is implemented for
11970           // compatibility.
11971           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11972             break;
11973         } else {
11974           // A constant whose negation can be used as an immediate value in a
11975           // data-processing instruction. This can be used in GCC with an "n"
11976           // modifier that prints the negated value, for use with SUB
11977           // instructions. It is not useful otherwise but is implemented for
11978           // compatibility.
11979           if (ARM_AM::getSOImmVal(-CVal) != -1)
11980             break;
11981         }
11982         return;
11983
11984       case 'M':
11985         if (Subtarget->isThumb1Only()) {
11986           // This must be a multiple of 4 between 0 and 1020, for
11987           // ADD sp + immediate.
11988           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11989             break;
11990         } else {
11991           // A power of two or a constant between 0 and 32.  This is used in
11992           // GCC for the shift amount on shifted register operands, but it is
11993           // useful in general for any shift amounts.
11994           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11995             break;
11996         }
11997         return;
11998
11999       case 'N':
12000         if (Subtarget->isThumb()) {  // FIXME thumb2
12001           // This must be a constant between 0 and 31, for shift amounts.
12002           if (CVal >= 0 && CVal <= 31)
12003             break;
12004         }
12005         return;
12006
12007       case 'O':
12008         if (Subtarget->isThumb()) {  // FIXME thumb2
12009           // This must be a multiple of 4 between -508 and 508, for
12010           // ADD/SUB sp = sp + immediate.
12011           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12012             break;
12013         }
12014         return;
12015     }
12016     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12017     break;
12018   }
12019
12020   if (Result.getNode()) {
12021     Ops.push_back(Result);
12022     return;
12023   }
12024   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12025 }
12026
12027 static RTLIB::Libcall getDivRemLibcall(
12028     const SDNode *N, MVT::SimpleValueType SVT) {
12029   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12030           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12031          "Unhandled Opcode in getDivRemLibcall");
12032   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12033                   N->getOpcode() == ISD::SREM;
12034   RTLIB::Libcall LC;
12035   switch (SVT) {
12036   default: llvm_unreachable("Unexpected request for libcall!");
12037   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
12038   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12039   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12040   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12041   }
12042   return LC;
12043 }
12044
12045 static TargetLowering::ArgListTy getDivRemArgList(
12046     const SDNode *N, LLVMContext *Context) {
12047   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12048           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12049          "Unhandled Opcode in getDivRemArgList");
12050   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12051                   N->getOpcode() == ISD::SREM;
12052   TargetLowering::ArgListTy Args;
12053   TargetLowering::ArgListEntry Entry;
12054   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12055     EVT ArgVT = N->getOperand(i).getValueType();
12056     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12057     Entry.Node = N->getOperand(i);
12058     Entry.Ty = ArgTy;
12059     Entry.isSExt = isSigned;
12060     Entry.isZExt = !isSigned;
12061     Args.push_back(Entry);
12062   }
12063   return Args;
12064 }
12065
12066 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12067   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12068           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI()) &&
12069          "Register-based DivRem lowering only");
12070   unsigned Opcode = Op->getOpcode();
12071   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12072          "Invalid opcode for Div/Rem lowering");
12073   bool isSigned = (Opcode == ISD::SDIVREM);
12074   EVT VT = Op->getValueType(0);
12075   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12076
12077   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12078                                        VT.getSimpleVT().SimpleTy);
12079   SDValue InChain = DAG.getEntryNode();
12080
12081   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12082                                                     DAG.getContext());
12083
12084   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12085                                          getPointerTy(DAG.getDataLayout()));
12086
12087   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12088
12089   SDLoc dl(Op);
12090   TargetLowering::CallLoweringInfo CLI(DAG);
12091   CLI.setDebugLoc(dl).setChain(InChain)
12092     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
12093     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
12094
12095   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
12096   return CallInfo.first;
12097 }
12098
12099 // Lowers REM using divmod helpers
12100 // see RTABI section 4.2/4.3
12101 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
12102   // Build return types (div and rem)
12103   std::vector<Type*> RetTyParams;
12104   Type *RetTyElement;
12105
12106   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
12107   default: llvm_unreachable("Unexpected request for libcall!");
12108   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
12109   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
12110   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
12111   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
12112   }
12113
12114   RetTyParams.push_back(RetTyElement);
12115   RetTyParams.push_back(RetTyElement);
12116   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
12117   Type *RetTy = StructType::get(*DAG.getContext(), ret);
12118
12119   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
12120                                                              SimpleTy);
12121   SDValue InChain = DAG.getEntryNode();
12122   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
12123   bool isSigned = N->getOpcode() == ISD::SREM;
12124   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12125                                          getPointerTy(DAG.getDataLayout()));
12126
12127   // Lower call
12128   CallLoweringInfo CLI(DAG);
12129   CLI.setChain(InChain)
12130      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
12131      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
12132   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12133
12134   // Return second (rem) result operand (first contains div)
12135   SDNode *ResNode = CallResult.first.getNode();
12136   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
12137   return ResNode->getOperand(1);
12138 }
12139
12140 SDValue
12141 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
12142   assert(Subtarget->isTargetWindows() && "unsupported target platform");
12143   SDLoc DL(Op);
12144
12145   // Get the inputs.
12146   SDValue Chain = Op.getOperand(0);
12147   SDValue Size  = Op.getOperand(1);
12148
12149   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
12150                               DAG.getConstant(2, DL, MVT::i32));
12151
12152   SDValue Flag;
12153   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
12154   Flag = Chain.getValue(1);
12155
12156   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12157   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
12158
12159   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
12160   Chain = NewSP.getValue(1);
12161
12162   SDValue Ops[2] = { NewSP, Chain };
12163   return DAG.getMergeValues(Ops, DL);
12164 }
12165
12166 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12167   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
12168          "Unexpected type for custom-lowering FP_EXTEND");
12169
12170   RTLIB::Libcall LC;
12171   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
12172
12173   SDValue SrcVal = Op.getOperand(0);
12174   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12175                      SDLoc(Op)).first;
12176 }
12177
12178 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12179   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
12180          Subtarget->isFPOnlySP() &&
12181          "Unexpected type for custom-lowering FP_ROUND");
12182
12183   RTLIB::Libcall LC;
12184   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
12185
12186   SDValue SrcVal = Op.getOperand(0);
12187   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12188                      SDLoc(Op)).first;
12189 }
12190
12191 bool
12192 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12193   // The ARM target isn't yet aware of offsets.
12194   return false;
12195 }
12196
12197 bool ARM::isBitFieldInvertedMask(unsigned v) {
12198   if (v == 0xffffffff)
12199     return false;
12200
12201   // there can be 1's on either or both "outsides", all the "inside"
12202   // bits must be 0's
12203   return isShiftedMask_32(~v);
12204 }
12205
12206 /// isFPImmLegal - Returns true if the target can instruction select the
12207 /// specified FP immediate natively. If false, the legalizer will
12208 /// materialize the FP immediate as a load from a constant pool.
12209 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12210   if (!Subtarget->hasVFP3())
12211     return false;
12212   if (VT == MVT::f32)
12213     return ARM_AM::getFP32Imm(Imm) != -1;
12214   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
12215     return ARM_AM::getFP64Imm(Imm) != -1;
12216   return false;
12217 }
12218
12219 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
12220 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
12221 /// specified in the intrinsic calls.
12222 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12223                                            const CallInst &I,
12224                                            unsigned Intrinsic) const {
12225   switch (Intrinsic) {
12226   case Intrinsic::arm_neon_vld1:
12227   case Intrinsic::arm_neon_vld2:
12228   case Intrinsic::arm_neon_vld3:
12229   case Intrinsic::arm_neon_vld4:
12230   case Intrinsic::arm_neon_vld2lane:
12231   case Intrinsic::arm_neon_vld3lane:
12232   case Intrinsic::arm_neon_vld4lane: {
12233     Info.opc = ISD::INTRINSIC_W_CHAIN;
12234     // Conservatively set memVT to the entire set of vectors loaded.
12235     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12236     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
12237     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12238     Info.ptrVal = I.getArgOperand(0);
12239     Info.offset = 0;
12240     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12241     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12242     Info.vol = false; // volatile loads with NEON intrinsics not supported
12243     Info.readMem = true;
12244     Info.writeMem = false;
12245     return true;
12246   }
12247   case Intrinsic::arm_neon_vst1:
12248   case Intrinsic::arm_neon_vst2:
12249   case Intrinsic::arm_neon_vst3:
12250   case Intrinsic::arm_neon_vst4:
12251   case Intrinsic::arm_neon_vst2lane:
12252   case Intrinsic::arm_neon_vst3lane:
12253   case Intrinsic::arm_neon_vst4lane: {
12254     Info.opc = ISD::INTRINSIC_VOID;
12255     // Conservatively set memVT to the entire set of vectors stored.
12256     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12257     unsigned NumElts = 0;
12258     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
12259       Type *ArgTy = I.getArgOperand(ArgI)->getType();
12260       if (!ArgTy->isVectorTy())
12261         break;
12262       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
12263     }
12264     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12265     Info.ptrVal = I.getArgOperand(0);
12266     Info.offset = 0;
12267     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12268     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12269     Info.vol = false; // volatile stores with NEON intrinsics not supported
12270     Info.readMem = false;
12271     Info.writeMem = true;
12272     return true;
12273   }
12274   case Intrinsic::arm_ldaex:
12275   case Intrinsic::arm_ldrex: {
12276     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12277     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
12278     Info.opc = ISD::INTRINSIC_W_CHAIN;
12279     Info.memVT = MVT::getVT(PtrTy->getElementType());
12280     Info.ptrVal = I.getArgOperand(0);
12281     Info.offset = 0;
12282     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12283     Info.vol = true;
12284     Info.readMem = true;
12285     Info.writeMem = false;
12286     return true;
12287   }
12288   case Intrinsic::arm_stlex:
12289   case Intrinsic::arm_strex: {
12290     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12291     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
12292     Info.opc = ISD::INTRINSIC_W_CHAIN;
12293     Info.memVT = MVT::getVT(PtrTy->getElementType());
12294     Info.ptrVal = I.getArgOperand(1);
12295     Info.offset = 0;
12296     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12297     Info.vol = true;
12298     Info.readMem = false;
12299     Info.writeMem = true;
12300     return true;
12301   }
12302   case Intrinsic::arm_stlexd:
12303   case Intrinsic::arm_strexd: {
12304     Info.opc = ISD::INTRINSIC_W_CHAIN;
12305     Info.memVT = MVT::i64;
12306     Info.ptrVal = I.getArgOperand(2);
12307     Info.offset = 0;
12308     Info.align = 8;
12309     Info.vol = true;
12310     Info.readMem = false;
12311     Info.writeMem = true;
12312     return true;
12313   }
12314   case Intrinsic::arm_ldaexd:
12315   case Intrinsic::arm_ldrexd: {
12316     Info.opc = ISD::INTRINSIC_W_CHAIN;
12317     Info.memVT = MVT::i64;
12318     Info.ptrVal = I.getArgOperand(0);
12319     Info.offset = 0;
12320     Info.align = 8;
12321     Info.vol = true;
12322     Info.readMem = true;
12323     Info.writeMem = false;
12324     return true;
12325   }
12326   default:
12327     break;
12328   }
12329
12330   return false;
12331 }
12332
12333 /// \brief Returns true if it is beneficial to convert a load of a constant
12334 /// to just the constant itself.
12335 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12336                                                           Type *Ty) const {
12337   assert(Ty->isIntegerTy());
12338
12339   unsigned Bits = Ty->getPrimitiveSizeInBits();
12340   if (Bits == 0 || Bits > 32)
12341     return false;
12342   return true;
12343 }
12344
12345 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
12346                                         ARM_MB::MemBOpt Domain) const {
12347   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12348
12349   // First, if the target has no DMB, see what fallback we can use.
12350   if (!Subtarget->hasDataBarrier()) {
12351     // Some ARMv6 cpus can support data barriers with an mcr instruction.
12352     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
12353     // here.
12354     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
12355       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
12356       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
12357                         Builder.getInt32(0), Builder.getInt32(7),
12358                         Builder.getInt32(10), Builder.getInt32(5)};
12359       return Builder.CreateCall(MCR, args);
12360     } else {
12361       // Instead of using barriers, atomic accesses on these subtargets use
12362       // libcalls.
12363       llvm_unreachable("makeDMB on a target so old that it has no barriers");
12364     }
12365   } else {
12366     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
12367     // Only a full system barrier exists in the M-class architectures.
12368     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
12369     Constant *CDomain = Builder.getInt32(Domain);
12370     return Builder.CreateCall(DMB, CDomain);
12371   }
12372 }
12373
12374 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
12375 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
12376                                          AtomicOrdering Ord, bool IsStore,
12377                                          bool IsLoad) const {
12378   switch (Ord) {
12379   case AtomicOrdering::NotAtomic:
12380   case AtomicOrdering::Unordered:
12381     llvm_unreachable("Invalid fence: unordered/non-atomic");
12382   case AtomicOrdering::Monotonic:
12383   case AtomicOrdering::Acquire:
12384     return nullptr; // Nothing to do
12385   case AtomicOrdering::SequentiallyConsistent:
12386     if (!IsStore)
12387       return nullptr; // Nothing to do
12388     /*FALLTHROUGH*/
12389   case AtomicOrdering::Release:
12390   case AtomicOrdering::AcquireRelease:
12391     if (Subtarget->preferISHSTBarriers())
12392       return makeDMB(Builder, ARM_MB::ISHST);
12393     // FIXME: add a comment with a link to documentation justifying this.
12394     else
12395       return makeDMB(Builder, ARM_MB::ISH);
12396   }
12397   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12398 }
12399
12400 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12401                                           AtomicOrdering Ord, bool IsStore,
12402                                           bool IsLoad) const {
12403   switch (Ord) {
12404   case AtomicOrdering::NotAtomic:
12405   case AtomicOrdering::Unordered:
12406     llvm_unreachable("Invalid fence: unordered/not-atomic");
12407   case AtomicOrdering::Monotonic:
12408   case AtomicOrdering::Release:
12409     return nullptr; // Nothing to do
12410   case AtomicOrdering::Acquire:
12411   case AtomicOrdering::AcquireRelease:
12412   case AtomicOrdering::SequentiallyConsistent:
12413     return makeDMB(Builder, ARM_MB::ISH);
12414   }
12415   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12416 }
12417
12418 // Loads and stores less than 64-bits are already atomic; ones above that
12419 // are doomed anyway, so defer to the default libcall and blame the OS when
12420 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12421 // anything for those.
12422 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12423   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12424   return (Size == 64) && !Subtarget->isMClass();
12425 }
12426
12427 // Loads and stores less than 64-bits are already atomic; ones above that
12428 // are doomed anyway, so defer to the default libcall and blame the OS when
12429 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12430 // anything for those.
12431 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12432 // guarantee, see DDI0406C ARM architecture reference manual,
12433 // sections A8.8.72-74 LDRD)
12434 TargetLowering::AtomicExpansionKind
12435 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12436   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12437   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12438                                                   : AtomicExpansionKind::None;
12439 }
12440
12441 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12442 // and up to 64 bits on the non-M profiles
12443 TargetLowering::AtomicExpansionKind
12444 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12445   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12446   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12447              ? AtomicExpansionKind::LLSC
12448              : AtomicExpansionKind::None;
12449 }
12450
12451 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12452     AtomicCmpXchgInst *AI) const {
12453   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12454   // implement cmpxchg without spilling. If the address being exchanged is also
12455   // on the stack and close enough to the spill slot, this can lead to a
12456   // situation where the monitor always gets cleared and the atomic operation
12457   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12458   return getTargetMachine().getOptLevel() != 0;
12459 }
12460
12461 bool ARMTargetLowering::shouldInsertFencesForAtomic(
12462     const Instruction *I) const {
12463   return InsertFencesForAtomic;
12464 }
12465
12466 // This has so far only been implemented for MachO.
12467 bool ARMTargetLowering::useLoadStackGuardNode() const {
12468   return Subtarget->isTargetMachO();
12469 }
12470
12471 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12472                                                   unsigned &Cost) const {
12473   // If we do not have NEON, vector types are not natively supported.
12474   if (!Subtarget->hasNEON())
12475     return false;
12476
12477   // Floating point values and vector values map to the same register file.
12478   // Therefore, although we could do a store extract of a vector type, this is
12479   // better to leave at float as we have more freedom in the addressing mode for
12480   // those.
12481   if (VectorTy->isFPOrFPVectorTy())
12482     return false;
12483
12484   // If the index is unknown at compile time, this is very expensive to lower
12485   // and it is not possible to combine the store with the extract.
12486   if (!isa<ConstantInt>(Idx))
12487     return false;
12488
12489   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12490   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12491   // We can do a store + vector extract on any vector that fits perfectly in a D
12492   // or Q register.
12493   if (BitWidth == 64 || BitWidth == 128) {
12494     Cost = 0;
12495     return true;
12496   }
12497   return false;
12498 }
12499
12500 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12501   return Subtarget->hasV6T2Ops();
12502 }
12503
12504 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12505   return Subtarget->hasV6T2Ops();
12506 }
12507
12508 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12509                                          AtomicOrdering Ord) const {
12510   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12511   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12512   bool IsAcquire = isAcquireOrStronger(Ord);
12513
12514   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12515   // intrinsic must return {i32, i32} and we have to recombine them into a
12516   // single i64 here.
12517   if (ValTy->getPrimitiveSizeInBits() == 64) {
12518     Intrinsic::ID Int =
12519         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12520     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12521
12522     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12523     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12524
12525     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12526     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12527     if (!Subtarget->isLittle())
12528       std::swap (Lo, Hi);
12529     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12530     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12531     return Builder.CreateOr(
12532         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12533   }
12534
12535   Type *Tys[] = { Addr->getType() };
12536   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12537   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12538
12539   return Builder.CreateTruncOrBitCast(
12540       Builder.CreateCall(Ldrex, Addr),
12541       cast<PointerType>(Addr->getType())->getElementType());
12542 }
12543
12544 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12545     IRBuilder<> &Builder) const {
12546   if (!Subtarget->hasV7Ops())
12547     return;
12548   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12549   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12550 }
12551
12552 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12553                                                Value *Addr,
12554                                                AtomicOrdering Ord) const {
12555   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12556   bool IsRelease = isReleaseOrStronger(Ord);
12557
12558   // Since the intrinsics must have legal type, the i64 intrinsics take two
12559   // parameters: "i32, i32". We must marshal Val into the appropriate form
12560   // before the call.
12561   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12562     Intrinsic::ID Int =
12563         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
12564     Function *Strex = Intrinsic::getDeclaration(M, Int);
12565     Type *Int32Ty = Type::getInt32Ty(M->getContext());
12566
12567     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
12568     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
12569     if (!Subtarget->isLittle())
12570       std::swap (Lo, Hi);
12571     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12572     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
12573   }
12574
12575   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
12576   Type *Tys[] = { Addr->getType() };
12577   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
12578
12579   return Builder.CreateCall(
12580       Strex, {Builder.CreateZExtOrBitCast(
12581                   Val, Strex->getFunctionType()->getParamType(0)),
12582               Addr});
12583 }
12584
12585 /// \brief Lower an interleaved load into a vldN intrinsic.
12586 ///
12587 /// E.g. Lower an interleaved load (Factor = 2):
12588 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
12589 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12590 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12591 ///
12592 ///      Into:
12593 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
12594 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
12595 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
12596 bool ARMTargetLowering::lowerInterleavedLoad(
12597     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12598     ArrayRef<unsigned> Indices, unsigned Factor) const {
12599   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12600          "Invalid interleave factor");
12601   assert(!Shuffles.empty() && "Empty shufflevector input");
12602   assert(Shuffles.size() == Indices.size() &&
12603          "Unmatched number of shufflevectors and indices");
12604
12605   VectorType *VecTy = Shuffles[0]->getType();
12606   Type *EltTy = VecTy->getVectorElementType();
12607
12608   const DataLayout &DL = LI->getModule()->getDataLayout();
12609   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12610   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12611
12612   // Skip if we do not have NEON and skip illegal vector types and vector types
12613   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
12614   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
12615     return false;
12616
12617   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12618   // load integer vectors first and then convert to pointer vectors.
12619   if (EltTy->isPointerTy())
12620     VecTy =
12621         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
12622
12623   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
12624                                             Intrinsic::arm_neon_vld3,
12625                                             Intrinsic::arm_neon_vld4};
12626
12627   IRBuilder<> Builder(LI);
12628   SmallVector<Value *, 2> Ops;
12629
12630   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
12631   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
12632   Ops.push_back(Builder.getInt32(LI->getAlignment()));
12633
12634   Type *Tys[] = { VecTy, Int8Ptr };
12635   Function *VldnFunc =
12636       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12637   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
12638
12639   // Replace uses of each shufflevector with the corresponding vector loaded
12640   // by ldN.
12641   for (unsigned i = 0; i < Shuffles.size(); i++) {
12642     ShuffleVectorInst *SV = Shuffles[i];
12643     unsigned Index = Indices[i];
12644
12645     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
12646
12647     // Convert the integer vector to pointer vector if the element is pointer.
12648     if (EltTy->isPointerTy())
12649       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
12650
12651     SV->replaceAllUsesWith(SubVec);
12652   }
12653
12654   return true;
12655 }
12656
12657 /// \brief Get a mask consisting of sequential integers starting from \p Start.
12658 ///
12659 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
12660 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
12661                                    unsigned NumElts) {
12662   SmallVector<Constant *, 16> Mask;
12663   for (unsigned i = 0; i < NumElts; i++)
12664     Mask.push_back(Builder.getInt32(Start + i));
12665
12666   return ConstantVector::get(Mask);
12667 }
12668
12669 /// \brief Lower an interleaved store into a vstN intrinsic.
12670 ///
12671 /// E.g. Lower an interleaved store (Factor = 3):
12672 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12673 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12674 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
12675 ///
12676 ///      Into:
12677 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12678 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12679 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12680 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12681 ///
12682 /// Note that the new shufflevectors will be removed and we'll only generate one
12683 /// vst3 instruction in CodeGen.
12684 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12685                                               ShuffleVectorInst *SVI,
12686                                               unsigned Factor) const {
12687   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12688          "Invalid interleave factor");
12689
12690   VectorType *VecTy = SVI->getType();
12691   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12692          "Invalid interleaved store");
12693
12694   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12695   Type *EltTy = VecTy->getVectorElementType();
12696   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12697
12698   const DataLayout &DL = SI->getModule()->getDataLayout();
12699   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
12700   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
12701
12702   // Skip if we do not have NEON and skip illegal vector types and vector types
12703   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12704   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12705       EltIs64Bits)
12706     return false;
12707
12708   Value *Op0 = SVI->getOperand(0);
12709   Value *Op1 = SVI->getOperand(1);
12710   IRBuilder<> Builder(SI);
12711
12712   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12713   // vectors to integer vectors.
12714   if (EltTy->isPointerTy()) {
12715     Type *IntTy = DL.getIntPtrType(EltTy);
12716
12717     // Convert to the corresponding integer vector.
12718     Type *IntVecTy =
12719         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12720     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12721     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12722
12723     SubVecTy = VectorType::get(IntTy, NumSubElts);
12724   }
12725
12726   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12727                                              Intrinsic::arm_neon_vst3,
12728                                              Intrinsic::arm_neon_vst4};
12729   SmallVector<Value *, 6> Ops;
12730
12731   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12732   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12733
12734   Type *Tys[] = { Int8Ptr, SubVecTy };
12735   Function *VstNFunc = Intrinsic::getDeclaration(
12736       SI->getModule(), StoreInts[Factor - 2], Tys);
12737
12738   // Split the shufflevector operands into sub vectors for the new vstN call.
12739   for (unsigned i = 0; i < Factor; i++)
12740     Ops.push_back(Builder.CreateShuffleVector(
12741         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12742
12743   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12744   Builder.CreateCall(VstNFunc, Ops);
12745   return true;
12746 }
12747
12748 enum HABaseType {
12749   HA_UNKNOWN = 0,
12750   HA_FLOAT,
12751   HA_DOUBLE,
12752   HA_VECT64,
12753   HA_VECT128
12754 };
12755
12756 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12757                                    uint64_t &Members) {
12758   if (auto *ST = dyn_cast<StructType>(Ty)) {
12759     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12760       uint64_t SubMembers = 0;
12761       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12762         return false;
12763       Members += SubMembers;
12764     }
12765   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12766     uint64_t SubMembers = 0;
12767     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12768       return false;
12769     Members += SubMembers * AT->getNumElements();
12770   } else if (Ty->isFloatTy()) {
12771     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12772       return false;
12773     Members = 1;
12774     Base = HA_FLOAT;
12775   } else if (Ty->isDoubleTy()) {
12776     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12777       return false;
12778     Members = 1;
12779     Base = HA_DOUBLE;
12780   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12781     Members = 1;
12782     switch (Base) {
12783     case HA_FLOAT:
12784     case HA_DOUBLE:
12785       return false;
12786     case HA_VECT64:
12787       return VT->getBitWidth() == 64;
12788     case HA_VECT128:
12789       return VT->getBitWidth() == 128;
12790     case HA_UNKNOWN:
12791       switch (VT->getBitWidth()) {
12792       case 64:
12793         Base = HA_VECT64;
12794         return true;
12795       case 128:
12796         Base = HA_VECT128;
12797         return true;
12798       default:
12799         return false;
12800       }
12801     }
12802   }
12803
12804   return (Members > 0 && Members <= 4);
12805 }
12806
12807 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12808 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12809 /// passing according to AAPCS rules.
12810 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12811     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12812   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12813       CallingConv::ARM_AAPCS_VFP)
12814     return false;
12815
12816   HABaseType Base = HA_UNKNOWN;
12817   uint64_t Members = 0;
12818   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12819   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12820
12821   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12822   return IsHA || IsIntArray;
12823 }
12824
12825 unsigned ARMTargetLowering::getExceptionPointerRegister(
12826     const Constant *PersonalityFn) const {
12827   // Platforms which do not use SjLj EH may return values in these registers
12828   // via the personality function.
12829   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12830 }
12831
12832 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12833     const Constant *PersonalityFn) const {
12834   // Platforms which do not use SjLj EH may return values in these registers
12835   // via the personality function.
12836   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12837 }
12838
12839 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12840   // Update IsSplitCSR in ARMFunctionInfo.
12841   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
12842   AFI->setIsSplitCSR(true);
12843 }
12844
12845 void ARMTargetLowering::insertCopiesSplitCSR(
12846     MachineBasicBlock *Entry,
12847     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12848   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
12849   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12850   if (!IStart)
12851     return;
12852
12853   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12854   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12855   MachineBasicBlock::iterator MBBI = Entry->begin();
12856   for (const MCPhysReg *I = IStart; *I; ++I) {
12857     const TargetRegisterClass *RC = nullptr;
12858     if (ARM::GPRRegClass.contains(*I))
12859       RC = &ARM::GPRRegClass;
12860     else if (ARM::DPRRegClass.contains(*I))
12861       RC = &ARM::DPRRegClass;
12862     else
12863       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12864
12865     unsigned NewVR = MRI->createVirtualRegister(RC);
12866     // Create copy from CSR to a virtual register.
12867     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12868     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12869     // nounwind. If we want to generalize this later, we may need to emit
12870     // CFI pseudo-instructions.
12871     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12872                Attribute::NoUnwind) &&
12873            "Function should be nounwind in insertCopiesSplitCSR!");
12874     Entry->addLiveIn(*I);
12875     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12876         .addReg(*I);
12877
12878     // Insert the copy-back instructions right before the terminator.
12879     for (auto *Exit : Exits)
12880       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12881               TII->get(TargetOpcode::COPY), *I)
12882           .addReg(NewVR);
12883   }
12884 }