[ARM] Replace ARMISD::VMINNM/VMAXNM with ISD::FMINNUM/FMAXNUM
[oota-llvm.git] / 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 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145
146   if (VT.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       static const struct {
175         const RTLIB::Libcall Op;
176         const char * const Name;
177         const ISD::CondCode Cond;
178       } LibraryCalls[] = {
179         // Single-precision floating-point arithmetic.
180         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184
185         // Double-precision floating-point arithmetic.
186         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190
191         // Single-precision comparisons.
192         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200
201         // Double-precision comparisons.
202         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210
211         // Floating-point to integer conversions.
212         // i64 conversions are done via library routines even when generating VFP
213         // instructions, so use the same ones.
214         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218
219         // Conversions between floating types.
220         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222
223         // Integer to floating-point conversions.
224         // i64 conversions are done via library routines even when generating VFP
225         // instructions, so use the same ones.
226         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227         // e.g., __floatunsidf vs. __floatunssidfvfp.
228         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232       };
233
234       for (const auto &LC : LibraryCalls) {
235         setLibcallName(LC.Op, LC.Name);
236         if (LC.Cond != ISD::SETCC_INVALID)
237           setCmpLibcallCC(LC.Op, LC.Cond);
238       }
239     }
240   }
241
242   // These libcalls are not available in 32-bit.
243   setLibcallName(RTLIB::SHL_I128, nullptr);
244   setLibcallName(RTLIB::SRL_I128, nullptr);
245   setLibcallName(RTLIB::SRA_I128, nullptr);
246
247   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248       !Subtarget->isTargetWindows()) {
249     static const struct {
250       const RTLIB::Libcall Op;
251       const char * const Name;
252       const CallingConv::ID CC;
253       const ISD::CondCode Cond;
254     } LibraryCalls[] = {
255       // Double-precision floating-point arithmetic helper functions
256       // RTABI chapter 4.1.2, Table 2
257       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261
262       // Double-precision floating-point comparison helper functions
263       // RTABI chapter 4.1.2, Table 3
264       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
272
273       // Single-precision floating-point arithmetic helper functions
274       // RTABI chapter 4.1.2, Table 4
275       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279
280       // Single-precision floating-point comparison helper functions
281       // RTABI chapter 4.1.2, Table 5
282       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
290
291       // Floating-point to integer conversions.
292       // RTABI chapter 4.1.2, Table 6
293       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301
302       // Conversions between floating types.
303       // RTABI chapter 4.1.2, Table 7
304       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Integer to floating-point conversions.
309       // RTABI chapter 4.1.2, Table 8
310       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Long long helper functions
320       // RTABI chapter 4.2, Table 9
321       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325
326       // Integer division functions
327       // RTABI chapter 4.3.1
328       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Memory operations
338       // RTABI chapter 4.3.4
339       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342     };
343
344     for (const auto &LC : LibraryCalls) {
345       setLibcallName(LC.Op, LC.Name);
346       setLibcallCallingConv(LC.Op, LC.CC);
347       if (LC.Cond != ISD::SETCC_INVALID)
348         setCmpLibcallCC(LC.Op, LC.Cond);
349     }
350   }
351
352   if (Subtarget->isTargetWindows()) {
353     static const struct {
354       const RTLIB::Libcall Op;
355       const char * const Name;
356       const CallingConv::ID CC;
357     } LibraryCalls[] = {
358       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
366
367       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
430
431   if (Subtarget->hasNEON()) {
432     addDRTypeForNEON(MVT::v2f32);
433     addDRTypeForNEON(MVT::v8i8);
434     addDRTypeForNEON(MVT::v4i16);
435     addDRTypeForNEON(MVT::v2i32);
436     addDRTypeForNEON(MVT::v1i64);
437
438     addQRTypeForNEON(MVT::v4f32);
439     addQRTypeForNEON(MVT::v2f64);
440     addQRTypeForNEON(MVT::v16i8);
441     addQRTypeForNEON(MVT::v8i16);
442     addQRTypeForNEON(MVT::v4i32);
443     addQRTypeForNEON(MVT::v2i64);
444
445     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446     // neither Neon nor VFP support any arithmetic operations on it.
447     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448     // supported for v4f32.
449     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452     // FIXME: Code duplication: FDIV and FREM are expanded always, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456     // FIXME: Create unittest.
457     // In another words, find a way when "copysign" appears in DAG with vector
458     // operands.
459     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460     // FIXME: Code duplication: SETCC has custom operation action, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463     // FIXME: Create unittest for FNEG and for FABS.
464     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
483
484     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
499
500     // Mark v2f32 intrinsics.
501     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
516
517     // Neon does not support some operations on v1i64 and v2i64 types.
518     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519     // Custom handling for some quad-vector types to detect VMULL.
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523     // Custom handling for some vector types to avoid expensive expansions
524     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531     // a destination type that is wider than the source, and nor does
532     // it have a FP_TO_[SU]INT instruction with a narrower destination than
533     // source.
534     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
538
539     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
540     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
541
542     // NEON does not have single instruction CTPOP for vectors with element
543     // types wider than 8-bits.  However, custom lowering can leverage the
544     // v8i8/v16i8 vcnt instruction.
545     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
549
550     // NEON does not have single instruction CTTZ for vectors.
551     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
555
556     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
560
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
570
571     // NEON only has FMA instructions as of VFP4.
572     if (!Subtarget->hasVFP4()) {
573       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
575     }
576
577     setTargetDAGCombine(ISD::INTRINSIC_VOID);
578     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580     setTargetDAGCombine(ISD::SHL);
581     setTargetDAGCombine(ISD::SRL);
582     setTargetDAGCombine(ISD::SRA);
583     setTargetDAGCombine(ISD::SIGN_EXTEND);
584     setTargetDAGCombine(ISD::ZERO_EXTEND);
585     setTargetDAGCombine(ISD::ANY_EXTEND);
586     setTargetDAGCombine(ISD::SELECT_CC);
587     setTargetDAGCombine(ISD::BUILD_VECTOR);
588     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
589     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
590     setTargetDAGCombine(ISD::STORE);
591     setTargetDAGCombine(ISD::FP_TO_SINT);
592     setTargetDAGCombine(ISD::FP_TO_UINT);
593     setTargetDAGCombine(ISD::FDIV);
594     setTargetDAGCombine(ISD::LOAD);
595
596     // It is legal to extload from v4i8 to v4i16 or v4i32.
597     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
598                    MVT::v2i32}) {
599       for (MVT VT : MVT::integer_vector_valuetypes()) {
600         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
601         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
602         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
603       }
604     }
605   }
606
607   // ARM and Thumb2 support UMLAL/SMLAL.
608   if (!Subtarget->isThumb1Only())
609     setTargetDAGCombine(ISD::ADDC);
610
611   if (Subtarget->isFPOnlySP()) {
612     // When targeting a floating-point unit with only single-precision
613     // operations, f64 is legal for the few double-precision instructions which
614     // are present However, no double-precision operations other than moves,
615     // loads and stores are provided by the hardware.
616     setOperationAction(ISD::FADD,       MVT::f64, Expand);
617     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
618     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
619     setOperationAction(ISD::FMA,        MVT::f64, Expand);
620     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
621     setOperationAction(ISD::FREM,       MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
623     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
624     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
625     setOperationAction(ISD::FABS,       MVT::f64, Expand);
626     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
627     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
628     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
629     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
630     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
631     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
632     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
633     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
634     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
635     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
636     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
637     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
638     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
639     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
640     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
641     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
645     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
646     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
647     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
648     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
649   }
650
651   computeRegisterProperties(Subtarget->getRegisterInfo());
652
653   // ARM does not have floating-point extending loads.
654   for (MVT VT : MVT::fp_valuetypes()) {
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
656     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
657   }
658
659   // ... or truncating stores
660   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
661   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
662   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663
664   // ARM does not have i1 sign extending load.
665   for (MVT VT : MVT::integer_valuetypes())
666     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
667
668   // ARM supports all 4 flavors of integer indexed load / store.
669   if (!Subtarget->isThumb1Only()) {
670     for (unsigned im = (unsigned)ISD::PRE_INC;
671          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
672       setIndexedLoadAction(im,  MVT::i1,  Legal);
673       setIndexedLoadAction(im,  MVT::i8,  Legal);
674       setIndexedLoadAction(im,  MVT::i16, Legal);
675       setIndexedLoadAction(im,  MVT::i32, Legal);
676       setIndexedStoreAction(im, MVT::i1,  Legal);
677       setIndexedStoreAction(im, MVT::i8,  Legal);
678       setIndexedStoreAction(im, MVT::i16, Legal);
679       setIndexedStoreAction(im, MVT::i32, Legal);
680     }
681   }
682
683   setOperationAction(ISD::SADDO, MVT::i32, Custom);
684   setOperationAction(ISD::UADDO, MVT::i32, Custom);
685   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
686   setOperationAction(ISD::USUBO, MVT::i32, Custom);
687
688   // i64 operation support.
689   setOperationAction(ISD::MUL,     MVT::i64, Expand);
690   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
691   if (Subtarget->isThumb1Only()) {
692     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
693     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
694   }
695   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
696       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
697     setOperationAction(ISD::MULHS, MVT::i32, Expand);
698
699   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
700   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
702   setOperationAction(ISD::SRL,       MVT::i64, Custom);
703   setOperationAction(ISD::SRA,       MVT::i64, Custom);
704
705   if (!Subtarget->isThumb1Only()) {
706     // FIXME: We should do this for Thumb1 as well.
707     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
708     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
709     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
710     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
711   }
712
713   // ARM does not have ROTL.
714   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
715   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
716   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
717   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
718     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
719
720   // These just redirect to CTTZ and CTLZ on ARM.
721   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
722   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
723
724   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
725
726   // Only ARMv6 has BSWAP.
727   if (!Subtarget->hasV6Ops())
728     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
729
730   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
731       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
732     // These are expanded into libcalls if the cpu doesn't have HW divider.
733     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
734     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
735   }
736
737   // FIXME: Also set divmod for SREM on EABI/androideabi
738   setOperationAction(ISD::SREM,  MVT::i32, Expand);
739   setOperationAction(ISD::UREM,  MVT::i32, Expand);
740   // Register based DivRem for AEABI (RTABI 4.2)
741   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
742     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
743     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
744     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
745     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
746     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
747     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
748     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
749     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
750
751     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
752     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
754     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
755     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
758     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
759
760     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
761     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
762   } else {
763     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
764     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
765   }
766
767   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
768   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
769   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
770   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
771   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
772
773   setOperationAction(ISD::TRAP, MVT::Other, Legal);
774
775   // Use the default implementation.
776   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
777   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
778   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
779   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
780   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
781   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
782
783   if (!Subtarget->isTargetMachO()) {
784     // Non-MachO platforms may return values in these registers via the
785     // personality function.
786     setExceptionPointerRegister(ARM::R0);
787     setExceptionSelectorRegister(ARM::R1);
788   }
789
790   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
791     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
792   else
793     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
794
795   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
796   // the default expansion. If we are targeting a single threaded system,
797   // then set them all for expand so we can lower them later into their
798   // non-atomic form.
799   if (TM.Options.ThreadModel == ThreadModel::Single)
800     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
801   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
802     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
803     // to ldrex/strex loops already.
804     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
805
806     // On v8, we have particularly efficient implementations of atomic fences
807     // if they can be combined with nearby atomic loads and stores.
808     if (!Subtarget->hasV8Ops()) {
809       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
810       setInsertFencesForAtomic(true);
811     }
812   } else {
813     // If there's anything we can use as a barrier, go through custom lowering
814     // for ATOMIC_FENCE.
815     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
816                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
817
818     // Set them all for expansion, which will force libcalls.
819     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
820     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
830     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
831     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
832     // Unordered/Monotonic case.
833     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
834     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
835   }
836
837   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
838
839   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
840   if (!Subtarget->hasV6Ops()) {
841     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
842     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
843   }
844   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
845
846   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
847       !Subtarget->isThumb1Only()) {
848     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
849     // iff target supports vfp2.
850     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
851     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
852   }
853
854   // We want to custom lower some of our intrinsics.
855   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
856   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
857   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
858   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
859   if (Subtarget->isTargetDarwin())
860     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
861
862   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
863   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
864   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
865   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
866   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
867   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
868   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
869   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
870   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
871
872   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
873   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
874   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
875   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
876   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
877
878   // We don't support sin/cos/fmod/copysign/pow
879   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
880   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
881   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
882   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
883   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
884   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
885   setOperationAction(ISD::FREM,      MVT::f64, Expand);
886   setOperationAction(ISD::FREM,      MVT::f32, Expand);
887   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
888       !Subtarget->isThumb1Only()) {
889     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
890     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
891   }
892   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
893   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
894
895   if (!Subtarget->hasVFP4()) {
896     setOperationAction(ISD::FMA, MVT::f64, Expand);
897     setOperationAction(ISD::FMA, MVT::f32, Expand);
898   }
899
900   // Various VFP goodness
901   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
902     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
903     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
904       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
905       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
906     }
907
908     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
909     if (!Subtarget->hasFP16()) {
910       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
911       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
912     }
913   }
914
915   // Combine sin / cos into one node or libcall if possible.
916   if (Subtarget->hasSinCos()) {
917     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
918     setLibcallName(RTLIB::SINCOS_F64, "sincos");
919     if (Subtarget->getTargetTriple().isiOS()) {
920       // For iOS, we don't want to the normal expansion of a libcall to
921       // sincos. We want to issue a libcall to __sincos_stret.
922       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
923       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
924     }
925   }
926
927   // FP-ARMv8 implements a lot of rounding-like FP operations.
928   if (Subtarget->hasFPARMv8()) {
929     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
930     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
931     setOperationAction(ISD::FROUND, MVT::f32, Legal);
932     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
933     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
934     setOperationAction(ISD::FRINT, MVT::f32, Legal);
935     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
936     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
937     if (!Subtarget->isFPOnlySP()) {
938       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
939       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
940       setOperationAction(ISD::FROUND, MVT::f64, Legal);
941       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
942       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
943       setOperationAction(ISD::FRINT, MVT::f64, Legal);
944       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
945       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
946     }
947   }
948
949   if (Subtarget->hasVFP3()) {
950     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
951     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
952     setOperationAction(ISD::FMINNAN, MVT::f64, Legal);
953     setOperationAction(ISD::FMAXNAN, MVT::f64, Legal);
954   }
955
956   // We have target-specific dag combine patterns for the following nodes:
957   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
958   setTargetDAGCombine(ISD::ADD);
959   setTargetDAGCombine(ISD::SUB);
960   setTargetDAGCombine(ISD::MUL);
961   setTargetDAGCombine(ISD::AND);
962   setTargetDAGCombine(ISD::OR);
963   setTargetDAGCombine(ISD::XOR);
964
965   if (Subtarget->hasV6Ops())
966     setTargetDAGCombine(ISD::SRL);
967
968   setStackPointerRegisterToSaveRestore(ARM::SP);
969
970   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
971       !Subtarget->hasVFP2())
972     setSchedulingPreference(Sched::RegPressure);
973   else
974     setSchedulingPreference(Sched::Hybrid);
975
976   //// temporary - rewrite interface to use type
977   MaxStoresPerMemset = 8;
978   MaxStoresPerMemsetOptSize = 4;
979   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
980   MaxStoresPerMemcpyOptSize = 2;
981   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
982   MaxStoresPerMemmoveOptSize = 2;
983
984   // On ARM arguments smaller than 4 bytes are extended, so all arguments
985   // are at least 4 bytes aligned.
986   setMinStackArgumentAlignment(4);
987
988   // Prefer likely predicted branches to selects on out-of-order cores.
989   PredictableSelectIsExpensive = Subtarget->isLikeA9();
990
991   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
992 }
993
994 bool ARMTargetLowering::useSoftFloat() const {
995   return Subtarget->useSoftFloat();
996 }
997
998 // FIXME: It might make sense to define the representative register class as the
999 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1000 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1001 // SPR's representative would be DPR_VFP2. This should work well if register
1002 // pressure tracking were modified such that a register use would increment the
1003 // pressure of the register class's representative and all of it's super
1004 // classes' representatives transitively. We have not implemented this because
1005 // of the difficulty prior to coalescing of modeling operand register classes
1006 // due to the common occurrence of cross class copies and subregister insertions
1007 // and extractions.
1008 std::pair<const TargetRegisterClass *, uint8_t>
1009 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1010                                            MVT VT) const {
1011   const TargetRegisterClass *RRC = nullptr;
1012   uint8_t Cost = 1;
1013   switch (VT.SimpleTy) {
1014   default:
1015     return TargetLowering::findRepresentativeClass(TRI, VT);
1016   // Use DPR as representative register class for all floating point
1017   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1018   // the cost is 1 for both f32 and f64.
1019   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1020   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1021     RRC = &ARM::DPRRegClass;
1022     // When NEON is used for SP, only half of the register file is available
1023     // because operations that define both SP and DP results will be constrained
1024     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1025     // coalescing by double-counting the SP regs. See the FIXME above.
1026     if (Subtarget->useNEONForSinglePrecisionFP())
1027       Cost = 2;
1028     break;
1029   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1030   case MVT::v4f32: case MVT::v2f64:
1031     RRC = &ARM::DPRRegClass;
1032     Cost = 2;
1033     break;
1034   case MVT::v4i64:
1035     RRC = &ARM::DPRRegClass;
1036     Cost = 4;
1037     break;
1038   case MVT::v8i64:
1039     RRC = &ARM::DPRRegClass;
1040     Cost = 8;
1041     break;
1042   }
1043   return std::make_pair(RRC, Cost);
1044 }
1045
1046 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1047   switch ((ARMISD::NodeType)Opcode) {
1048   case ARMISD::FIRST_NUMBER:  break;
1049   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1050   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1051   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1052   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1053   case ARMISD::CALL:          return "ARMISD::CALL";
1054   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1055   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1056   case ARMISD::tCALL:         return "ARMISD::tCALL";
1057   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1058   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1059   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1060   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1061   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1062   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1063   case ARMISD::CMP:           return "ARMISD::CMP";
1064   case ARMISD::CMN:           return "ARMISD::CMN";
1065   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1066   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1067   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1068   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1069   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1070
1071   case ARMISD::CMOV:          return "ARMISD::CMOV";
1072
1073   case ARMISD::RBIT:          return "ARMISD::RBIT";
1074
1075   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1076   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1077   case ARMISD::RRX:           return "ARMISD::RRX";
1078
1079   case ARMISD::ADDC:          return "ARMISD::ADDC";
1080   case ARMISD::ADDE:          return "ARMISD::ADDE";
1081   case ARMISD::SUBC:          return "ARMISD::SUBC";
1082   case ARMISD::SUBE:          return "ARMISD::SUBE";
1083
1084   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1085   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1086
1087   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1088   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1089   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1090
1091   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1092
1093   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1094
1095   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1096
1097   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1098
1099   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1100
1101   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1102
1103   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1104   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1105   case ARMISD::VCGE:          return "ARMISD::VCGE";
1106   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1107   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1108   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1109   case ARMISD::VCGT:          return "ARMISD::VCGT";
1110   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1111   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1112   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1113   case ARMISD::VTST:          return "ARMISD::VTST";
1114
1115   case ARMISD::VSHL:          return "ARMISD::VSHL";
1116   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1117   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1118   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1119   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1120   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1121   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1122   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1123   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1124   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1125   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1126   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1127   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1128   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1129   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1130   case ARMISD::VSLI:          return "ARMISD::VSLI";
1131   case ARMISD::VSRI:          return "ARMISD::VSRI";
1132   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1133   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1134   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1135   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1136   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1137   case ARMISD::VDUP:          return "ARMISD::VDUP";
1138   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1139   case ARMISD::VEXT:          return "ARMISD::VEXT";
1140   case ARMISD::VREV64:        return "ARMISD::VREV64";
1141   case ARMISD::VREV32:        return "ARMISD::VREV32";
1142   case ARMISD::VREV16:        return "ARMISD::VREV16";
1143   case ARMISD::VZIP:          return "ARMISD::VZIP";
1144   case ARMISD::VUZP:          return "ARMISD::VUZP";
1145   case ARMISD::VTRN:          return "ARMISD::VTRN";
1146   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1147   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1148   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1149   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1150   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1151   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1152   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1153   case ARMISD::BFI:           return "ARMISD::BFI";
1154   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1155   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1156   case ARMISD::VBSL:          return "ARMISD::VBSL";
1157   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1158   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1159   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1160   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1161   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1162   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1163   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1164   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1165   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1166   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1167   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1168   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1169   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1170   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1171   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1172   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1173   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1174   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1175   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1176   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1177   }
1178   return nullptr;
1179 }
1180
1181 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1182                                           EVT VT) const {
1183   if (!VT.isVector())
1184     return getPointerTy(DL);
1185   return VT.changeVectorElementTypeToInteger();
1186 }
1187
1188 /// getRegClassFor - Return the register class that should be used for the
1189 /// specified value type.
1190 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1191   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1192   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1193   // load / store 4 to 8 consecutive D registers.
1194   if (Subtarget->hasNEON()) {
1195     if (VT == MVT::v4i64)
1196       return &ARM::QQPRRegClass;
1197     if (VT == MVT::v8i64)
1198       return &ARM::QQQQPRRegClass;
1199   }
1200   return TargetLowering::getRegClassFor(VT);
1201 }
1202
1203 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1204 // source/dest is aligned and the copy size is large enough. We therefore want
1205 // to align such objects passed to memory intrinsics.
1206 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1207                                                unsigned &PrefAlign) const {
1208   if (!isa<MemIntrinsic>(CI))
1209     return false;
1210   MinSize = 8;
1211   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1212   // cycle faster than 4-byte aligned LDM.
1213   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1214   return true;
1215 }
1216
1217 // Create a fast isel object.
1218 FastISel *
1219 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1220                                   const TargetLibraryInfo *libInfo) const {
1221   return ARM::createFastISel(funcInfo, libInfo);
1222 }
1223
1224 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1225   unsigned NumVals = N->getNumValues();
1226   if (!NumVals)
1227     return Sched::RegPressure;
1228
1229   for (unsigned i = 0; i != NumVals; ++i) {
1230     EVT VT = N->getValueType(i);
1231     if (VT == MVT::Glue || VT == MVT::Other)
1232       continue;
1233     if (VT.isFloatingPoint() || VT.isVector())
1234       return Sched::ILP;
1235   }
1236
1237   if (!N->isMachineOpcode())
1238     return Sched::RegPressure;
1239
1240   // Load are scheduled for latency even if there instruction itinerary
1241   // is not available.
1242   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1243   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1244
1245   if (MCID.getNumDefs() == 0)
1246     return Sched::RegPressure;
1247   if (!Itins->isEmpty() &&
1248       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1249     return Sched::ILP;
1250
1251   return Sched::RegPressure;
1252 }
1253
1254 //===----------------------------------------------------------------------===//
1255 // Lowering Code
1256 //===----------------------------------------------------------------------===//
1257
1258 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1259 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1260   switch (CC) {
1261   default: llvm_unreachable("Unknown condition code!");
1262   case ISD::SETNE:  return ARMCC::NE;
1263   case ISD::SETEQ:  return ARMCC::EQ;
1264   case ISD::SETGT:  return ARMCC::GT;
1265   case ISD::SETGE:  return ARMCC::GE;
1266   case ISD::SETLT:  return ARMCC::LT;
1267   case ISD::SETLE:  return ARMCC::LE;
1268   case ISD::SETUGT: return ARMCC::HI;
1269   case ISD::SETUGE: return ARMCC::HS;
1270   case ISD::SETULT: return ARMCC::LO;
1271   case ISD::SETULE: return ARMCC::LS;
1272   }
1273 }
1274
1275 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1276 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1277                         ARMCC::CondCodes &CondCode2) {
1278   CondCode2 = ARMCC::AL;
1279   switch (CC) {
1280   default: llvm_unreachable("Unknown FP condition!");
1281   case ISD::SETEQ:
1282   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1283   case ISD::SETGT:
1284   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1285   case ISD::SETGE:
1286   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1287   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1288   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1289   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1290   case ISD::SETO:   CondCode = ARMCC::VC; break;
1291   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1292   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1293   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1294   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1295   case ISD::SETLT:
1296   case ISD::SETULT: CondCode = ARMCC::LT; break;
1297   case ISD::SETLE:
1298   case ISD::SETULE: CondCode = ARMCC::LE; break;
1299   case ISD::SETNE:
1300   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1301   }
1302 }
1303
1304 //===----------------------------------------------------------------------===//
1305 //                      Calling Convention Implementation
1306 //===----------------------------------------------------------------------===//
1307
1308 #include "ARMGenCallingConv.inc"
1309
1310 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1311 /// account presence of floating point hardware and calling convention
1312 /// limitations, such as support for variadic functions.
1313 CallingConv::ID
1314 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1315                                            bool isVarArg) const {
1316   switch (CC) {
1317   default:
1318     llvm_unreachable("Unsupported calling convention");
1319   case CallingConv::ARM_AAPCS:
1320   case CallingConv::ARM_APCS:
1321   case CallingConv::GHC:
1322     return CC;
1323   case CallingConv::ARM_AAPCS_VFP:
1324     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1325   case CallingConv::C:
1326     if (!Subtarget->isAAPCS_ABI())
1327       return CallingConv::ARM_APCS;
1328     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1329              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1330              !isVarArg)
1331       return CallingConv::ARM_AAPCS_VFP;
1332     else
1333       return CallingConv::ARM_AAPCS;
1334   case CallingConv::Fast:
1335     if (!Subtarget->isAAPCS_ABI()) {
1336       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1337         return CallingConv::Fast;
1338       return CallingConv::ARM_APCS;
1339     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1340       return CallingConv::ARM_AAPCS_VFP;
1341     else
1342       return CallingConv::ARM_AAPCS;
1343   }
1344 }
1345
1346 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1347 /// CallingConvention.
1348 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1349                                                  bool Return,
1350                                                  bool isVarArg) const {
1351   switch (getEffectiveCallingConv(CC, isVarArg)) {
1352   default:
1353     llvm_unreachable("Unsupported calling convention");
1354   case CallingConv::ARM_APCS:
1355     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1356   case CallingConv::ARM_AAPCS:
1357     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1358   case CallingConv::ARM_AAPCS_VFP:
1359     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1360   case CallingConv::Fast:
1361     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1362   case CallingConv::GHC:
1363     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1364   }
1365 }
1366
1367 /// LowerCallResult - Lower the result values of a call into the
1368 /// appropriate copies out of appropriate physical registers.
1369 SDValue
1370 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1371                                    CallingConv::ID CallConv, bool isVarArg,
1372                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1373                                    SDLoc dl, SelectionDAG &DAG,
1374                                    SmallVectorImpl<SDValue> &InVals,
1375                                    bool isThisReturn, SDValue ThisVal) const {
1376
1377   // Assign locations to each value returned by this call.
1378   SmallVector<CCValAssign, 16> RVLocs;
1379   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1380                     *DAG.getContext(), Call);
1381   CCInfo.AnalyzeCallResult(Ins,
1382                            CCAssignFnForNode(CallConv, /* Return*/ true,
1383                                              isVarArg));
1384
1385   // Copy all of the result registers out of their specified physreg.
1386   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1387     CCValAssign VA = RVLocs[i];
1388
1389     // Pass 'this' value directly from the argument to return value, to avoid
1390     // reg unit interference
1391     if (i == 0 && isThisReturn) {
1392       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1393              "unexpected return calling convention register assignment");
1394       InVals.push_back(ThisVal);
1395       continue;
1396     }
1397
1398     SDValue Val;
1399     if (VA.needsCustom()) {
1400       // Handle f64 or half of a v2f64.
1401       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1402                                       InFlag);
1403       Chain = Lo.getValue(1);
1404       InFlag = Lo.getValue(2);
1405       VA = RVLocs[++i]; // skip ahead to next loc
1406       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1407                                       InFlag);
1408       Chain = Hi.getValue(1);
1409       InFlag = Hi.getValue(2);
1410       if (!Subtarget->isLittle())
1411         std::swap (Lo, Hi);
1412       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1413
1414       if (VA.getLocVT() == MVT::v2f64) {
1415         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1416         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1417                           DAG.getConstant(0, dl, MVT::i32));
1418
1419         VA = RVLocs[++i]; // skip ahead to next loc
1420         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1421         Chain = Lo.getValue(1);
1422         InFlag = Lo.getValue(2);
1423         VA = RVLocs[++i]; // skip ahead to next loc
1424         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1425         Chain = Hi.getValue(1);
1426         InFlag = Hi.getValue(2);
1427         if (!Subtarget->isLittle())
1428           std::swap (Lo, Hi);
1429         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1430         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1431                           DAG.getConstant(1, dl, MVT::i32));
1432       }
1433     } else {
1434       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1435                                InFlag);
1436       Chain = Val.getValue(1);
1437       InFlag = Val.getValue(2);
1438     }
1439
1440     switch (VA.getLocInfo()) {
1441     default: llvm_unreachable("Unknown loc info!");
1442     case CCValAssign::Full: break;
1443     case CCValAssign::BCvt:
1444       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1445       break;
1446     }
1447
1448     InVals.push_back(Val);
1449   }
1450
1451   return Chain;
1452 }
1453
1454 /// LowerMemOpCallTo - Store the argument to the stack.
1455 SDValue
1456 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1457                                     SDValue StackPtr, SDValue Arg,
1458                                     SDLoc dl, SelectionDAG &DAG,
1459                                     const CCValAssign &VA,
1460                                     ISD::ArgFlagsTy Flags) const {
1461   unsigned LocMemOffset = VA.getLocMemOffset();
1462   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1463   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1464                        StackPtr, PtrOff);
1465   return DAG.getStore(Chain, dl, Arg, PtrOff,
1466                       MachinePointerInfo::getStack(LocMemOffset),
1467                       false, false, 0);
1468 }
1469
1470 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1471                                          SDValue Chain, SDValue &Arg,
1472                                          RegsToPassVector &RegsToPass,
1473                                          CCValAssign &VA, CCValAssign &NextVA,
1474                                          SDValue &StackPtr,
1475                                          SmallVectorImpl<SDValue> &MemOpChains,
1476                                          ISD::ArgFlagsTy Flags) const {
1477
1478   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1479                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1480   unsigned id = Subtarget->isLittle() ? 0 : 1;
1481   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1482
1483   if (NextVA.isRegLoc())
1484     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1485   else {
1486     assert(NextVA.isMemLoc());
1487     if (!StackPtr.getNode())
1488       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1489                                     getPointerTy(DAG.getDataLayout()));
1490
1491     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1492                                            dl, DAG, NextVA,
1493                                            Flags));
1494   }
1495 }
1496
1497 /// LowerCall - Lowering a call into a callseq_start <-
1498 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1499 /// nodes.
1500 SDValue
1501 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1502                              SmallVectorImpl<SDValue> &InVals) const {
1503   SelectionDAG &DAG                     = CLI.DAG;
1504   SDLoc &dl                             = CLI.DL;
1505   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1506   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1507   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1508   SDValue Chain                         = CLI.Chain;
1509   SDValue Callee                        = CLI.Callee;
1510   bool &isTailCall                      = CLI.IsTailCall;
1511   CallingConv::ID CallConv              = CLI.CallConv;
1512   bool doesNotRet                       = CLI.DoesNotReturn;
1513   bool isVarArg                         = CLI.IsVarArg;
1514
1515   MachineFunction &MF = DAG.getMachineFunction();
1516   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1517   bool isThisReturn   = false;
1518   bool isSibCall      = false;
1519   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1520
1521   // Disable tail calls if they're not supported.
1522   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1523     isTailCall = false;
1524
1525   if (isTailCall) {
1526     // Check if it's really possible to do a tail call.
1527     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1528                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1529                                                    Outs, OutVals, Ins, DAG);
1530     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1531       report_fatal_error("failed to perform tail call elimination on a call "
1532                          "site marked musttail");
1533     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1534     // detected sibcalls.
1535     if (isTailCall) {
1536       ++NumTailCalls;
1537       isSibCall = true;
1538     }
1539   }
1540
1541   // Analyze operands of the call, assigning locations to each operand.
1542   SmallVector<CCValAssign, 16> ArgLocs;
1543   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1544                     *DAG.getContext(), Call);
1545   CCInfo.AnalyzeCallOperands(Outs,
1546                              CCAssignFnForNode(CallConv, /* Return*/ false,
1547                                                isVarArg));
1548
1549   // Get a count of how many bytes are to be pushed on the stack.
1550   unsigned NumBytes = CCInfo.getNextStackOffset();
1551
1552   // For tail calls, memory operands are available in our caller's stack.
1553   if (isSibCall)
1554     NumBytes = 0;
1555
1556   // Adjust the stack pointer for the new arguments...
1557   // These operations are automatically eliminated by the prolog/epilog pass
1558   if (!isSibCall)
1559     Chain = DAG.getCALLSEQ_START(Chain,
1560                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1561
1562   SDValue StackPtr =
1563       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1564
1565   RegsToPassVector RegsToPass;
1566   SmallVector<SDValue, 8> MemOpChains;
1567
1568   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1569   // of tail call optimization, arguments are handled later.
1570   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1571        i != e;
1572        ++i, ++realArgIdx) {
1573     CCValAssign &VA = ArgLocs[i];
1574     SDValue Arg = OutVals[realArgIdx];
1575     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1576     bool isByVal = Flags.isByVal();
1577
1578     // Promote the value if needed.
1579     switch (VA.getLocInfo()) {
1580     default: llvm_unreachable("Unknown loc info!");
1581     case CCValAssign::Full: break;
1582     case CCValAssign::SExt:
1583       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1584       break;
1585     case CCValAssign::ZExt:
1586       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1587       break;
1588     case CCValAssign::AExt:
1589       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1590       break;
1591     case CCValAssign::BCvt:
1592       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1593       break;
1594     }
1595
1596     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1597     if (VA.needsCustom()) {
1598       if (VA.getLocVT() == MVT::v2f64) {
1599         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1600                                   DAG.getConstant(0, dl, MVT::i32));
1601         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1602                                   DAG.getConstant(1, dl, MVT::i32));
1603
1604         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1605                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1606
1607         VA = ArgLocs[++i]; // skip ahead to next loc
1608         if (VA.isRegLoc()) {
1609           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1610                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1611         } else {
1612           assert(VA.isMemLoc());
1613
1614           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1615                                                  dl, DAG, VA, Flags));
1616         }
1617       } else {
1618         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1619                          StackPtr, MemOpChains, Flags);
1620       }
1621     } else if (VA.isRegLoc()) {
1622       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1623         assert(VA.getLocVT() == MVT::i32 &&
1624                "unexpected calling convention register assignment");
1625         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1626                "unexpected use of 'returned'");
1627         isThisReturn = true;
1628       }
1629       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1630     } else if (isByVal) {
1631       assert(VA.isMemLoc());
1632       unsigned offset = 0;
1633
1634       // True if this byval aggregate will be split between registers
1635       // and memory.
1636       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1637       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1638
1639       if (CurByValIdx < ByValArgsCount) {
1640
1641         unsigned RegBegin, RegEnd;
1642         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1643
1644         EVT PtrVT =
1645             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1646         unsigned int i, j;
1647         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1648           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1649           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1650           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1651                                      MachinePointerInfo(),
1652                                      false, false, false,
1653                                      DAG.InferPtrAlignment(AddArg));
1654           MemOpChains.push_back(Load.getValue(1));
1655           RegsToPass.push_back(std::make_pair(j, Load));
1656         }
1657
1658         // If parameter size outsides register area, "offset" value
1659         // helps us to calculate stack slot for remained part properly.
1660         offset = RegEnd - RegBegin;
1661
1662         CCInfo.nextInRegsParam();
1663       }
1664
1665       if (Flags.getByValSize() > 4*offset) {
1666         auto PtrVT = getPointerTy(DAG.getDataLayout());
1667         unsigned LocMemOffset = VA.getLocMemOffset();
1668         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1669         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1670         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1671         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1672         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1673                                            MVT::i32);
1674         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1675                                             MVT::i32);
1676
1677         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1678         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1679         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1680                                           Ops));
1681       }
1682     } else if (!isSibCall) {
1683       assert(VA.isMemLoc());
1684
1685       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1686                                              dl, DAG, VA, Flags));
1687     }
1688   }
1689
1690   if (!MemOpChains.empty())
1691     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1692
1693   // Build a sequence of copy-to-reg nodes chained together with token chain
1694   // and flag operands which copy the outgoing args into the appropriate regs.
1695   SDValue InFlag;
1696   // Tail call byval lowering might overwrite argument registers so in case of
1697   // tail call optimization the copies to registers are lowered later.
1698   if (!isTailCall)
1699     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1700       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1701                                RegsToPass[i].second, InFlag);
1702       InFlag = Chain.getValue(1);
1703     }
1704
1705   // For tail calls lower the arguments to the 'real' stack slot.
1706   if (isTailCall) {
1707     // Force all the incoming stack arguments to be loaded from the stack
1708     // before any new outgoing arguments are stored to the stack, because the
1709     // outgoing stack slots may alias the incoming argument stack slots, and
1710     // the alias isn't otherwise explicit. This is slightly more conservative
1711     // than necessary, because it means that each store effectively depends
1712     // on every argument instead of just those arguments it would clobber.
1713
1714     // Do not flag preceding copytoreg stuff together with the following stuff.
1715     InFlag = SDValue();
1716     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1717       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1718                                RegsToPass[i].second, InFlag);
1719       InFlag = Chain.getValue(1);
1720     }
1721     InFlag = SDValue();
1722   }
1723
1724   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1725   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1726   // node so that legalize doesn't hack it.
1727   bool isDirect = false;
1728   bool isARMFunc = false;
1729   bool isLocalARMFunc = false;
1730   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1731   auto PtrVt = getPointerTy(DAG.getDataLayout());
1732
1733   if (Subtarget->genLongCalls()) {
1734     assert((Subtarget->isTargetWindows() ||
1735             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1736            "long-calls with non-static relocation model!");
1737     // Handle a global address or an external symbol. If it's not one of
1738     // those, the target's already in a register, so we don't need to do
1739     // anything extra.
1740     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1741       const GlobalValue *GV = G->getGlobal();
1742       // Create a constant pool entry for the callee address
1743       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1744       ARMConstantPoolValue *CPV =
1745         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1746
1747       // Get the address of the callee into a register
1748       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1749       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1750       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1751                            MachinePointerInfo::getConstantPool(), false, false,
1752                            false, 0);
1753     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1754       const char *Sym = S->getSymbol();
1755
1756       // Create a constant pool entry for the callee address
1757       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1758       ARMConstantPoolValue *CPV =
1759         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1760                                       ARMPCLabelIndex, 0);
1761       // Get the address of the callee into a register
1762       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1763       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1764       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1765                            MachinePointerInfo::getConstantPool(), false, false,
1766                            false, 0);
1767     }
1768   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1769     const GlobalValue *GV = G->getGlobal();
1770     isDirect = true;
1771     bool isDef = GV->isStrongDefinitionForLinker();
1772     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1773                    getTargetMachine().getRelocationModel() != Reloc::Static;
1774     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1775     // ARM call to a local ARM function is predicable.
1776     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1777     // tBX takes a register source operand.
1778     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1779       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1780       Callee = DAG.getNode(
1781           ARMISD::WrapperPIC, dl, PtrVt,
1782           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1783       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1784                            MachinePointerInfo::getGOT(), false, false, true, 0);
1785     } else if (Subtarget->isTargetCOFF()) {
1786       assert(Subtarget->isTargetWindows() &&
1787              "Windows is the only supported COFF target");
1788       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1789                                  ? ARMII::MO_DLLIMPORT
1790                                  : ARMII::MO_NO_FLAG;
1791       Callee =
1792           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1793       if (GV->hasDLLImportStorageClass())
1794         Callee =
1795             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1796                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1797                         MachinePointerInfo::getGOT(), false, false, false, 0);
1798     } else {
1799       // On ELF targets for PIC code, direct calls should go through the PLT
1800       unsigned OpFlags = 0;
1801       if (Subtarget->isTargetELF() &&
1802           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1803         OpFlags = ARMII::MO_PLT;
1804       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1805     }
1806   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1807     isDirect = true;
1808     bool isStub = Subtarget->isTargetMachO() &&
1809                   getTargetMachine().getRelocationModel() != Reloc::Static;
1810     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1811     // tBX takes a register source operand.
1812     const char *Sym = S->getSymbol();
1813     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1814       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1815       ARMConstantPoolValue *CPV =
1816         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1817                                       ARMPCLabelIndex, 4);
1818       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1819       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1820       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1821                            MachinePointerInfo::getConstantPool(), false, false,
1822                            false, 0);
1823       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1824       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1825     } else {
1826       unsigned OpFlags = 0;
1827       // On ELF targets for PIC code, direct calls should go through the PLT
1828       if (Subtarget->isTargetELF() &&
1829                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1830         OpFlags = ARMII::MO_PLT;
1831       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1832     }
1833   }
1834
1835   // FIXME: handle tail calls differently.
1836   unsigned CallOpc;
1837   if (Subtarget->isThumb()) {
1838     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1839       CallOpc = ARMISD::CALL_NOLINK;
1840     else
1841       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1842   } else {
1843     if (!isDirect && !Subtarget->hasV5TOps())
1844       CallOpc = ARMISD::CALL_NOLINK;
1845     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1846              // Emit regular call when code size is the priority
1847              !MF.getFunction()->optForMinSize())
1848       // "mov lr, pc; b _foo" to avoid confusing the RSP
1849       CallOpc = ARMISD::CALL_NOLINK;
1850     else
1851       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1852   }
1853
1854   std::vector<SDValue> Ops;
1855   Ops.push_back(Chain);
1856   Ops.push_back(Callee);
1857
1858   // Add argument registers to the end of the list so that they are known live
1859   // into the call.
1860   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1861     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1862                                   RegsToPass[i].second.getValueType()));
1863
1864   // Add a register mask operand representing the call-preserved registers.
1865   if (!isTailCall) {
1866     const uint32_t *Mask;
1867     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1868     if (isThisReturn) {
1869       // For 'this' returns, use the R0-preserving mask if applicable
1870       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1871       if (!Mask) {
1872         // Set isThisReturn to false if the calling convention is not one that
1873         // allows 'returned' to be modeled in this way, so LowerCallResult does
1874         // not try to pass 'this' straight through
1875         isThisReturn = false;
1876         Mask = ARI->getCallPreservedMask(MF, CallConv);
1877       }
1878     } else
1879       Mask = ARI->getCallPreservedMask(MF, CallConv);
1880
1881     assert(Mask && "Missing call preserved mask for calling convention");
1882     Ops.push_back(DAG.getRegisterMask(Mask));
1883   }
1884
1885   if (InFlag.getNode())
1886     Ops.push_back(InFlag);
1887
1888   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1889   if (isTailCall) {
1890     MF.getFrameInfo()->setHasTailCall();
1891     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1892   }
1893
1894   // Returns a chain and a flag for retval copy to use.
1895   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1896   InFlag = Chain.getValue(1);
1897
1898   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1899                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1900   if (!Ins.empty())
1901     InFlag = Chain.getValue(1);
1902
1903   // Handle result values, copying them out of physregs into vregs that we
1904   // return.
1905   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1906                          InVals, isThisReturn,
1907                          isThisReturn ? OutVals[0] : SDValue());
1908 }
1909
1910 /// HandleByVal - Every parameter *after* a byval parameter is passed
1911 /// on the stack.  Remember the next parameter register to allocate,
1912 /// and then confiscate the rest of the parameter registers to insure
1913 /// this.
1914 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1915                                     unsigned Align) const {
1916   assert((State->getCallOrPrologue() == Prologue ||
1917           State->getCallOrPrologue() == Call) &&
1918          "unhandled ParmContext");
1919
1920   // Byval (as with any stack) slots are always at least 4 byte aligned.
1921   Align = std::max(Align, 4U);
1922
1923   unsigned Reg = State->AllocateReg(GPRArgRegs);
1924   if (!Reg)
1925     return;
1926
1927   unsigned AlignInRegs = Align / 4;
1928   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1929   for (unsigned i = 0; i < Waste; ++i)
1930     Reg = State->AllocateReg(GPRArgRegs);
1931
1932   if (!Reg)
1933     return;
1934
1935   unsigned Excess = 4 * (ARM::R4 - Reg);
1936
1937   // Special case when NSAA != SP and parameter size greater than size of
1938   // all remained GPR regs. In that case we can't split parameter, we must
1939   // send it to stack. We also must set NCRN to R4, so waste all
1940   // remained registers.
1941   const unsigned NSAAOffset = State->getNextStackOffset();
1942   if (NSAAOffset != 0 && Size > Excess) {
1943     while (State->AllocateReg(GPRArgRegs))
1944       ;
1945     return;
1946   }
1947
1948   // First register for byval parameter is the first register that wasn't
1949   // allocated before this method call, so it would be "reg".
1950   // If parameter is small enough to be saved in range [reg, r4), then
1951   // the end (first after last) register would be reg + param-size-in-regs,
1952   // else parameter would be splitted between registers and stack,
1953   // end register would be r4 in this case.
1954   unsigned ByValRegBegin = Reg;
1955   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1956   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1957   // Note, first register is allocated in the beginning of function already,
1958   // allocate remained amount of registers we need.
1959   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1960     State->AllocateReg(GPRArgRegs);
1961   // A byval parameter that is split between registers and memory needs its
1962   // size truncated here.
1963   // In the case where the entire structure fits in registers, we set the
1964   // size in memory to zero.
1965   Size = std::max<int>(Size - Excess, 0);
1966 }
1967
1968 /// MatchingStackOffset - Return true if the given stack call argument is
1969 /// already available in the same position (relatively) of the caller's
1970 /// incoming argument stack.
1971 static
1972 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1973                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1974                          const TargetInstrInfo *TII) {
1975   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1976   int FI = INT_MAX;
1977   if (Arg.getOpcode() == ISD::CopyFromReg) {
1978     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1979     if (!TargetRegisterInfo::isVirtualRegister(VR))
1980       return false;
1981     MachineInstr *Def = MRI->getVRegDef(VR);
1982     if (!Def)
1983       return false;
1984     if (!Flags.isByVal()) {
1985       if (!TII->isLoadFromStackSlot(Def, FI))
1986         return false;
1987     } else {
1988       return false;
1989     }
1990   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1991     if (Flags.isByVal())
1992       // ByVal argument is passed in as a pointer but it's now being
1993       // dereferenced. e.g.
1994       // define @foo(%struct.X* %A) {
1995       //   tail call @bar(%struct.X* byval %A)
1996       // }
1997       return false;
1998     SDValue Ptr = Ld->getBasePtr();
1999     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2000     if (!FINode)
2001       return false;
2002     FI = FINode->getIndex();
2003   } else
2004     return false;
2005
2006   assert(FI != INT_MAX);
2007   if (!MFI->isFixedObjectIndex(FI))
2008     return false;
2009   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2010 }
2011
2012 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2013 /// for tail call optimization. Targets which want to do tail call
2014 /// optimization should implement this function.
2015 bool
2016 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2017                                                      CallingConv::ID CalleeCC,
2018                                                      bool isVarArg,
2019                                                      bool isCalleeStructRet,
2020                                                      bool isCallerStructRet,
2021                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2022                                     const SmallVectorImpl<SDValue> &OutVals,
2023                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2024                                                      SelectionDAG& DAG) const {
2025   const Function *CallerF = DAG.getMachineFunction().getFunction();
2026   CallingConv::ID CallerCC = CallerF->getCallingConv();
2027   bool CCMatch = CallerCC == CalleeCC;
2028
2029   // Look for obvious safe cases to perform tail call optimization that do not
2030   // require ABI changes. This is what gcc calls sibcall.
2031
2032   // Do not sibcall optimize vararg calls unless the call site is not passing
2033   // any arguments.
2034   if (isVarArg && !Outs.empty())
2035     return false;
2036
2037   // Exception-handling functions need a special set of instructions to indicate
2038   // a return to the hardware. Tail-calling another function would probably
2039   // break this.
2040   if (CallerF->hasFnAttribute("interrupt"))
2041     return false;
2042
2043   // Also avoid sibcall optimization if either caller or callee uses struct
2044   // return semantics.
2045   if (isCalleeStructRet || isCallerStructRet)
2046     return false;
2047
2048   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2049   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2050   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2051   // support in the assembler and linker to be used. This would need to be
2052   // fixed to fully support tail calls in Thumb1.
2053   //
2054   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2055   // LR.  This means if we need to reload LR, it takes an extra instructions,
2056   // which outweighs the value of the tail call; but here we don't know yet
2057   // whether LR is going to be used.  Probably the right approach is to
2058   // generate the tail call here and turn it back into CALL/RET in
2059   // emitEpilogue if LR is used.
2060
2061   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2062   // but we need to make sure there are enough registers; the only valid
2063   // registers are the 4 used for parameters.  We don't currently do this
2064   // case.
2065   if (Subtarget->isThumb1Only())
2066     return false;
2067
2068   // Externally-defined functions with weak linkage should not be
2069   // tail-called on ARM when the OS does not support dynamic
2070   // pre-emption of symbols, as the AAELF spec requires normal calls
2071   // to undefined weak functions to be replaced with a NOP or jump to the
2072   // next instruction. The behaviour of branch instructions in this
2073   // situation (as used for tail calls) is implementation-defined, so we
2074   // cannot rely on the linker replacing the tail call with a return.
2075   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2076     const GlobalValue *GV = G->getGlobal();
2077     const Triple &TT = getTargetMachine().getTargetTriple();
2078     if (GV->hasExternalWeakLinkage() &&
2079         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2080       return false;
2081   }
2082
2083   // If the calling conventions do not match, then we'd better make sure the
2084   // results are returned in the same way as what the caller expects.
2085   if (!CCMatch) {
2086     SmallVector<CCValAssign, 16> RVLocs1;
2087     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2088                        *DAG.getContext(), Call);
2089     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2090
2091     SmallVector<CCValAssign, 16> RVLocs2;
2092     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2093                        *DAG.getContext(), Call);
2094     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2095
2096     if (RVLocs1.size() != RVLocs2.size())
2097       return false;
2098     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2099       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2100         return false;
2101       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2102         return false;
2103       if (RVLocs1[i].isRegLoc()) {
2104         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2105           return false;
2106       } else {
2107         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2108           return false;
2109       }
2110     }
2111   }
2112
2113   // If Caller's vararg or byval argument has been split between registers and
2114   // stack, do not perform tail call, since part of the argument is in caller's
2115   // local frame.
2116   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2117                                       getInfo<ARMFunctionInfo>();
2118   if (AFI_Caller->getArgRegsSaveSize())
2119     return false;
2120
2121   // If the callee takes no arguments then go on to check the results of the
2122   // call.
2123   if (!Outs.empty()) {
2124     // Check if stack adjustment is needed. For now, do not do this if any
2125     // argument is passed on the stack.
2126     SmallVector<CCValAssign, 16> ArgLocs;
2127     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2128                       *DAG.getContext(), Call);
2129     CCInfo.AnalyzeCallOperands(Outs,
2130                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2131     if (CCInfo.getNextStackOffset()) {
2132       MachineFunction &MF = DAG.getMachineFunction();
2133
2134       // Check if the arguments are already laid out in the right way as
2135       // the caller's fixed stack objects.
2136       MachineFrameInfo *MFI = MF.getFrameInfo();
2137       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2138       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2139       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2140            i != e;
2141            ++i, ++realArgIdx) {
2142         CCValAssign &VA = ArgLocs[i];
2143         EVT RegVT = VA.getLocVT();
2144         SDValue Arg = OutVals[realArgIdx];
2145         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2146         if (VA.getLocInfo() == CCValAssign::Indirect)
2147           return false;
2148         if (VA.needsCustom()) {
2149           // f64 and vector types are split into multiple registers or
2150           // register/stack-slot combinations.  The types will not match
2151           // the registers; give up on memory f64 refs until we figure
2152           // out what to do about this.
2153           if (!VA.isRegLoc())
2154             return false;
2155           if (!ArgLocs[++i].isRegLoc())
2156             return false;
2157           if (RegVT == MVT::v2f64) {
2158             if (!ArgLocs[++i].isRegLoc())
2159               return false;
2160             if (!ArgLocs[++i].isRegLoc())
2161               return false;
2162           }
2163         } else if (!VA.isRegLoc()) {
2164           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2165                                    MFI, MRI, TII))
2166             return false;
2167         }
2168       }
2169     }
2170   }
2171
2172   return true;
2173 }
2174
2175 bool
2176 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2177                                   MachineFunction &MF, bool isVarArg,
2178                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2179                                   LLVMContext &Context) const {
2180   SmallVector<CCValAssign, 16> RVLocs;
2181   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2182   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2183                                                     isVarArg));
2184 }
2185
2186 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2187                                     SDLoc DL, SelectionDAG &DAG) {
2188   const MachineFunction &MF = DAG.getMachineFunction();
2189   const Function *F = MF.getFunction();
2190
2191   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2192
2193   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2194   // version of the "preferred return address". These offsets affect the return
2195   // instruction if this is a return from PL1 without hypervisor extensions.
2196   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2197   //    SWI:     0      "subs pc, lr, #0"
2198   //    ABORT:   +4     "subs pc, lr, #4"
2199   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2200   // UNDEF varies depending on where the exception came from ARM or Thumb
2201   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2202
2203   int64_t LROffset;
2204   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2205       IntKind == "ABORT")
2206     LROffset = 4;
2207   else if (IntKind == "SWI" || IntKind == "UNDEF")
2208     LROffset = 0;
2209   else
2210     report_fatal_error("Unsupported interrupt attribute. If present, value "
2211                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2212
2213   RetOps.insert(RetOps.begin() + 1,
2214                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2215
2216   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2217 }
2218
2219 SDValue
2220 ARMTargetLowering::LowerReturn(SDValue Chain,
2221                                CallingConv::ID CallConv, bool isVarArg,
2222                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2223                                const SmallVectorImpl<SDValue> &OutVals,
2224                                SDLoc dl, SelectionDAG &DAG) const {
2225
2226   // CCValAssign - represent the assignment of the return value to a location.
2227   SmallVector<CCValAssign, 16> RVLocs;
2228
2229   // CCState - Info about the registers and stack slots.
2230   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2231                     *DAG.getContext(), Call);
2232
2233   // Analyze outgoing return values.
2234   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2235                                                isVarArg));
2236
2237   SDValue Flag;
2238   SmallVector<SDValue, 4> RetOps;
2239   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2240   bool isLittleEndian = Subtarget->isLittle();
2241
2242   MachineFunction &MF = DAG.getMachineFunction();
2243   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2244   AFI->setReturnRegsCount(RVLocs.size());
2245
2246   // Copy the result values into the output registers.
2247   for (unsigned i = 0, realRVLocIdx = 0;
2248        i != RVLocs.size();
2249        ++i, ++realRVLocIdx) {
2250     CCValAssign &VA = RVLocs[i];
2251     assert(VA.isRegLoc() && "Can only return in registers!");
2252
2253     SDValue Arg = OutVals[realRVLocIdx];
2254
2255     switch (VA.getLocInfo()) {
2256     default: llvm_unreachable("Unknown loc info!");
2257     case CCValAssign::Full: break;
2258     case CCValAssign::BCvt:
2259       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2260       break;
2261     }
2262
2263     if (VA.needsCustom()) {
2264       if (VA.getLocVT() == MVT::v2f64) {
2265         // Extract the first half and return it in two registers.
2266         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2267                                    DAG.getConstant(0, dl, MVT::i32));
2268         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2269                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2270
2271         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2272                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2273                                  Flag);
2274         Flag = Chain.getValue(1);
2275         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2276         VA = RVLocs[++i]; // skip ahead to next loc
2277         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2278                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2279                                  Flag);
2280         Flag = Chain.getValue(1);
2281         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2282         VA = RVLocs[++i]; // skip ahead to next loc
2283
2284         // Extract the 2nd half and fall through to handle it as an f64 value.
2285         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2286                           DAG.getConstant(1, dl, MVT::i32));
2287       }
2288       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2289       // available.
2290       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2291                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2292       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2293                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2294                                Flag);
2295       Flag = Chain.getValue(1);
2296       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2297       VA = RVLocs[++i]; // skip ahead to next loc
2298       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2299                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2300                                Flag);
2301     } else
2302       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2303
2304     // Guarantee that all emitted copies are
2305     // stuck together, avoiding something bad.
2306     Flag = Chain.getValue(1);
2307     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2308   }
2309
2310   // Update chain and glue.
2311   RetOps[0] = Chain;
2312   if (Flag.getNode())
2313     RetOps.push_back(Flag);
2314
2315   // CPUs which aren't M-class use a special sequence to return from
2316   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2317   // though we use "subs pc, lr, #N").
2318   //
2319   // M-class CPUs actually use a normal return sequence with a special
2320   // (hardware-provided) value in LR, so the normal code path works.
2321   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2322       !Subtarget->isMClass()) {
2323     if (Subtarget->isThumb1Only())
2324       report_fatal_error("interrupt attribute is not supported in Thumb1");
2325     return LowerInterruptReturn(RetOps, dl, DAG);
2326   }
2327
2328   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2329 }
2330
2331 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2332   if (N->getNumValues() != 1)
2333     return false;
2334   if (!N->hasNUsesOfValue(1, 0))
2335     return false;
2336
2337   SDValue TCChain = Chain;
2338   SDNode *Copy = *N->use_begin();
2339   if (Copy->getOpcode() == ISD::CopyToReg) {
2340     // If the copy has a glue operand, we conservatively assume it isn't safe to
2341     // perform a tail call.
2342     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2343       return false;
2344     TCChain = Copy->getOperand(0);
2345   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2346     SDNode *VMov = Copy;
2347     // f64 returned in a pair of GPRs.
2348     SmallPtrSet<SDNode*, 2> Copies;
2349     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2350          UI != UE; ++UI) {
2351       if (UI->getOpcode() != ISD::CopyToReg)
2352         return false;
2353       Copies.insert(*UI);
2354     }
2355     if (Copies.size() > 2)
2356       return false;
2357
2358     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2359          UI != UE; ++UI) {
2360       SDValue UseChain = UI->getOperand(0);
2361       if (Copies.count(UseChain.getNode()))
2362         // Second CopyToReg
2363         Copy = *UI;
2364       else {
2365         // We are at the top of this chain.
2366         // If the copy has a glue operand, we conservatively assume it
2367         // isn't safe to perform a tail call.
2368         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2369           return false;
2370         // First CopyToReg
2371         TCChain = UseChain;
2372       }
2373     }
2374   } else if (Copy->getOpcode() == ISD::BITCAST) {
2375     // f32 returned in a single GPR.
2376     if (!Copy->hasOneUse())
2377       return false;
2378     Copy = *Copy->use_begin();
2379     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2380       return false;
2381     // If the copy has a glue operand, we conservatively assume it isn't safe to
2382     // perform a tail call.
2383     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2384       return false;
2385     TCChain = Copy->getOperand(0);
2386   } else {
2387     return false;
2388   }
2389
2390   bool HasRet = false;
2391   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2392        UI != UE; ++UI) {
2393     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2394         UI->getOpcode() != ARMISD::INTRET_FLAG)
2395       return false;
2396     HasRet = true;
2397   }
2398
2399   if (!HasRet)
2400     return false;
2401
2402   Chain = TCChain;
2403   return true;
2404 }
2405
2406 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2407   if (!Subtarget->supportsTailCall())
2408     return false;
2409
2410   auto Attr =
2411       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2412   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2413     return false;
2414
2415   return !Subtarget->isThumb1Only();
2416 }
2417
2418 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2419 // and pass the lower and high parts through.
2420 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2421   SDLoc DL(Op);
2422   SDValue WriteValue = Op->getOperand(2);
2423
2424   // This function is only supposed to be called for i64 type argument.
2425   assert(WriteValue.getValueType() == MVT::i64
2426           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2427
2428   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2429                            DAG.getConstant(0, DL, MVT::i32));
2430   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2431                            DAG.getConstant(1, DL, MVT::i32));
2432   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2433   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2434 }
2435
2436 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2437 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2438 // one of the above mentioned nodes. It has to be wrapped because otherwise
2439 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2440 // be used to form addressing mode. These wrapped nodes will be selected
2441 // into MOVi.
2442 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2443   EVT PtrVT = Op.getValueType();
2444   // FIXME there is no actual debug info here
2445   SDLoc dl(Op);
2446   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2447   SDValue Res;
2448   if (CP->isMachineConstantPoolEntry())
2449     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2450                                     CP->getAlignment());
2451   else
2452     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2453                                     CP->getAlignment());
2454   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2455 }
2456
2457 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2458   return MachineJumpTableInfo::EK_Inline;
2459 }
2460
2461 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2462                                              SelectionDAG &DAG) const {
2463   MachineFunction &MF = DAG.getMachineFunction();
2464   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2465   unsigned ARMPCLabelIndex = 0;
2466   SDLoc DL(Op);
2467   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2468   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2469   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2470   SDValue CPAddr;
2471   if (RelocM == Reloc::Static) {
2472     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2473   } else {
2474     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2475     ARMPCLabelIndex = AFI->createPICLabelUId();
2476     ARMConstantPoolValue *CPV =
2477       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2478                                       ARMCP::CPBlockAddress, PCAdj);
2479     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2480   }
2481   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2482   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2483                                MachinePointerInfo::getConstantPool(),
2484                                false, false, false, 0);
2485   if (RelocM == Reloc::Static)
2486     return Result;
2487   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2488   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2489 }
2490
2491 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2492 SDValue
2493 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2494                                                  SelectionDAG &DAG) const {
2495   SDLoc dl(GA);
2496   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2497   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2498   MachineFunction &MF = DAG.getMachineFunction();
2499   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2500   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2501   ARMConstantPoolValue *CPV =
2502     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2503                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2504   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2505   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2506   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2507                          MachinePointerInfo::getConstantPool(),
2508                          false, false, false, 0);
2509   SDValue Chain = Argument.getValue(1);
2510
2511   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2512   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2513
2514   // call __tls_get_addr.
2515   ArgListTy Args;
2516   ArgListEntry Entry;
2517   Entry.Node = Argument;
2518   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2519   Args.push_back(Entry);
2520
2521   // FIXME: is there useful debug info available here?
2522   TargetLowering::CallLoweringInfo CLI(DAG);
2523   CLI.setDebugLoc(dl).setChain(Chain)
2524     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2525                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2526                0);
2527
2528   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2529   return CallResult.first;
2530 }
2531
2532 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2533 // "local exec" model.
2534 SDValue
2535 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2536                                         SelectionDAG &DAG,
2537                                         TLSModel::Model model) const {
2538   const GlobalValue *GV = GA->getGlobal();
2539   SDLoc dl(GA);
2540   SDValue Offset;
2541   SDValue Chain = DAG.getEntryNode();
2542   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2543   // Get the Thread Pointer
2544   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2545
2546   if (model == TLSModel::InitialExec) {
2547     MachineFunction &MF = DAG.getMachineFunction();
2548     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2549     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2550     // Initial exec model.
2551     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2552     ARMConstantPoolValue *CPV =
2553       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2554                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2555                                       true);
2556     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2557     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2558     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2559                          MachinePointerInfo::getConstantPool(),
2560                          false, false, false, 0);
2561     Chain = Offset.getValue(1);
2562
2563     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2564     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2565
2566     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2567                          MachinePointerInfo::getConstantPool(),
2568                          false, false, false, 0);
2569   } else {
2570     // local exec model
2571     assert(model == TLSModel::LocalExec);
2572     ARMConstantPoolValue *CPV =
2573       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2574     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2575     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2576     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2577                          MachinePointerInfo::getConstantPool(),
2578                          false, false, false, 0);
2579   }
2580
2581   // The address of the thread local variable is the add of the thread
2582   // pointer with the offset of the variable.
2583   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2584 }
2585
2586 SDValue
2587 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2588   // TODO: implement the "local dynamic" model
2589   assert(Subtarget->isTargetELF() &&
2590          "TLS not implemented for non-ELF targets");
2591   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2592   if (DAG.getTarget().Options.EmulatedTLS)
2593     return LowerToTLSEmulatedModel(GA, DAG);
2594
2595   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2596
2597   switch (model) {
2598     case TLSModel::GeneralDynamic:
2599     case TLSModel::LocalDynamic:
2600       return LowerToTLSGeneralDynamicModel(GA, DAG);
2601     case TLSModel::InitialExec:
2602     case TLSModel::LocalExec:
2603       return LowerToTLSExecModels(GA, DAG, model);
2604   }
2605   llvm_unreachable("bogus TLS model");
2606 }
2607
2608 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2609                                                  SelectionDAG &DAG) const {
2610   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2611   SDLoc dl(Op);
2612   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2613   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2614     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2615     ARMConstantPoolValue *CPV =
2616       ARMConstantPoolConstant::Create(GV,
2617                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2618     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2619     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2620     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2621                                  CPAddr,
2622                                  MachinePointerInfo::getConstantPool(),
2623                                  false, false, false, 0);
2624     SDValue Chain = Result.getValue(1);
2625     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2626     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2627     if (!UseGOTOFF)
2628       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2629                            MachinePointerInfo::getGOT(),
2630                            false, false, false, 0);
2631     return Result;
2632   }
2633
2634   // If we have T2 ops, we can materialize the address directly via movt/movw
2635   // pair. This is always cheaper.
2636   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2637     ++NumMovwMovt;
2638     // FIXME: Once remat is capable of dealing with instructions with register
2639     // operands, expand this into two nodes.
2640     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2641                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2642   } else {
2643     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2644     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2645     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2646                        MachinePointerInfo::getConstantPool(),
2647                        false, false, false, 0);
2648   }
2649 }
2650
2651 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2652                                                     SelectionDAG &DAG) const {
2653   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2654   SDLoc dl(Op);
2655   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2656   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2657
2658   if (Subtarget->useMovt(DAG.getMachineFunction()))
2659     ++NumMovwMovt;
2660
2661   // FIXME: Once remat is capable of dealing with instructions with register
2662   // operands, expand this into multiple nodes
2663   unsigned Wrapper =
2664       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2665
2666   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2667   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2668
2669   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2670     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2671                          MachinePointerInfo::getGOT(), false, false, false, 0);
2672   return Result;
2673 }
2674
2675 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2676                                                      SelectionDAG &DAG) const {
2677   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2678   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2679          "Windows on ARM expects to use movw/movt");
2680
2681   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2682   const ARMII::TOF TargetFlags =
2683     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2684   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2685   SDValue Result;
2686   SDLoc DL(Op);
2687
2688   ++NumMovwMovt;
2689
2690   // FIXME: Once remat is capable of dealing with instructions with register
2691   // operands, expand this into two nodes.
2692   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2693                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2694                                                   TargetFlags));
2695   if (GV->hasDLLImportStorageClass())
2696     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2697                          MachinePointerInfo::getGOT(), false, false, false, 0);
2698   return Result;
2699 }
2700
2701 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2702                                                     SelectionDAG &DAG) const {
2703   assert(Subtarget->isTargetELF() &&
2704          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2705   MachineFunction &MF = DAG.getMachineFunction();
2706   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2707   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2708   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2709   SDLoc dl(Op);
2710   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2711   ARMConstantPoolValue *CPV =
2712     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2713                                   ARMPCLabelIndex, PCAdj);
2714   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2715   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2716   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2717                                MachinePointerInfo::getConstantPool(),
2718                                false, false, false, 0);
2719   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2720   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2721 }
2722
2723 SDValue
2724 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2725   SDLoc dl(Op);
2726   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2727   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2728                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2729                      Op.getOperand(1), Val);
2730 }
2731
2732 SDValue
2733 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2734   SDLoc dl(Op);
2735   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2736                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2737 }
2738
2739 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2740                                                       SelectionDAG &DAG) const {
2741   SDLoc dl(Op);
2742   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2743                      Op.getOperand(0));
2744 }
2745
2746 SDValue
2747 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2748                                           const ARMSubtarget *Subtarget) const {
2749   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2750   SDLoc dl(Op);
2751   switch (IntNo) {
2752   default: return SDValue();    // Don't custom lower most intrinsics.
2753   case Intrinsic::arm_rbit: {
2754     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2755            "RBIT intrinsic must have i32 type!");
2756     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2757   }
2758   case Intrinsic::arm_thread_pointer: {
2759     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2760     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2761   }
2762   case Intrinsic::eh_sjlj_lsda: {
2763     MachineFunction &MF = DAG.getMachineFunction();
2764     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2765     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2766     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2767     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2768     SDValue CPAddr;
2769     unsigned PCAdj = (RelocM != Reloc::PIC_)
2770       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2771     ARMConstantPoolValue *CPV =
2772       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2773                                       ARMCP::CPLSDA, PCAdj);
2774     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2775     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2776     SDValue Result =
2777       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2778                   MachinePointerInfo::getConstantPool(),
2779                   false, false, false, 0);
2780
2781     if (RelocM == Reloc::PIC_) {
2782       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2783       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2784     }
2785     return Result;
2786   }
2787   case Intrinsic::arm_neon_vmulls:
2788   case Intrinsic::arm_neon_vmullu: {
2789     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2790       ? ARMISD::VMULLs : ARMISD::VMULLu;
2791     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2792                        Op.getOperand(1), Op.getOperand(2));
2793   }
2794   }
2795 }
2796
2797 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2798                                  const ARMSubtarget *Subtarget) {
2799   // FIXME: handle "fence singlethread" more efficiently.
2800   SDLoc dl(Op);
2801   if (!Subtarget->hasDataBarrier()) {
2802     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2803     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2804     // here.
2805     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2806            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2807     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2808                        DAG.getConstant(0, dl, MVT::i32));
2809   }
2810
2811   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2812   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2813   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2814   if (Subtarget->isMClass()) {
2815     // Only a full system barrier exists in the M-class architectures.
2816     Domain = ARM_MB::SY;
2817   } else if (Subtarget->isSwift() && Ord == Release) {
2818     // Swift happens to implement ISHST barriers in a way that's compatible with
2819     // Release semantics but weaker than ISH so we'd be fools not to use
2820     // it. Beware: other processors probably don't!
2821     Domain = ARM_MB::ISHST;
2822   }
2823
2824   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2825                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2826                      DAG.getConstant(Domain, dl, MVT::i32));
2827 }
2828
2829 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2830                              const ARMSubtarget *Subtarget) {
2831   // ARM pre v5TE and Thumb1 does not have preload instructions.
2832   if (!(Subtarget->isThumb2() ||
2833         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2834     // Just preserve the chain.
2835     return Op.getOperand(0);
2836
2837   SDLoc dl(Op);
2838   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2839   if (!isRead &&
2840       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2841     // ARMv7 with MP extension has PLDW.
2842     return Op.getOperand(0);
2843
2844   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2845   if (Subtarget->isThumb()) {
2846     // Invert the bits.
2847     isRead = ~isRead & 1;
2848     isData = ~isData & 1;
2849   }
2850
2851   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2852                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2853                      DAG.getConstant(isData, dl, MVT::i32));
2854 }
2855
2856 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2857   MachineFunction &MF = DAG.getMachineFunction();
2858   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2859
2860   // vastart just stores the address of the VarArgsFrameIndex slot into the
2861   // memory location argument.
2862   SDLoc dl(Op);
2863   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2864   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2865   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2866   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2867                       MachinePointerInfo(SV), false, false, 0);
2868 }
2869
2870 SDValue
2871 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2872                                         SDValue &Root, SelectionDAG &DAG,
2873                                         SDLoc dl) const {
2874   MachineFunction &MF = DAG.getMachineFunction();
2875   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2876
2877   const TargetRegisterClass *RC;
2878   if (AFI->isThumb1OnlyFunction())
2879     RC = &ARM::tGPRRegClass;
2880   else
2881     RC = &ARM::GPRRegClass;
2882
2883   // Transform the arguments stored in physical registers into virtual ones.
2884   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2885   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2886
2887   SDValue ArgValue2;
2888   if (NextVA.isMemLoc()) {
2889     MachineFrameInfo *MFI = MF.getFrameInfo();
2890     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2891
2892     // Create load node to retrieve arguments from the stack.
2893     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2894     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2895                             MachinePointerInfo::getFixedStack(FI),
2896                             false, false, false, 0);
2897   } else {
2898     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2899     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2900   }
2901   if (!Subtarget->isLittle())
2902     std::swap (ArgValue, ArgValue2);
2903   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2904 }
2905
2906 // The remaining GPRs hold either the beginning of variable-argument
2907 // data, or the beginning of an aggregate passed by value (usually
2908 // byval).  Either way, we allocate stack slots adjacent to the data
2909 // provided by our caller, and store the unallocated registers there.
2910 // If this is a variadic function, the va_list pointer will begin with
2911 // these values; otherwise, this reassembles a (byval) structure that
2912 // was split between registers and memory.
2913 // Return: The frame index registers were stored into.
2914 int
2915 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2916                                   SDLoc dl, SDValue &Chain,
2917                                   const Value *OrigArg,
2918                                   unsigned InRegsParamRecordIdx,
2919                                   int ArgOffset,
2920                                   unsigned ArgSize) const {
2921   // Currently, two use-cases possible:
2922   // Case #1. Non-var-args function, and we meet first byval parameter.
2923   //          Setup first unallocated register as first byval register;
2924   //          eat all remained registers
2925   //          (these two actions are performed by HandleByVal method).
2926   //          Then, here, we initialize stack frame with
2927   //          "store-reg" instructions.
2928   // Case #2. Var-args function, that doesn't contain byval parameters.
2929   //          The same: eat all remained unallocated registers,
2930   //          initialize stack frame.
2931
2932   MachineFunction &MF = DAG.getMachineFunction();
2933   MachineFrameInfo *MFI = MF.getFrameInfo();
2934   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2935   unsigned RBegin, REnd;
2936   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2937     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2938   } else {
2939     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2940     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2941     REnd = ARM::R4;
2942   }
2943
2944   if (REnd != RBegin)
2945     ArgOffset = -4 * (ARM::R4 - RBegin);
2946
2947   auto PtrVT = getPointerTy(DAG.getDataLayout());
2948   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2949   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2950
2951   SmallVector<SDValue, 4> MemOps;
2952   const TargetRegisterClass *RC =
2953       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2954
2955   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2956     unsigned VReg = MF.addLiveIn(Reg, RC);
2957     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2958     SDValue Store =
2959         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2960                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2961     MemOps.push_back(Store);
2962     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2963   }
2964
2965   if (!MemOps.empty())
2966     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2967   return FrameIndex;
2968 }
2969
2970 // Setup stack frame, the va_list pointer will start from.
2971 void
2972 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2973                                         SDLoc dl, SDValue &Chain,
2974                                         unsigned ArgOffset,
2975                                         unsigned TotalArgRegsSaveSize,
2976                                         bool ForceMutable) const {
2977   MachineFunction &MF = DAG.getMachineFunction();
2978   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2979
2980   // Try to store any remaining integer argument regs
2981   // to their spots on the stack so that they may be loaded by deferencing
2982   // the result of va_next.
2983   // If there is no regs to be stored, just point address after last
2984   // argument passed via stack.
2985   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2986                                   CCInfo.getInRegsParamsCount(),
2987                                   CCInfo.getNextStackOffset(), 4);
2988   AFI->setVarArgsFrameIndex(FrameIndex);
2989 }
2990
2991 SDValue
2992 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2993                                         CallingConv::ID CallConv, bool isVarArg,
2994                                         const SmallVectorImpl<ISD::InputArg>
2995                                           &Ins,
2996                                         SDLoc dl, SelectionDAG &DAG,
2997                                         SmallVectorImpl<SDValue> &InVals)
2998                                           const {
2999   MachineFunction &MF = DAG.getMachineFunction();
3000   MachineFrameInfo *MFI = MF.getFrameInfo();
3001
3002   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3003
3004   // Assign locations to all of the incoming arguments.
3005   SmallVector<CCValAssign, 16> ArgLocs;
3006   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3007                     *DAG.getContext(), Prologue);
3008   CCInfo.AnalyzeFormalArguments(Ins,
3009                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3010                                                   isVarArg));
3011
3012   SmallVector<SDValue, 16> ArgValues;
3013   SDValue ArgValue;
3014   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3015   unsigned CurArgIdx = 0;
3016
3017   // Initially ArgRegsSaveSize is zero.
3018   // Then we increase this value each time we meet byval parameter.
3019   // We also increase this value in case of varargs function.
3020   AFI->setArgRegsSaveSize(0);
3021
3022   // Calculate the amount of stack space that we need to allocate to store
3023   // byval and variadic arguments that are passed in registers.
3024   // We need to know this before we allocate the first byval or variadic
3025   // argument, as they will be allocated a stack slot below the CFA (Canonical
3026   // Frame Address, the stack pointer at entry to the function).
3027   unsigned ArgRegBegin = ARM::R4;
3028   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3029     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3030       break;
3031
3032     CCValAssign &VA = ArgLocs[i];
3033     unsigned Index = VA.getValNo();
3034     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3035     if (!Flags.isByVal())
3036       continue;
3037
3038     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3039     unsigned RBegin, REnd;
3040     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3041     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3042
3043     CCInfo.nextInRegsParam();
3044   }
3045   CCInfo.rewindByValRegsInfo();
3046
3047   int lastInsIndex = -1;
3048   if (isVarArg && MFI->hasVAStart()) {
3049     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3050     if (RegIdx != array_lengthof(GPRArgRegs))
3051       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3052   }
3053
3054   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3055   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3056   auto PtrVT = getPointerTy(DAG.getDataLayout());
3057
3058   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3059     CCValAssign &VA = ArgLocs[i];
3060     if (Ins[VA.getValNo()].isOrigArg()) {
3061       std::advance(CurOrigArg,
3062                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3063       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3064     }
3065     // Arguments stored in registers.
3066     if (VA.isRegLoc()) {
3067       EVT RegVT = VA.getLocVT();
3068
3069       if (VA.needsCustom()) {
3070         // f64 and vector types are split up into multiple registers or
3071         // combinations of registers and stack slots.
3072         if (VA.getLocVT() == MVT::v2f64) {
3073           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3074                                                    Chain, DAG, dl);
3075           VA = ArgLocs[++i]; // skip ahead to next loc
3076           SDValue ArgValue2;
3077           if (VA.isMemLoc()) {
3078             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3079             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3080             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3081                                     MachinePointerInfo::getFixedStack(FI),
3082                                     false, false, false, 0);
3083           } else {
3084             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3085                                              Chain, DAG, dl);
3086           }
3087           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3088           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3089                                  ArgValue, ArgValue1,
3090                                  DAG.getIntPtrConstant(0, dl));
3091           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3092                                  ArgValue, ArgValue2,
3093                                  DAG.getIntPtrConstant(1, dl));
3094         } else
3095           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3096
3097       } else {
3098         const TargetRegisterClass *RC;
3099
3100         if (RegVT == MVT::f32)
3101           RC = &ARM::SPRRegClass;
3102         else if (RegVT == MVT::f64)
3103           RC = &ARM::DPRRegClass;
3104         else if (RegVT == MVT::v2f64)
3105           RC = &ARM::QPRRegClass;
3106         else if (RegVT == MVT::i32)
3107           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3108                                            : &ARM::GPRRegClass;
3109         else
3110           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3111
3112         // Transform the arguments in physical registers into virtual ones.
3113         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3114         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3115       }
3116
3117       // If this is an 8 or 16-bit value, it is really passed promoted
3118       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3119       // truncate to the right size.
3120       switch (VA.getLocInfo()) {
3121       default: llvm_unreachable("Unknown loc info!");
3122       case CCValAssign::Full: break;
3123       case CCValAssign::BCvt:
3124         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3125         break;
3126       case CCValAssign::SExt:
3127         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3128                                DAG.getValueType(VA.getValVT()));
3129         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3130         break;
3131       case CCValAssign::ZExt:
3132         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3133                                DAG.getValueType(VA.getValVT()));
3134         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3135         break;
3136       }
3137
3138       InVals.push_back(ArgValue);
3139
3140     } else { // VA.isRegLoc()
3141
3142       // sanity check
3143       assert(VA.isMemLoc());
3144       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3145
3146       int index = VA.getValNo();
3147
3148       // Some Ins[] entries become multiple ArgLoc[] entries.
3149       // Process them only once.
3150       if (index != lastInsIndex)
3151         {
3152           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3153           // FIXME: For now, all byval parameter objects are marked mutable.
3154           // This can be changed with more analysis.
3155           // In case of tail call optimization mark all arguments mutable.
3156           // Since they could be overwritten by lowering of arguments in case of
3157           // a tail call.
3158           if (Flags.isByVal()) {
3159             assert(Ins[index].isOrigArg() &&
3160                    "Byval arguments cannot be implicit");
3161             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3162
3163             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3164                                             CurByValIndex, VA.getLocMemOffset(),
3165                                             Flags.getByValSize());
3166             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3167             CCInfo.nextInRegsParam();
3168           } else {
3169             unsigned FIOffset = VA.getLocMemOffset();
3170             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3171                                             FIOffset, true);
3172
3173             // Create load nodes to retrieve arguments from the stack.
3174             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3175             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3176                                          MachinePointerInfo::getFixedStack(FI),
3177                                          false, false, false, 0));
3178           }
3179           lastInsIndex = index;
3180         }
3181     }
3182   }
3183
3184   // varargs
3185   if (isVarArg && MFI->hasVAStart())
3186     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3187                          CCInfo.getNextStackOffset(),
3188                          TotalArgRegsSaveSize);
3189
3190   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3191
3192   return Chain;
3193 }
3194
3195 /// isFloatingPointZero - Return true if this is +0.0.
3196 static bool isFloatingPointZero(SDValue Op) {
3197   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3198     return CFP->getValueAPF().isPosZero();
3199   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3200     // Maybe this has already been legalized into the constant pool?
3201     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3202       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3203       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3204         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3205           return CFP->getValueAPF().isPosZero();
3206     }
3207   } else if (Op->getOpcode() == ISD::BITCAST &&
3208              Op->getValueType(0) == MVT::f64) {
3209     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3210     // created by LowerConstantFP().
3211     SDValue BitcastOp = Op->getOperand(0);
3212     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3213       SDValue MoveOp = BitcastOp->getOperand(0);
3214       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3215           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3216         return true;
3217       }
3218     }
3219   }
3220   return false;
3221 }
3222
3223 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3224 /// the given operands.
3225 SDValue
3226 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3227                              SDValue &ARMcc, SelectionDAG &DAG,
3228                              SDLoc dl) const {
3229   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3230     unsigned C = RHSC->getZExtValue();
3231     if (!isLegalICmpImmediate(C)) {
3232       // Constant does not fit, try adjusting it by one?
3233       switch (CC) {
3234       default: break;
3235       case ISD::SETLT:
3236       case ISD::SETGE:
3237         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3238           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3239           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3240         }
3241         break;
3242       case ISD::SETULT:
3243       case ISD::SETUGE:
3244         if (C != 0 && isLegalICmpImmediate(C-1)) {
3245           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3246           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3247         }
3248         break;
3249       case ISD::SETLE:
3250       case ISD::SETGT:
3251         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3252           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3253           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3254         }
3255         break;
3256       case ISD::SETULE:
3257       case ISD::SETUGT:
3258         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3259           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3260           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3261         }
3262         break;
3263       }
3264     }
3265   }
3266
3267   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3268   ARMISD::NodeType CompareType;
3269   switch (CondCode) {
3270   default:
3271     CompareType = ARMISD::CMP;
3272     break;
3273   case ARMCC::EQ:
3274   case ARMCC::NE:
3275     // Uses only Z Flag
3276     CompareType = ARMISD::CMPZ;
3277     break;
3278   }
3279   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3280   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3281 }
3282
3283 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3284 SDValue
3285 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3286                              SDLoc dl) const {
3287   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3288   SDValue Cmp;
3289   if (!isFloatingPointZero(RHS))
3290     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3291   else
3292     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3293   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3294 }
3295
3296 /// duplicateCmp - Glue values can have only one use, so this function
3297 /// duplicates a comparison node.
3298 SDValue
3299 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3300   unsigned Opc = Cmp.getOpcode();
3301   SDLoc DL(Cmp);
3302   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3303     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3304
3305   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3306   Cmp = Cmp.getOperand(0);
3307   Opc = Cmp.getOpcode();
3308   if (Opc == ARMISD::CMPFP)
3309     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3310   else {
3311     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3312     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3313   }
3314   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3315 }
3316
3317 std::pair<SDValue, SDValue>
3318 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3319                                  SDValue &ARMcc) const {
3320   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3321
3322   SDValue Value, OverflowCmp;
3323   SDValue LHS = Op.getOperand(0);
3324   SDValue RHS = Op.getOperand(1);
3325   SDLoc dl(Op);
3326
3327   // FIXME: We are currently always generating CMPs because we don't support
3328   // generating CMN through the backend. This is not as good as the natural
3329   // CMP case because it causes a register dependency and cannot be folded
3330   // later.
3331
3332   switch (Op.getOpcode()) {
3333   default:
3334     llvm_unreachable("Unknown overflow instruction!");
3335   case ISD::SADDO:
3336     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3337     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3338     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3339     break;
3340   case ISD::UADDO:
3341     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3342     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3343     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3344     break;
3345   case ISD::SSUBO:
3346     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3347     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3348     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3349     break;
3350   case ISD::USUBO:
3351     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3352     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3353     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3354     break;
3355   } // switch (...)
3356
3357   return std::make_pair(Value, OverflowCmp);
3358 }
3359
3360
3361 SDValue
3362 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3363   // Let legalize expand this if it isn't a legal type yet.
3364   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3365     return SDValue();
3366
3367   SDValue Value, OverflowCmp;
3368   SDValue ARMcc;
3369   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3370   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3371   SDLoc dl(Op);
3372   // We use 0 and 1 as false and true values.
3373   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3374   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3375   EVT VT = Op.getValueType();
3376
3377   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3378                                  ARMcc, CCR, OverflowCmp);
3379
3380   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3381   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3382 }
3383
3384
3385 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3386   SDValue Cond = Op.getOperand(0);
3387   SDValue SelectTrue = Op.getOperand(1);
3388   SDValue SelectFalse = Op.getOperand(2);
3389   SDLoc dl(Op);
3390   unsigned Opc = Cond.getOpcode();
3391
3392   if (Cond.getResNo() == 1 &&
3393       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3394        Opc == ISD::USUBO)) {
3395     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3396       return SDValue();
3397
3398     SDValue Value, OverflowCmp;
3399     SDValue ARMcc;
3400     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3401     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3402     EVT VT = Op.getValueType();
3403
3404     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3405                    OverflowCmp, DAG);
3406   }
3407
3408   // Convert:
3409   //
3410   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3411   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3412   //
3413   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3414     const ConstantSDNode *CMOVTrue =
3415       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3416     const ConstantSDNode *CMOVFalse =
3417       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3418
3419     if (CMOVTrue && CMOVFalse) {
3420       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3421       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3422
3423       SDValue True;
3424       SDValue False;
3425       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3426         True = SelectTrue;
3427         False = SelectFalse;
3428       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3429         True = SelectFalse;
3430         False = SelectTrue;
3431       }
3432
3433       if (True.getNode() && False.getNode()) {
3434         EVT VT = Op.getValueType();
3435         SDValue ARMcc = Cond.getOperand(2);
3436         SDValue CCR = Cond.getOperand(3);
3437         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3438         assert(True.getValueType() == VT);
3439         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3440       }
3441     }
3442   }
3443
3444   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3445   // undefined bits before doing a full-word comparison with zero.
3446   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3447                      DAG.getConstant(1, dl, Cond.getValueType()));
3448
3449   return DAG.getSelectCC(dl, Cond,
3450                          DAG.getConstant(0, dl, Cond.getValueType()),
3451                          SelectTrue, SelectFalse, ISD::SETNE);
3452 }
3453
3454 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3455                                  bool &swpCmpOps, bool &swpVselOps) {
3456   // Start by selecting the GE condition code for opcodes that return true for
3457   // 'equality'
3458   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3459       CC == ISD::SETULE)
3460     CondCode = ARMCC::GE;
3461
3462   // and GT for opcodes that return false for 'equality'.
3463   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3464            CC == ISD::SETULT)
3465     CondCode = ARMCC::GT;
3466
3467   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3468   // to swap the compare operands.
3469   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3470       CC == ISD::SETULT)
3471     swpCmpOps = true;
3472
3473   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3474   // If we have an unordered opcode, we need to swap the operands to the VSEL
3475   // instruction (effectively negating the condition).
3476   //
3477   // This also has the effect of swapping which one of 'less' or 'greater'
3478   // returns true, so we also swap the compare operands. It also switches
3479   // whether we return true for 'equality', so we compensate by picking the
3480   // opposite condition code to our original choice.
3481   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3482       CC == ISD::SETUGT) {
3483     swpCmpOps = !swpCmpOps;
3484     swpVselOps = !swpVselOps;
3485     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3486   }
3487
3488   // 'ordered' is 'anything but unordered', so use the VS condition code and
3489   // swap the VSEL operands.
3490   if (CC == ISD::SETO) {
3491     CondCode = ARMCC::VS;
3492     swpVselOps = true;
3493   }
3494
3495   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3496   // code and swap the VSEL operands.
3497   if (CC == ISD::SETUNE) {
3498     CondCode = ARMCC::EQ;
3499     swpVselOps = true;
3500   }
3501 }
3502
3503 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3504                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3505                                    SDValue Cmp, SelectionDAG &DAG) const {
3506   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3507     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3508                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3509     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3510                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3511
3512     SDValue TrueLow = TrueVal.getValue(0);
3513     SDValue TrueHigh = TrueVal.getValue(1);
3514     SDValue FalseLow = FalseVal.getValue(0);
3515     SDValue FalseHigh = FalseVal.getValue(1);
3516
3517     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3518                               ARMcc, CCR, Cmp);
3519     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3520                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3521
3522     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3523   } else {
3524     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3525                        Cmp);
3526   }
3527 }
3528
3529 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3530   EVT VT = Op.getValueType();
3531   SDValue LHS = Op.getOperand(0);
3532   SDValue RHS = Op.getOperand(1);
3533   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3534   SDValue TrueVal = Op.getOperand(2);
3535   SDValue FalseVal = Op.getOperand(3);
3536   SDLoc dl(Op);
3537
3538   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3539     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3540                                                     dl);
3541
3542     // If softenSetCCOperands only returned one value, we should compare it to
3543     // zero.
3544     if (!RHS.getNode()) {
3545       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3546       CC = ISD::SETNE;
3547     }
3548   }
3549
3550   if (LHS.getValueType() == MVT::i32) {
3551     // Try to generate VSEL on ARMv8.
3552     // The VSEL instruction can't use all the usual ARM condition
3553     // codes: it only has two bits to select the condition code, so it's
3554     // constrained to use only GE, GT, VS and EQ.
3555     //
3556     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3557     // swap the operands of the previous compare instruction (effectively
3558     // inverting the compare condition, swapping 'less' and 'greater') and
3559     // sometimes need to swap the operands to the VSEL (which inverts the
3560     // condition in the sense of firing whenever the previous condition didn't)
3561     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3562                                     TrueVal.getValueType() == MVT::f64)) {
3563       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3564       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3565           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3566         CC = ISD::getSetCCInverse(CC, true);
3567         std::swap(TrueVal, FalseVal);
3568       }
3569     }
3570
3571     SDValue ARMcc;
3572     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3573     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3574     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3575   }
3576
3577   ARMCC::CondCodes CondCode, CondCode2;
3578   FPCCToARMCC(CC, CondCode, CondCode2);
3579
3580   // Try to generate VMAXNM/VMINNM on ARMv8.
3581   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3582                                   TrueVal.getValueType() == MVT::f64)) {
3583     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3584     // same operands, as follows:
3585     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3586     //   select c, a, b
3587     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3588     bool swapSides = false;
3589     if (!getTargetMachine().Options.NoNaNsFPMath) {
3590       // transformability may depend on which way around we compare
3591       switch (CC) {
3592       default:
3593         break;
3594       case ISD::SETOGT:
3595       case ISD::SETOGE:
3596       case ISD::SETOLT:
3597       case ISD::SETOLE:
3598         // the non-NaN should be RHS
3599         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3600         break;
3601       case ISD::SETUGT:
3602       case ISD::SETUGE:
3603       case ISD::SETULT:
3604       case ISD::SETULE:
3605         // the non-NaN should be LHS
3606         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3607         break;
3608       }
3609     }
3610     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3611     if (swapSides) {
3612       CC = ISD::getSetCCSwappedOperands(CC);
3613       std::swap(LHS, RHS);
3614     }
3615     if (LHS == TrueVal && RHS == FalseVal) {
3616       bool canTransform = true;
3617       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3618       if (!getTargetMachine().Options.UnsafeFPMath &&
3619           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3620         const ConstantFPSDNode *Zero;
3621         switch (CC) {
3622         default:
3623           break;
3624         case ISD::SETOGT:
3625         case ISD::SETUGT:
3626         case ISD::SETGT:
3627           // RHS must not be -0
3628           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3629                          !Zero->isNegative();
3630           break;
3631         case ISD::SETOGE:
3632         case ISD::SETUGE:
3633         case ISD::SETGE:
3634           // LHS must not be -0
3635           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3636                          !Zero->isNegative();
3637           break;
3638         case ISD::SETOLT:
3639         case ISD::SETULT:
3640         case ISD::SETLT:
3641           // RHS must not be +0
3642           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3643                           Zero->isNegative();
3644           break;
3645         case ISD::SETOLE:
3646         case ISD::SETULE:
3647         case ISD::SETLE:
3648           // LHS must not be +0
3649           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3650                           Zero->isNegative();
3651           break;
3652         }
3653       }
3654       if (canTransform) {
3655         // Note: If one of the elements in a pair is a number and the other
3656         // element is NaN, the corresponding result element is the number.
3657         // This is consistent with the IEEE 754-2008 standard.
3658         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3659         switch (CC) {
3660         default:
3661           break;
3662         case ISD::SETOGT:
3663         case ISD::SETOGE:
3664           if (!DAG.isKnownNeverNaN(RHS))
3665             break;
3666           return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3667         case ISD::SETUGT:
3668         case ISD::SETUGE:
3669           if (!DAG.isKnownNeverNaN(LHS))
3670             break;
3671         case ISD::SETGT:
3672         case ISD::SETGE:
3673           return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3674         case ISD::SETOLT:
3675         case ISD::SETOLE:
3676           if (!DAG.isKnownNeverNaN(RHS))
3677             break;
3678           return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3679         case ISD::SETULT:
3680         case ISD::SETULE:
3681           if (!DAG.isKnownNeverNaN(LHS))
3682             break;
3683         case ISD::SETLT:
3684         case ISD::SETLE:
3685           return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3686         }
3687       }
3688     }
3689
3690     bool swpCmpOps = false;
3691     bool swpVselOps = false;
3692     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3693
3694     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3695         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3696       if (swpCmpOps)
3697         std::swap(LHS, RHS);
3698       if (swpVselOps)
3699         std::swap(TrueVal, FalseVal);
3700     }
3701   }
3702
3703   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3704   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3705   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3706   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3707   if (CondCode2 != ARMCC::AL) {
3708     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3709     // FIXME: Needs another CMP because flag can have but one use.
3710     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3711     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3712   }
3713   return Result;
3714 }
3715
3716 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3717 /// to morph to an integer compare sequence.
3718 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3719                            const ARMSubtarget *Subtarget) {
3720   SDNode *N = Op.getNode();
3721   if (!N->hasOneUse())
3722     // Otherwise it requires moving the value from fp to integer registers.
3723     return false;
3724   if (!N->getNumValues())
3725     return false;
3726   EVT VT = Op.getValueType();
3727   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3728     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3729     // vmrs are very slow, e.g. cortex-a8.
3730     return false;
3731
3732   if (isFloatingPointZero(Op)) {
3733     SeenZero = true;
3734     return true;
3735   }
3736   return ISD::isNormalLoad(N);
3737 }
3738
3739 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3740   if (isFloatingPointZero(Op))
3741     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3742
3743   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3744     return DAG.getLoad(MVT::i32, SDLoc(Op),
3745                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3746                        Ld->isVolatile(), Ld->isNonTemporal(),
3747                        Ld->isInvariant(), Ld->getAlignment());
3748
3749   llvm_unreachable("Unknown VFP cmp argument!");
3750 }
3751
3752 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3753                            SDValue &RetVal1, SDValue &RetVal2) {
3754   SDLoc dl(Op);
3755
3756   if (isFloatingPointZero(Op)) {
3757     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3758     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3759     return;
3760   }
3761
3762   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3763     SDValue Ptr = Ld->getBasePtr();
3764     RetVal1 = DAG.getLoad(MVT::i32, dl,
3765                           Ld->getChain(), Ptr,
3766                           Ld->getPointerInfo(),
3767                           Ld->isVolatile(), Ld->isNonTemporal(),
3768                           Ld->isInvariant(), Ld->getAlignment());
3769
3770     EVT PtrType = Ptr.getValueType();
3771     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3772     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3773                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3774     RetVal2 = DAG.getLoad(MVT::i32, dl,
3775                           Ld->getChain(), NewPtr,
3776                           Ld->getPointerInfo().getWithOffset(4),
3777                           Ld->isVolatile(), Ld->isNonTemporal(),
3778                           Ld->isInvariant(), NewAlign);
3779     return;
3780   }
3781
3782   llvm_unreachable("Unknown VFP cmp argument!");
3783 }
3784
3785 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3786 /// f32 and even f64 comparisons to integer ones.
3787 SDValue
3788 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3789   SDValue Chain = Op.getOperand(0);
3790   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3791   SDValue LHS = Op.getOperand(2);
3792   SDValue RHS = Op.getOperand(3);
3793   SDValue Dest = Op.getOperand(4);
3794   SDLoc dl(Op);
3795
3796   bool LHSSeenZero = false;
3797   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3798   bool RHSSeenZero = false;
3799   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3800   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3801     // If unsafe fp math optimization is enabled and there are no other uses of
3802     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3803     // to an integer comparison.
3804     if (CC == ISD::SETOEQ)
3805       CC = ISD::SETEQ;
3806     else if (CC == ISD::SETUNE)
3807       CC = ISD::SETNE;
3808
3809     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3810     SDValue ARMcc;
3811     if (LHS.getValueType() == MVT::f32) {
3812       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3813                         bitcastf32Toi32(LHS, DAG), Mask);
3814       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3815                         bitcastf32Toi32(RHS, DAG), Mask);
3816       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3817       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3818       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3819                          Chain, Dest, ARMcc, CCR, Cmp);
3820     }
3821
3822     SDValue LHS1, LHS2;
3823     SDValue RHS1, RHS2;
3824     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3825     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3826     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3827     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3828     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3829     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3830     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3831     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3832     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3833   }
3834
3835   return SDValue();
3836 }
3837
3838 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3839   SDValue Chain = Op.getOperand(0);
3840   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3841   SDValue LHS = Op.getOperand(2);
3842   SDValue RHS = Op.getOperand(3);
3843   SDValue Dest = Op.getOperand(4);
3844   SDLoc dl(Op);
3845
3846   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3847     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3848                                                     dl);
3849
3850     // If softenSetCCOperands only returned one value, we should compare it to
3851     // zero.
3852     if (!RHS.getNode()) {
3853       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3854       CC = ISD::SETNE;
3855     }
3856   }
3857
3858   if (LHS.getValueType() == MVT::i32) {
3859     SDValue ARMcc;
3860     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3861     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3862     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3863                        Chain, Dest, ARMcc, CCR, Cmp);
3864   }
3865
3866   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3867
3868   if (getTargetMachine().Options.UnsafeFPMath &&
3869       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3870        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3871     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3872     if (Result.getNode())
3873       return Result;
3874   }
3875
3876   ARMCC::CondCodes CondCode, CondCode2;
3877   FPCCToARMCC(CC, CondCode, CondCode2);
3878
3879   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3880   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3881   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3882   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3883   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3884   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3885   if (CondCode2 != ARMCC::AL) {
3886     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3887     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3888     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3889   }
3890   return Res;
3891 }
3892
3893 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3894   SDValue Chain = Op.getOperand(0);
3895   SDValue Table = Op.getOperand(1);
3896   SDValue Index = Op.getOperand(2);
3897   SDLoc dl(Op);
3898
3899   EVT PTy = getPointerTy(DAG.getDataLayout());
3900   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3901   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3902   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3903   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3904   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3905   if (Subtarget->isThumb2()) {
3906     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3907     // which does another jump to the destination. This also makes it easier
3908     // to translate it to TBB / TBH later.
3909     // FIXME: This might not work if the function is extremely large.
3910     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3911                        Addr, Op.getOperand(2), JTI);
3912   }
3913   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3914     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3915                        MachinePointerInfo::getJumpTable(),
3916                        false, false, false, 0);
3917     Chain = Addr.getValue(1);
3918     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3919     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3920   } else {
3921     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3922                        MachinePointerInfo::getJumpTable(),
3923                        false, false, false, 0);
3924     Chain = Addr.getValue(1);
3925     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3926   }
3927 }
3928
3929 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3930   EVT VT = Op.getValueType();
3931   SDLoc dl(Op);
3932
3933   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3934     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3935       return Op;
3936     return DAG.UnrollVectorOp(Op.getNode());
3937   }
3938
3939   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3940          "Invalid type for custom lowering!");
3941   if (VT != MVT::v4i16)
3942     return DAG.UnrollVectorOp(Op.getNode());
3943
3944   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3945   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3946 }
3947
3948 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3949   EVT VT = Op.getValueType();
3950   if (VT.isVector())
3951     return LowerVectorFP_TO_INT(Op, DAG);
3952   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3953     RTLIB::Libcall LC;
3954     if (Op.getOpcode() == ISD::FP_TO_SINT)
3955       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3956                               Op.getValueType());
3957     else
3958       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3959                               Op.getValueType());
3960     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3961                        /*isSigned*/ false, SDLoc(Op)).first;
3962   }
3963
3964   return Op;
3965 }
3966
3967 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3968   EVT VT = Op.getValueType();
3969   SDLoc dl(Op);
3970
3971   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3972     if (VT.getVectorElementType() == MVT::f32)
3973       return Op;
3974     return DAG.UnrollVectorOp(Op.getNode());
3975   }
3976
3977   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3978          "Invalid type for custom lowering!");
3979   if (VT != MVT::v4f32)
3980     return DAG.UnrollVectorOp(Op.getNode());
3981
3982   unsigned CastOpc;
3983   unsigned Opc;
3984   switch (Op.getOpcode()) {
3985   default: llvm_unreachable("Invalid opcode!");
3986   case ISD::SINT_TO_FP:
3987     CastOpc = ISD::SIGN_EXTEND;
3988     Opc = ISD::SINT_TO_FP;
3989     break;
3990   case ISD::UINT_TO_FP:
3991     CastOpc = ISD::ZERO_EXTEND;
3992     Opc = ISD::UINT_TO_FP;
3993     break;
3994   }
3995
3996   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3997   return DAG.getNode(Opc, dl, VT, Op);
3998 }
3999
4000 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4001   EVT VT = Op.getValueType();
4002   if (VT.isVector())
4003     return LowerVectorINT_TO_FP(Op, DAG);
4004   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4005     RTLIB::Libcall LC;
4006     if (Op.getOpcode() == ISD::SINT_TO_FP)
4007       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4008                               Op.getValueType());
4009     else
4010       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4011                               Op.getValueType());
4012     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4013                        /*isSigned*/ false, SDLoc(Op)).first;
4014   }
4015
4016   return Op;
4017 }
4018
4019 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4020   // Implement fcopysign with a fabs and a conditional fneg.
4021   SDValue Tmp0 = Op.getOperand(0);
4022   SDValue Tmp1 = Op.getOperand(1);
4023   SDLoc dl(Op);
4024   EVT VT = Op.getValueType();
4025   EVT SrcVT = Tmp1.getValueType();
4026   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4027     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4028   bool UseNEON = !InGPR && Subtarget->hasNEON();
4029
4030   if (UseNEON) {
4031     // Use VBSL to copy the sign bit.
4032     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4033     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4034                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4035     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4036     if (VT == MVT::f64)
4037       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4038                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4039                          DAG.getConstant(32, dl, MVT::i32));
4040     else /*if (VT == MVT::f32)*/
4041       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4042     if (SrcVT == MVT::f32) {
4043       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4044       if (VT == MVT::f64)
4045         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4046                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4047                            DAG.getConstant(32, dl, MVT::i32));
4048     } else if (VT == MVT::f32)
4049       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4050                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4051                          DAG.getConstant(32, dl, MVT::i32));
4052     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4053     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4054
4055     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4056                                             dl, MVT::i32);
4057     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4058     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4059                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4060
4061     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4062                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4063                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4064     if (VT == MVT::f32) {
4065       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4066       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4067                         DAG.getConstant(0, dl, MVT::i32));
4068     } else {
4069       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4070     }
4071
4072     return Res;
4073   }
4074
4075   // Bitcast operand 1 to i32.
4076   if (SrcVT == MVT::f64)
4077     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4078                        Tmp1).getValue(1);
4079   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4080
4081   // Or in the signbit with integer operations.
4082   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4083   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4084   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4085   if (VT == MVT::f32) {
4086     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4087                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4088     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4089                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4090   }
4091
4092   // f64: Or the high part with signbit and then combine two parts.
4093   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4094                      Tmp0);
4095   SDValue Lo = Tmp0.getValue(0);
4096   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4097   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4098   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4099 }
4100
4101 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4102   MachineFunction &MF = DAG.getMachineFunction();
4103   MachineFrameInfo *MFI = MF.getFrameInfo();
4104   MFI->setReturnAddressIsTaken(true);
4105
4106   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4107     return SDValue();
4108
4109   EVT VT = Op.getValueType();
4110   SDLoc dl(Op);
4111   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4112   if (Depth) {
4113     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4114     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4115     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4116                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4117                        MachinePointerInfo(), false, false, false, 0);
4118   }
4119
4120   // Return LR, which contains the return address. Mark it an implicit live-in.
4121   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4122   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4123 }
4124
4125 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4126   const ARMBaseRegisterInfo &ARI =
4127     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4128   MachineFunction &MF = DAG.getMachineFunction();
4129   MachineFrameInfo *MFI = MF.getFrameInfo();
4130   MFI->setFrameAddressIsTaken(true);
4131
4132   EVT VT = Op.getValueType();
4133   SDLoc dl(Op);  // FIXME probably not meaningful
4134   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4135   unsigned FrameReg = ARI.getFrameRegister(MF);
4136   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4137   while (Depth--)
4138     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4139                             MachinePointerInfo(),
4140                             false, false, false, 0);
4141   return FrameAddr;
4142 }
4143
4144 // FIXME? Maybe this could be a TableGen attribute on some registers and
4145 // this table could be generated automatically from RegInfo.
4146 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4147                                               SelectionDAG &DAG) const {
4148   unsigned Reg = StringSwitch<unsigned>(RegName)
4149                        .Case("sp", ARM::SP)
4150                        .Default(0);
4151   if (Reg)
4152     return Reg;
4153   report_fatal_error(Twine("Invalid register name \""
4154                               + StringRef(RegName)  + "\"."));
4155 }
4156
4157 // Result is 64 bit value so split into two 32 bit values and return as a
4158 // pair of values.
4159 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4160                                 SelectionDAG &DAG) {
4161   SDLoc DL(N);
4162
4163   // This function is only supposed to be called for i64 type destination.
4164   assert(N->getValueType(0) == MVT::i64
4165           && "ExpandREAD_REGISTER called for non-i64 type result.");
4166
4167   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4168                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4169                              N->getOperand(0),
4170                              N->getOperand(1));
4171
4172   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4173                     Read.getValue(1)));
4174   Results.push_back(Read.getOperand(0));
4175 }
4176
4177 /// ExpandBITCAST - If the target supports VFP, this function is called to
4178 /// expand a bit convert where either the source or destination type is i64 to
4179 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4180 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4181 /// vectors), since the legalizer won't know what to do with that.
4182 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4183   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4184   SDLoc dl(N);
4185   SDValue Op = N->getOperand(0);
4186
4187   // This function is only supposed to be called for i64 types, either as the
4188   // source or destination of the bit convert.
4189   EVT SrcVT = Op.getValueType();
4190   EVT DstVT = N->getValueType(0);
4191   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4192          "ExpandBITCAST called for non-i64 type");
4193
4194   // Turn i64->f64 into VMOVDRR.
4195   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4196     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4197                              DAG.getConstant(0, dl, MVT::i32));
4198     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4199                              DAG.getConstant(1, dl, MVT::i32));
4200     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4201                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4202   }
4203
4204   // Turn f64->i64 into VMOVRRD.
4205   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4206     SDValue Cvt;
4207     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4208         SrcVT.getVectorNumElements() > 1)
4209       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4210                         DAG.getVTList(MVT::i32, MVT::i32),
4211                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4212     else
4213       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4214                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4215     // Merge the pieces into a single i64 value.
4216     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4217   }
4218
4219   return SDValue();
4220 }
4221
4222 /// getZeroVector - Returns a vector of specified type with all zero elements.
4223 /// Zero vectors are used to represent vector negation and in those cases
4224 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4225 /// not support i64 elements, so sometimes the zero vectors will need to be
4226 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4227 /// zero vector.
4228 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4229   assert(VT.isVector() && "Expected a vector type");
4230   // The canonical modified immediate encoding of a zero vector is....0!
4231   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4232   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4233   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4234   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4235 }
4236
4237 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4238 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4239 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4240                                                 SelectionDAG &DAG) const {
4241   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4242   EVT VT = Op.getValueType();
4243   unsigned VTBits = VT.getSizeInBits();
4244   SDLoc dl(Op);
4245   SDValue ShOpLo = Op.getOperand(0);
4246   SDValue ShOpHi = Op.getOperand(1);
4247   SDValue ShAmt  = Op.getOperand(2);
4248   SDValue ARMcc;
4249   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4250
4251   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4252
4253   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4254                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4255   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4256   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4257                                    DAG.getConstant(VTBits, dl, MVT::i32));
4258   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4259   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4260   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4261
4262   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4263   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4264                           ISD::SETGE, ARMcc, DAG, dl);
4265   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4266   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4267                            CCR, Cmp);
4268
4269   SDValue Ops[2] = { Lo, Hi };
4270   return DAG.getMergeValues(Ops, dl);
4271 }
4272
4273 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4274 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4275 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4276                                                SelectionDAG &DAG) const {
4277   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4278   EVT VT = Op.getValueType();
4279   unsigned VTBits = VT.getSizeInBits();
4280   SDLoc dl(Op);
4281   SDValue ShOpLo = Op.getOperand(0);
4282   SDValue ShOpHi = Op.getOperand(1);
4283   SDValue ShAmt  = Op.getOperand(2);
4284   SDValue ARMcc;
4285
4286   assert(Op.getOpcode() == ISD::SHL_PARTS);
4287   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4288                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4289   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4290   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4291                                    DAG.getConstant(VTBits, dl, MVT::i32));
4292   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4293   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4294
4295   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4296   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4297   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4298                           ISD::SETGE, ARMcc, DAG, dl);
4299   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4300   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4301                            CCR, Cmp);
4302
4303   SDValue Ops[2] = { Lo, Hi };
4304   return DAG.getMergeValues(Ops, dl);
4305 }
4306
4307 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4308                                             SelectionDAG &DAG) const {
4309   // The rounding mode is in bits 23:22 of the FPSCR.
4310   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4311   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4312   // so that the shift + and get folded into a bitfield extract.
4313   SDLoc dl(Op);
4314   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4315                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4316                                               MVT::i32));
4317   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4318                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4319   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4320                               DAG.getConstant(22, dl, MVT::i32));
4321   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4322                      DAG.getConstant(3, dl, MVT::i32));
4323 }
4324
4325 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4326                          const ARMSubtarget *ST) {
4327   SDLoc dl(N);
4328   EVT VT = N->getValueType(0);
4329   if (VT.isVector()) {
4330     assert(ST->hasNEON());
4331
4332     // Compute the least significant set bit: LSB = X & -X
4333     SDValue X = N->getOperand(0);
4334     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4335     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4336
4337     EVT ElemTy = VT.getVectorElementType();
4338
4339     if (ElemTy == MVT::i8) {
4340       // Compute with: cttz(x) = ctpop(lsb - 1)
4341       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4342                                 DAG.getTargetConstant(1, dl, ElemTy));
4343       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4344       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4345     }
4346
4347     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4348         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4349       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4350       unsigned NumBits = ElemTy.getSizeInBits();
4351       SDValue WidthMinus1 =
4352           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4353                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4354       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4355       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4356     }
4357
4358     // Compute with: cttz(x) = ctpop(lsb - 1)
4359
4360     // Since we can only compute the number of bits in a byte with vcnt.8, we
4361     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4362     // and i64.
4363
4364     // Compute LSB - 1.
4365     SDValue Bits;
4366     if (ElemTy == MVT::i64) {
4367       // Load constant 0xffff'ffff'ffff'ffff to register.
4368       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4369                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4370       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4371     } else {
4372       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4373                                 DAG.getTargetConstant(1, dl, ElemTy));
4374       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4375     }
4376
4377     // Count #bits with vcnt.8.
4378     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4379     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4380     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4381
4382     // Gather the #bits with vpaddl (pairwise add.)
4383     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4384     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4385         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4386         Cnt8);
4387     if (ElemTy == MVT::i16)
4388       return Cnt16;
4389
4390     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4391     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4392         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4393         Cnt16);
4394     if (ElemTy == MVT::i32)
4395       return Cnt32;
4396
4397     assert(ElemTy == MVT::i64);
4398     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4399         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4400         Cnt32);
4401     return Cnt64;
4402   }
4403
4404   if (!ST->hasV6T2Ops())
4405     return SDValue();
4406
4407   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4408   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4409 }
4410
4411 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4412 /// for each 16-bit element from operand, repeated.  The basic idea is to
4413 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4414 ///
4415 /// Trace for v4i16:
4416 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4417 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4418 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4419 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4420 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4421 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4422 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4423 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4424 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4425   EVT VT = N->getValueType(0);
4426   SDLoc DL(N);
4427
4428   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4429   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4430   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4431   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4432   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4433   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4434 }
4435
4436 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4437 /// bit-count for each 16-bit element from the operand.  We need slightly
4438 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4439 /// 64/128-bit registers.
4440 ///
4441 /// Trace for v4i16:
4442 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4443 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4444 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4445 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4446 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4447   EVT VT = N->getValueType(0);
4448   SDLoc DL(N);
4449
4450   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4451   if (VT.is64BitVector()) {
4452     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4453     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4454                        DAG.getIntPtrConstant(0, DL));
4455   } else {
4456     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4457                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4458     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4459   }
4460 }
4461
4462 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4463 /// bit-count for each 32-bit element from the operand.  The idea here is
4464 /// to split the vector into 16-bit elements, leverage the 16-bit count
4465 /// routine, and then combine the results.
4466 ///
4467 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4468 /// input    = [v0    v1    ] (vi: 32-bit elements)
4469 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4470 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4471 /// vrev: N0 = [k1 k0 k3 k2 ]
4472 ///            [k0 k1 k2 k3 ]
4473 ///       N1 =+[k1 k0 k3 k2 ]
4474 ///            [k0 k2 k1 k3 ]
4475 ///       N2 =+[k1 k3 k0 k2 ]
4476 ///            [k0    k2    k1    k3    ]
4477 /// Extended =+[k1    k3    k0    k2    ]
4478 ///            [k0    k2    ]
4479 /// Extracted=+[k1    k3    ]
4480 ///
4481 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4482   EVT VT = N->getValueType(0);
4483   SDLoc DL(N);
4484
4485   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4486
4487   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4488   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4489   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4490   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4491   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4492
4493   if (VT.is64BitVector()) {
4494     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4495     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4496                        DAG.getIntPtrConstant(0, DL));
4497   } else {
4498     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4499                                     DAG.getIntPtrConstant(0, DL));
4500     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4501   }
4502 }
4503
4504 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4505                           const ARMSubtarget *ST) {
4506   EVT VT = N->getValueType(0);
4507
4508   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4509   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4510           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4511          "Unexpected type for custom ctpop lowering");
4512
4513   if (VT.getVectorElementType() == MVT::i32)
4514     return lowerCTPOP32BitElements(N, DAG);
4515   else
4516     return lowerCTPOP16BitElements(N, DAG);
4517 }
4518
4519 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4520                           const ARMSubtarget *ST) {
4521   EVT VT = N->getValueType(0);
4522   SDLoc dl(N);
4523
4524   if (!VT.isVector())
4525     return SDValue();
4526
4527   // Lower vector shifts on NEON to use VSHL.
4528   assert(ST->hasNEON() && "unexpected vector shift");
4529
4530   // Left shifts translate directly to the vshiftu intrinsic.
4531   if (N->getOpcode() == ISD::SHL)
4532     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4533                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4534                                        MVT::i32),
4535                        N->getOperand(0), N->getOperand(1));
4536
4537   assert((N->getOpcode() == ISD::SRA ||
4538           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4539
4540   // NEON uses the same intrinsics for both left and right shifts.  For
4541   // right shifts, the shift amounts are negative, so negate the vector of
4542   // shift amounts.
4543   EVT ShiftVT = N->getOperand(1).getValueType();
4544   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4545                                      getZeroVector(ShiftVT, DAG, dl),
4546                                      N->getOperand(1));
4547   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4548                              Intrinsic::arm_neon_vshifts :
4549                              Intrinsic::arm_neon_vshiftu);
4550   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4551                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4552                      N->getOperand(0), NegatedCount);
4553 }
4554
4555 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4556                                 const ARMSubtarget *ST) {
4557   EVT VT = N->getValueType(0);
4558   SDLoc dl(N);
4559
4560   // We can get here for a node like i32 = ISD::SHL i32, i64
4561   if (VT != MVT::i64)
4562     return SDValue();
4563
4564   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4565          "Unknown shift to lower!");
4566
4567   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4568   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4569       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4570     return SDValue();
4571
4572   // If we are in thumb mode, we don't have RRX.
4573   if (ST->isThumb1Only()) return SDValue();
4574
4575   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4576   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4577                            DAG.getConstant(0, dl, MVT::i32));
4578   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4579                            DAG.getConstant(1, dl, MVT::i32));
4580
4581   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4582   // captures the result into a carry flag.
4583   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4584   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4585
4586   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4587   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4588
4589   // Merge the pieces into a single i64 value.
4590  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4591 }
4592
4593 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4594   SDValue TmpOp0, TmpOp1;
4595   bool Invert = false;
4596   bool Swap = false;
4597   unsigned Opc = 0;
4598
4599   SDValue Op0 = Op.getOperand(0);
4600   SDValue Op1 = Op.getOperand(1);
4601   SDValue CC = Op.getOperand(2);
4602   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4603   EVT VT = Op.getValueType();
4604   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4605   SDLoc dl(Op);
4606
4607   if (Op1.getValueType().isFloatingPoint()) {
4608     switch (SetCCOpcode) {
4609     default: llvm_unreachable("Illegal FP comparison");
4610     case ISD::SETUNE:
4611     case ISD::SETNE:  Invert = true; // Fallthrough
4612     case ISD::SETOEQ:
4613     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4614     case ISD::SETOLT:
4615     case ISD::SETLT: Swap = true; // Fallthrough
4616     case ISD::SETOGT:
4617     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4618     case ISD::SETOLE:
4619     case ISD::SETLE:  Swap = true; // Fallthrough
4620     case ISD::SETOGE:
4621     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4622     case ISD::SETUGE: Swap = true; // Fallthrough
4623     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4624     case ISD::SETUGT: Swap = true; // Fallthrough
4625     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4626     case ISD::SETUEQ: Invert = true; // Fallthrough
4627     case ISD::SETONE:
4628       // Expand this to (OLT | OGT).
4629       TmpOp0 = Op0;
4630       TmpOp1 = Op1;
4631       Opc = ISD::OR;
4632       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4633       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4634       break;
4635     case ISD::SETUO: Invert = true; // Fallthrough
4636     case ISD::SETO:
4637       // Expand this to (OLT | OGE).
4638       TmpOp0 = Op0;
4639       TmpOp1 = Op1;
4640       Opc = ISD::OR;
4641       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4642       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4643       break;
4644     }
4645   } else {
4646     // Integer comparisons.
4647     switch (SetCCOpcode) {
4648     default: llvm_unreachable("Illegal integer comparison");
4649     case ISD::SETNE:  Invert = true;
4650     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4651     case ISD::SETLT:  Swap = true;
4652     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4653     case ISD::SETLE:  Swap = true;
4654     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4655     case ISD::SETULT: Swap = true;
4656     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4657     case ISD::SETULE: Swap = true;
4658     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4659     }
4660
4661     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4662     if (Opc == ARMISD::VCEQ) {
4663
4664       SDValue AndOp;
4665       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4666         AndOp = Op0;
4667       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4668         AndOp = Op1;
4669
4670       // Ignore bitconvert.
4671       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4672         AndOp = AndOp.getOperand(0);
4673
4674       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4675         Opc = ARMISD::VTST;
4676         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4677         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4678         Invert = !Invert;
4679       }
4680     }
4681   }
4682
4683   if (Swap)
4684     std::swap(Op0, Op1);
4685
4686   // If one of the operands is a constant vector zero, attempt to fold the
4687   // comparison to a specialized compare-against-zero form.
4688   SDValue SingleOp;
4689   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4690     SingleOp = Op0;
4691   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4692     if (Opc == ARMISD::VCGE)
4693       Opc = ARMISD::VCLEZ;
4694     else if (Opc == ARMISD::VCGT)
4695       Opc = ARMISD::VCLTZ;
4696     SingleOp = Op1;
4697   }
4698
4699   SDValue Result;
4700   if (SingleOp.getNode()) {
4701     switch (Opc) {
4702     case ARMISD::VCEQ:
4703       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4704     case ARMISD::VCGE:
4705       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4706     case ARMISD::VCLEZ:
4707       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4708     case ARMISD::VCGT:
4709       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4710     case ARMISD::VCLTZ:
4711       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4712     default:
4713       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4714     }
4715   } else {
4716      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4717   }
4718
4719   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4720
4721   if (Invert)
4722     Result = DAG.getNOT(dl, Result, VT);
4723
4724   return Result;
4725 }
4726
4727 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4728 /// valid vector constant for a NEON instruction with a "modified immediate"
4729 /// operand (e.g., VMOV).  If so, return the encoded value.
4730 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4731                                  unsigned SplatBitSize, SelectionDAG &DAG,
4732                                  SDLoc dl, EVT &VT, bool is128Bits,
4733                                  NEONModImmType type) {
4734   unsigned OpCmode, Imm;
4735
4736   // SplatBitSize is set to the smallest size that splats the vector, so a
4737   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4738   // immediate instructions others than VMOV do not support the 8-bit encoding
4739   // of a zero vector, and the default encoding of zero is supposed to be the
4740   // 32-bit version.
4741   if (SplatBits == 0)
4742     SplatBitSize = 32;
4743
4744   switch (SplatBitSize) {
4745   case 8:
4746     if (type != VMOVModImm)
4747       return SDValue();
4748     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4749     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4750     OpCmode = 0xe;
4751     Imm = SplatBits;
4752     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4753     break;
4754
4755   case 16:
4756     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4757     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4758     if ((SplatBits & ~0xff) == 0) {
4759       // Value = 0x00nn: Op=x, Cmode=100x.
4760       OpCmode = 0x8;
4761       Imm = SplatBits;
4762       break;
4763     }
4764     if ((SplatBits & ~0xff00) == 0) {
4765       // Value = 0xnn00: Op=x, Cmode=101x.
4766       OpCmode = 0xa;
4767       Imm = SplatBits >> 8;
4768       break;
4769     }
4770     return SDValue();
4771
4772   case 32:
4773     // NEON's 32-bit VMOV supports splat values where:
4774     // * only one byte is nonzero, or
4775     // * the least significant byte is 0xff and the second byte is nonzero, or
4776     // * the least significant 2 bytes are 0xff and the third is nonzero.
4777     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4778     if ((SplatBits & ~0xff) == 0) {
4779       // Value = 0x000000nn: Op=x, Cmode=000x.
4780       OpCmode = 0;
4781       Imm = SplatBits;
4782       break;
4783     }
4784     if ((SplatBits & ~0xff00) == 0) {
4785       // Value = 0x0000nn00: Op=x, Cmode=001x.
4786       OpCmode = 0x2;
4787       Imm = SplatBits >> 8;
4788       break;
4789     }
4790     if ((SplatBits & ~0xff0000) == 0) {
4791       // Value = 0x00nn0000: Op=x, Cmode=010x.
4792       OpCmode = 0x4;
4793       Imm = SplatBits >> 16;
4794       break;
4795     }
4796     if ((SplatBits & ~0xff000000) == 0) {
4797       // Value = 0xnn000000: Op=x, Cmode=011x.
4798       OpCmode = 0x6;
4799       Imm = SplatBits >> 24;
4800       break;
4801     }
4802
4803     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4804     if (type == OtherModImm) return SDValue();
4805
4806     if ((SplatBits & ~0xffff) == 0 &&
4807         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4808       // Value = 0x0000nnff: Op=x, Cmode=1100.
4809       OpCmode = 0xc;
4810       Imm = SplatBits >> 8;
4811       break;
4812     }
4813
4814     if ((SplatBits & ~0xffffff) == 0 &&
4815         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4816       // Value = 0x00nnffff: Op=x, Cmode=1101.
4817       OpCmode = 0xd;
4818       Imm = SplatBits >> 16;
4819       break;
4820     }
4821
4822     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4823     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4824     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4825     // and fall through here to test for a valid 64-bit splat.  But, then the
4826     // caller would also need to check and handle the change in size.
4827     return SDValue();
4828
4829   case 64: {
4830     if (type != VMOVModImm)
4831       return SDValue();
4832     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4833     uint64_t BitMask = 0xff;
4834     uint64_t Val = 0;
4835     unsigned ImmMask = 1;
4836     Imm = 0;
4837     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4838       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4839         Val |= BitMask;
4840         Imm |= ImmMask;
4841       } else if ((SplatBits & BitMask) != 0) {
4842         return SDValue();
4843       }
4844       BitMask <<= 8;
4845       ImmMask <<= 1;
4846     }
4847
4848     if (DAG.getDataLayout().isBigEndian())
4849       // swap higher and lower 32 bit word
4850       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4851
4852     // Op=1, Cmode=1110.
4853     OpCmode = 0x1e;
4854     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4855     break;
4856   }
4857
4858   default:
4859     llvm_unreachable("unexpected size for isNEONModifiedImm");
4860   }
4861
4862   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4863   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4864 }
4865
4866 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4867                                            const ARMSubtarget *ST) const {
4868   if (!ST->hasVFP3())
4869     return SDValue();
4870
4871   bool IsDouble = Op.getValueType() == MVT::f64;
4872   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4873
4874   // Use the default (constant pool) lowering for double constants when we have
4875   // an SP-only FPU
4876   if (IsDouble && Subtarget->isFPOnlySP())
4877     return SDValue();
4878
4879   // Try splatting with a VMOV.f32...
4880   APFloat FPVal = CFP->getValueAPF();
4881   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4882
4883   if (ImmVal != -1) {
4884     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4885       // We have code in place to select a valid ConstantFP already, no need to
4886       // do any mangling.
4887       return Op;
4888     }
4889
4890     // It's a float and we are trying to use NEON operations where
4891     // possible. Lower it to a splat followed by an extract.
4892     SDLoc DL(Op);
4893     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4894     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4895                                       NewVal);
4896     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4897                        DAG.getConstant(0, DL, MVT::i32));
4898   }
4899
4900   // The rest of our options are NEON only, make sure that's allowed before
4901   // proceeding..
4902   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4903     return SDValue();
4904
4905   EVT VMovVT;
4906   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4907
4908   // It wouldn't really be worth bothering for doubles except for one very
4909   // important value, which does happen to match: 0.0. So make sure we don't do
4910   // anything stupid.
4911   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4912     return SDValue();
4913
4914   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4915   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4916                                      VMovVT, false, VMOVModImm);
4917   if (NewVal != SDValue()) {
4918     SDLoc DL(Op);
4919     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4920                                       NewVal);
4921     if (IsDouble)
4922       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4923
4924     // It's a float: cast and extract a vector element.
4925     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4926                                        VecConstant);
4927     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4928                        DAG.getConstant(0, DL, MVT::i32));
4929   }
4930
4931   // Finally, try a VMVN.i32
4932   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4933                              false, VMVNModImm);
4934   if (NewVal != SDValue()) {
4935     SDLoc DL(Op);
4936     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4937
4938     if (IsDouble)
4939       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4940
4941     // It's a float: cast and extract a vector element.
4942     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4943                                        VecConstant);
4944     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4945                        DAG.getConstant(0, DL, MVT::i32));
4946   }
4947
4948   return SDValue();
4949 }
4950
4951 // check if an VEXT instruction can handle the shuffle mask when the
4952 // vector sources of the shuffle are the same.
4953 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4954   unsigned NumElts = VT.getVectorNumElements();
4955
4956   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4957   if (M[0] < 0)
4958     return false;
4959
4960   Imm = M[0];
4961
4962   // If this is a VEXT shuffle, the immediate value is the index of the first
4963   // element.  The other shuffle indices must be the successive elements after
4964   // the first one.
4965   unsigned ExpectedElt = Imm;
4966   for (unsigned i = 1; i < NumElts; ++i) {
4967     // Increment the expected index.  If it wraps around, just follow it
4968     // back to index zero and keep going.
4969     ++ExpectedElt;
4970     if (ExpectedElt == NumElts)
4971       ExpectedElt = 0;
4972
4973     if (M[i] < 0) continue; // ignore UNDEF indices
4974     if (ExpectedElt != static_cast<unsigned>(M[i]))
4975       return false;
4976   }
4977
4978   return true;
4979 }
4980
4981
4982 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4983                        bool &ReverseVEXT, unsigned &Imm) {
4984   unsigned NumElts = VT.getVectorNumElements();
4985   ReverseVEXT = false;
4986
4987   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4988   if (M[0] < 0)
4989     return false;
4990
4991   Imm = M[0];
4992
4993   // If this is a VEXT shuffle, the immediate value is the index of the first
4994   // element.  The other shuffle indices must be the successive elements after
4995   // the first one.
4996   unsigned ExpectedElt = Imm;
4997   for (unsigned i = 1; i < NumElts; ++i) {
4998     // Increment the expected index.  If it wraps around, it may still be
4999     // a VEXT but the source vectors must be swapped.
5000     ExpectedElt += 1;
5001     if (ExpectedElt == NumElts * 2) {
5002       ExpectedElt = 0;
5003       ReverseVEXT = true;
5004     }
5005
5006     if (M[i] < 0) continue; // ignore UNDEF indices
5007     if (ExpectedElt != static_cast<unsigned>(M[i]))
5008       return false;
5009   }
5010
5011   // Adjust the index value if the source operands will be swapped.
5012   if (ReverseVEXT)
5013     Imm -= NumElts;
5014
5015   return true;
5016 }
5017
5018 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5019 /// instruction with the specified blocksize.  (The order of the elements
5020 /// within each block of the vector is reversed.)
5021 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5022   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5023          "Only possible block sizes for VREV are: 16, 32, 64");
5024
5025   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5026   if (EltSz == 64)
5027     return false;
5028
5029   unsigned NumElts = VT.getVectorNumElements();
5030   unsigned BlockElts = M[0] + 1;
5031   // If the first shuffle index is UNDEF, be optimistic.
5032   if (M[0] < 0)
5033     BlockElts = BlockSize / EltSz;
5034
5035   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5036     return false;
5037
5038   for (unsigned i = 0; i < NumElts; ++i) {
5039     if (M[i] < 0) continue; // ignore UNDEF indices
5040     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5041       return false;
5042   }
5043
5044   return true;
5045 }
5046
5047 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5048   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5049   // range, then 0 is placed into the resulting vector. So pretty much any mask
5050   // of 8 elements can work here.
5051   return VT == MVT::v8i8 && M.size() == 8;
5052 }
5053
5054 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5055 // checking that pairs of elements in the shuffle mask represent the same index
5056 // in each vector, incrementing the expected index by 2 at each step.
5057 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5058 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5059 //  v2={e,f,g,h}
5060 // WhichResult gives the offset for each element in the mask based on which
5061 // of the two results it belongs to.
5062 //
5063 // The transpose can be represented either as:
5064 // result1 = shufflevector v1, v2, result1_shuffle_mask
5065 // result2 = shufflevector v1, v2, result2_shuffle_mask
5066 // where v1/v2 and the shuffle masks have the same number of elements
5067 // (here WhichResult (see below) indicates which result is being checked)
5068 //
5069 // or as:
5070 // results = shufflevector v1, v2, shuffle_mask
5071 // where both results are returned in one vector and the shuffle mask has twice
5072 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5073 // want to check the low half and high half of the shuffle mask as if it were
5074 // the other case
5075 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5076   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5077   if (EltSz == 64)
5078     return false;
5079
5080   unsigned NumElts = VT.getVectorNumElements();
5081   if (M.size() != NumElts && M.size() != NumElts*2)
5082     return false;
5083
5084   // If the mask is twice as long as the result then we need to check the upper
5085   // and lower parts of the mask
5086   for (unsigned i = 0; i < M.size(); i += NumElts) {
5087     WhichResult = M[i] == 0 ? 0 : 1;
5088     for (unsigned j = 0; j < NumElts; j += 2) {
5089       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5090           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5091         return false;
5092     }
5093   }
5094
5095   if (M.size() == NumElts*2)
5096     WhichResult = 0;
5097
5098   return true;
5099 }
5100
5101 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5102 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5103 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5104 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5105   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5106   if (EltSz == 64)
5107     return false;
5108
5109   unsigned NumElts = VT.getVectorNumElements();
5110   if (M.size() != NumElts && M.size() != NumElts*2)
5111     return false;
5112
5113   for (unsigned i = 0; i < M.size(); i += NumElts) {
5114     WhichResult = M[i] == 0 ? 0 : 1;
5115     for (unsigned j = 0; j < NumElts; j += 2) {
5116       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5117           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5118         return false;
5119     }
5120   }
5121
5122   if (M.size() == NumElts*2)
5123     WhichResult = 0;
5124
5125   return true;
5126 }
5127
5128 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5129 // that the mask elements are either all even and in steps of size 2 or all odd
5130 // and in steps of size 2.
5131 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5132 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5133 //  v2={e,f,g,h}
5134 // Requires similar checks to that of isVTRNMask with
5135 // respect the how results are returned.
5136 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5137   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5138   if (EltSz == 64)
5139     return false;
5140
5141   unsigned NumElts = VT.getVectorNumElements();
5142   if (M.size() != NumElts && M.size() != NumElts*2)
5143     return false;
5144
5145   for (unsigned i = 0; i < M.size(); i += NumElts) {
5146     WhichResult = M[i] == 0 ? 0 : 1;
5147     for (unsigned j = 0; j < NumElts; ++j) {
5148       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5149         return false;
5150     }
5151   }
5152
5153   if (M.size() == NumElts*2)
5154     WhichResult = 0;
5155
5156   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5157   if (VT.is64BitVector() && EltSz == 32)
5158     return false;
5159
5160   return true;
5161 }
5162
5163 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5164 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5165 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5166 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5167   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5168   if (EltSz == 64)
5169     return false;
5170
5171   unsigned NumElts = VT.getVectorNumElements();
5172   if (M.size() != NumElts && M.size() != NumElts*2)
5173     return false;
5174
5175   unsigned Half = NumElts / 2;
5176   for (unsigned i = 0; i < M.size(); i += NumElts) {
5177     WhichResult = M[i] == 0 ? 0 : 1;
5178     for (unsigned j = 0; j < NumElts; j += Half) {
5179       unsigned Idx = WhichResult;
5180       for (unsigned k = 0; k < Half; ++k) {
5181         int MIdx = M[i + j + k];
5182         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5183           return false;
5184         Idx += 2;
5185       }
5186     }
5187   }
5188
5189   if (M.size() == NumElts*2)
5190     WhichResult = 0;
5191
5192   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5193   if (VT.is64BitVector() && EltSz == 32)
5194     return false;
5195
5196   return true;
5197 }
5198
5199 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5200 // that pairs of elements of the shufflemask represent the same index in each
5201 // vector incrementing sequentially through the vectors.
5202 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5203 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5204 //  v2={e,f,g,h}
5205 // Requires similar checks to that of isVTRNMask with respect the how results
5206 // are returned.
5207 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5208   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5209   if (EltSz == 64)
5210     return false;
5211
5212   unsigned NumElts = VT.getVectorNumElements();
5213   if (M.size() != NumElts && M.size() != NumElts*2)
5214     return false;
5215
5216   for (unsigned i = 0; i < M.size(); i += NumElts) {
5217     WhichResult = M[i] == 0 ? 0 : 1;
5218     unsigned Idx = WhichResult * NumElts / 2;
5219     for (unsigned j = 0; j < NumElts; j += 2) {
5220       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5221           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5222         return false;
5223       Idx += 1;
5224     }
5225   }
5226
5227   if (M.size() == NumElts*2)
5228     WhichResult = 0;
5229
5230   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5231   if (VT.is64BitVector() && EltSz == 32)
5232     return false;
5233
5234   return true;
5235 }
5236
5237 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5238 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5239 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5240 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5241   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5242   if (EltSz == 64)
5243     return false;
5244
5245   unsigned NumElts = VT.getVectorNumElements();
5246   if (M.size() != NumElts && M.size() != NumElts*2)
5247     return false;
5248
5249   for (unsigned i = 0; i < M.size(); i += NumElts) {
5250     WhichResult = M[i] == 0 ? 0 : 1;
5251     unsigned Idx = WhichResult * NumElts / 2;
5252     for (unsigned j = 0; j < NumElts; j += 2) {
5253       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5254           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5255         return false;
5256       Idx += 1;
5257     }
5258   }
5259
5260   if (M.size() == NumElts*2)
5261     WhichResult = 0;
5262
5263   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5264   if (VT.is64BitVector() && EltSz == 32)
5265     return false;
5266
5267   return true;
5268 }
5269
5270 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5271 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5272 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5273                                            unsigned &WhichResult,
5274                                            bool &isV_UNDEF) {
5275   isV_UNDEF = false;
5276   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5277     return ARMISD::VTRN;
5278   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5279     return ARMISD::VUZP;
5280   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5281     return ARMISD::VZIP;
5282
5283   isV_UNDEF = true;
5284   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5285     return ARMISD::VTRN;
5286   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5287     return ARMISD::VUZP;
5288   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5289     return ARMISD::VZIP;
5290
5291   return 0;
5292 }
5293
5294 /// \return true if this is a reverse operation on an vector.
5295 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5296   unsigned NumElts = VT.getVectorNumElements();
5297   // Make sure the mask has the right size.
5298   if (NumElts != M.size())
5299       return false;
5300
5301   // Look for <15, ..., 3, -1, 1, 0>.
5302   for (unsigned i = 0; i != NumElts; ++i)
5303     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5304       return false;
5305
5306   return true;
5307 }
5308
5309 // If N is an integer constant that can be moved into a register in one
5310 // instruction, return an SDValue of such a constant (will become a MOV
5311 // instruction).  Otherwise return null.
5312 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5313                                      const ARMSubtarget *ST, SDLoc dl) {
5314   uint64_t Val;
5315   if (!isa<ConstantSDNode>(N))
5316     return SDValue();
5317   Val = cast<ConstantSDNode>(N)->getZExtValue();
5318
5319   if (ST->isThumb1Only()) {
5320     if (Val <= 255 || ~Val <= 255)
5321       return DAG.getConstant(Val, dl, MVT::i32);
5322   } else {
5323     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5324       return DAG.getConstant(Val, dl, MVT::i32);
5325   }
5326   return SDValue();
5327 }
5328
5329 // If this is a case we can't handle, return null and let the default
5330 // expansion code take care of it.
5331 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5332                                              const ARMSubtarget *ST) const {
5333   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5334   SDLoc dl(Op);
5335   EVT VT = Op.getValueType();
5336
5337   APInt SplatBits, SplatUndef;
5338   unsigned SplatBitSize;
5339   bool HasAnyUndefs;
5340   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5341     if (SplatBitSize <= 64) {
5342       // Check if an immediate VMOV works.
5343       EVT VmovVT;
5344       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5345                                       SplatUndef.getZExtValue(), SplatBitSize,
5346                                       DAG, dl, VmovVT, VT.is128BitVector(),
5347                                       VMOVModImm);
5348       if (Val.getNode()) {
5349         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5350         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5351       }
5352
5353       // Try an immediate VMVN.
5354       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5355       Val = isNEONModifiedImm(NegatedImm,
5356                                       SplatUndef.getZExtValue(), SplatBitSize,
5357                                       DAG, dl, VmovVT, VT.is128BitVector(),
5358                                       VMVNModImm);
5359       if (Val.getNode()) {
5360         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5361         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5362       }
5363
5364       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5365       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5366         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5367         if (ImmVal != -1) {
5368           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5369           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5370         }
5371       }
5372     }
5373   }
5374
5375   // Scan through the operands to see if only one value is used.
5376   //
5377   // As an optimisation, even if more than one value is used it may be more
5378   // profitable to splat with one value then change some lanes.
5379   //
5380   // Heuristically we decide to do this if the vector has a "dominant" value,
5381   // defined as splatted to more than half of the lanes.
5382   unsigned NumElts = VT.getVectorNumElements();
5383   bool isOnlyLowElement = true;
5384   bool usesOnlyOneValue = true;
5385   bool hasDominantValue = false;
5386   bool isConstant = true;
5387
5388   // Map of the number of times a particular SDValue appears in the
5389   // element list.
5390   DenseMap<SDValue, unsigned> ValueCounts;
5391   SDValue Value;
5392   for (unsigned i = 0; i < NumElts; ++i) {
5393     SDValue V = Op.getOperand(i);
5394     if (V.getOpcode() == ISD::UNDEF)
5395       continue;
5396     if (i > 0)
5397       isOnlyLowElement = false;
5398     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5399       isConstant = false;
5400
5401     ValueCounts.insert(std::make_pair(V, 0));
5402     unsigned &Count = ValueCounts[V];
5403
5404     // Is this value dominant? (takes up more than half of the lanes)
5405     if (++Count > (NumElts / 2)) {
5406       hasDominantValue = true;
5407       Value = V;
5408     }
5409   }
5410   if (ValueCounts.size() != 1)
5411     usesOnlyOneValue = false;
5412   if (!Value.getNode() && ValueCounts.size() > 0)
5413     Value = ValueCounts.begin()->first;
5414
5415   if (ValueCounts.size() == 0)
5416     return DAG.getUNDEF(VT);
5417
5418   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5419   // Keep going if we are hitting this case.
5420   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5421     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5422
5423   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5424
5425   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5426   // i32 and try again.
5427   if (hasDominantValue && EltSize <= 32) {
5428     if (!isConstant) {
5429       SDValue N;
5430
5431       // If we are VDUPing a value that comes directly from a vector, that will
5432       // cause an unnecessary move to and from a GPR, where instead we could
5433       // just use VDUPLANE. We can only do this if the lane being extracted
5434       // is at a constant index, as the VDUP from lane instructions only have
5435       // constant-index forms.
5436       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5437           isa<ConstantSDNode>(Value->getOperand(1))) {
5438         // We need to create a new undef vector to use for the VDUPLANE if the
5439         // size of the vector from which we get the value is different than the
5440         // size of the vector that we need to create. We will insert the element
5441         // such that the register coalescer will remove unnecessary copies.
5442         if (VT != Value->getOperand(0).getValueType()) {
5443           ConstantSDNode *constIndex;
5444           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5445           assert(constIndex && "The index is not a constant!");
5446           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5447                              VT.getVectorNumElements();
5448           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5449                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5450                         Value, DAG.getConstant(index, dl, MVT::i32)),
5451                            DAG.getConstant(index, dl, MVT::i32));
5452         } else
5453           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5454                         Value->getOperand(0), Value->getOperand(1));
5455       } else
5456         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5457
5458       if (!usesOnlyOneValue) {
5459         // The dominant value was splatted as 'N', but we now have to insert
5460         // all differing elements.
5461         for (unsigned I = 0; I < NumElts; ++I) {
5462           if (Op.getOperand(I) == Value)
5463             continue;
5464           SmallVector<SDValue, 3> Ops;
5465           Ops.push_back(N);
5466           Ops.push_back(Op.getOperand(I));
5467           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5468           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5469         }
5470       }
5471       return N;
5472     }
5473     if (VT.getVectorElementType().isFloatingPoint()) {
5474       SmallVector<SDValue, 8> Ops;
5475       for (unsigned i = 0; i < NumElts; ++i)
5476         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5477                                   Op.getOperand(i)));
5478       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5479       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5480       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5481       if (Val.getNode())
5482         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5483     }
5484     if (usesOnlyOneValue) {
5485       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5486       if (isConstant && Val.getNode())
5487         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5488     }
5489   }
5490
5491   // If all elements are constants and the case above didn't get hit, fall back
5492   // to the default expansion, which will generate a load from the constant
5493   // pool.
5494   if (isConstant)
5495     return SDValue();
5496
5497   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5498   if (NumElts >= 4) {
5499     SDValue shuffle = ReconstructShuffle(Op, DAG);
5500     if (shuffle != SDValue())
5501       return shuffle;
5502   }
5503
5504   // Vectors with 32- or 64-bit elements can be built by directly assigning
5505   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5506   // will be legalized.
5507   if (EltSize >= 32) {
5508     // Do the expansion with floating-point types, since that is what the VFP
5509     // registers are defined to use, and since i64 is not legal.
5510     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5511     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5512     SmallVector<SDValue, 8> Ops;
5513     for (unsigned i = 0; i < NumElts; ++i)
5514       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5515     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5516     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5517   }
5518
5519   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5520   // know the default expansion would otherwise fall back on something even
5521   // worse. For a vector with one or two non-undef values, that's
5522   // scalar_to_vector for the elements followed by a shuffle (provided the
5523   // shuffle is valid for the target) and materialization element by element
5524   // on the stack followed by a load for everything else.
5525   if (!isConstant && !usesOnlyOneValue) {
5526     SDValue Vec = DAG.getUNDEF(VT);
5527     for (unsigned i = 0 ; i < NumElts; ++i) {
5528       SDValue V = Op.getOperand(i);
5529       if (V.getOpcode() == ISD::UNDEF)
5530         continue;
5531       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5532       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5533     }
5534     return Vec;
5535   }
5536
5537   return SDValue();
5538 }
5539
5540 /// getExtFactor - Determine the adjustment factor for the position when
5541 /// generating an "extract from vector registers" instruction.
5542 static unsigned getExtFactor(SDValue &V) {
5543   EVT EltType = V.getValueType().getVectorElementType();
5544   return EltType.getSizeInBits() / 8;
5545 }
5546
5547 // Gather data to see if the operation can be modelled as a
5548 // shuffle in combination with VEXTs.
5549 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5550                                               SelectionDAG &DAG) const {
5551   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5552   SDLoc dl(Op);
5553   EVT VT = Op.getValueType();
5554   unsigned NumElts = VT.getVectorNumElements();
5555
5556   struct ShuffleSourceInfo {
5557     SDValue Vec;
5558     unsigned MinElt;
5559     unsigned MaxElt;
5560
5561     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5562     // be compatible with the shuffle we intend to construct. As a result
5563     // ShuffleVec will be some sliding window into the original Vec.
5564     SDValue ShuffleVec;
5565
5566     // Code should guarantee that element i in Vec starts at element "WindowBase
5567     // + i * WindowScale in ShuffleVec".
5568     int WindowBase;
5569     int WindowScale;
5570
5571     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5572     ShuffleSourceInfo(SDValue Vec)
5573         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5574           WindowScale(1) {}
5575   };
5576
5577   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5578   // node.
5579   SmallVector<ShuffleSourceInfo, 2> Sources;
5580   for (unsigned i = 0; i < NumElts; ++i) {
5581     SDValue V = Op.getOperand(i);
5582     if (V.getOpcode() == ISD::UNDEF)
5583       continue;
5584     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5585       // A shuffle can only come from building a vector from various
5586       // elements of other vectors.
5587       return SDValue();
5588     }
5589
5590     // Add this element source to the list if it's not already there.
5591     SDValue SourceVec = V.getOperand(0);
5592     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5593     if (Source == Sources.end())
5594       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5595
5596     // Update the minimum and maximum lane number seen.
5597     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5598     Source->MinElt = std::min(Source->MinElt, EltNo);
5599     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5600   }
5601
5602   // Currently only do something sane when at most two source vectors
5603   // are involved.
5604   if (Sources.size() > 2)
5605     return SDValue();
5606
5607   // Find out the smallest element size among result and two sources, and use
5608   // it as element size to build the shuffle_vector.
5609   EVT SmallestEltTy = VT.getVectorElementType();
5610   for (auto &Source : Sources) {
5611     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5612     if (SrcEltTy.bitsLT(SmallestEltTy))
5613       SmallestEltTy = SrcEltTy;
5614   }
5615   unsigned ResMultiplier =
5616       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5617   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5618   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5619
5620   // If the source vector is too wide or too narrow, we may nevertheless be able
5621   // to construct a compatible shuffle either by concatenating it with UNDEF or
5622   // extracting a suitable range of elements.
5623   for (auto &Src : Sources) {
5624     EVT SrcVT = Src.ShuffleVec.getValueType();
5625
5626     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5627       continue;
5628
5629     // This stage of the search produces a source with the same element type as
5630     // the original, but with a total width matching the BUILD_VECTOR output.
5631     EVT EltVT = SrcVT.getVectorElementType();
5632     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5633     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5634
5635     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5636       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5637         return SDValue();
5638       // We can pad out the smaller vector for free, so if it's part of a
5639       // shuffle...
5640       Src.ShuffleVec =
5641           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5642                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5643       continue;
5644     }
5645
5646     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5647       return SDValue();
5648
5649     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5650       // Span too large for a VEXT to cope
5651       return SDValue();
5652     }
5653
5654     if (Src.MinElt >= NumSrcElts) {
5655       // The extraction can just take the second half
5656       Src.ShuffleVec =
5657           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5658                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5659       Src.WindowBase = -NumSrcElts;
5660     } else if (Src.MaxElt < NumSrcElts) {
5661       // The extraction can just take the first half
5662       Src.ShuffleVec =
5663           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5664                       DAG.getConstant(0, dl, MVT::i32));
5665     } else {
5666       // An actual VEXT is needed
5667       SDValue VEXTSrc1 =
5668           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5669                       DAG.getConstant(0, dl, MVT::i32));
5670       SDValue VEXTSrc2 =
5671           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5672                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5673       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5674
5675       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5676                                    VEXTSrc2,
5677                                    DAG.getConstant(Imm, dl, MVT::i32));
5678       Src.WindowBase = -Src.MinElt;
5679     }
5680   }
5681
5682   // Another possible incompatibility occurs from the vector element types. We
5683   // can fix this by bitcasting the source vectors to the same type we intend
5684   // for the shuffle.
5685   for (auto &Src : Sources) {
5686     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5687     if (SrcEltTy == SmallestEltTy)
5688       continue;
5689     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5690     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5691     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5692     Src.WindowBase *= Src.WindowScale;
5693   }
5694
5695   // Final sanity check before we try to actually produce a shuffle.
5696   DEBUG(
5697     for (auto Src : Sources)
5698       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5699   );
5700
5701   // The stars all align, our next step is to produce the mask for the shuffle.
5702   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5703   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5704   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5705     SDValue Entry = Op.getOperand(i);
5706     if (Entry.getOpcode() == ISD::UNDEF)
5707       continue;
5708
5709     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5710     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5711
5712     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5713     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5714     // segment.
5715     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5716     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5717                                VT.getVectorElementType().getSizeInBits());
5718     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5719
5720     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5721     // starting at the appropriate offset.
5722     int *LaneMask = &Mask[i * ResMultiplier];
5723
5724     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5725     ExtractBase += NumElts * (Src - Sources.begin());
5726     for (int j = 0; j < LanesDefined; ++j)
5727       LaneMask[j] = ExtractBase + j;
5728   }
5729
5730   // Final check before we try to produce nonsense...
5731   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5732     return SDValue();
5733
5734   // We can't handle more than two sources. This should have already
5735   // been checked before this point.
5736   assert(Sources.size() <= 2 && "Too many sources!");
5737
5738   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5739   for (unsigned i = 0; i < Sources.size(); ++i)
5740     ShuffleOps[i] = Sources[i].ShuffleVec;
5741
5742   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5743                                          ShuffleOps[1], &Mask[0]);
5744   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5745 }
5746
5747 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5748 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5749 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5750 /// are assumed to be legal.
5751 bool
5752 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5753                                       EVT VT) const {
5754   if (VT.getVectorNumElements() == 4 &&
5755       (VT.is128BitVector() || VT.is64BitVector())) {
5756     unsigned PFIndexes[4];
5757     for (unsigned i = 0; i != 4; ++i) {
5758       if (M[i] < 0)
5759         PFIndexes[i] = 8;
5760       else
5761         PFIndexes[i] = M[i];
5762     }
5763
5764     // Compute the index in the perfect shuffle table.
5765     unsigned PFTableIndex =
5766       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5767     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5768     unsigned Cost = (PFEntry >> 30);
5769
5770     if (Cost <= 4)
5771       return true;
5772   }
5773
5774   bool ReverseVEXT, isV_UNDEF;
5775   unsigned Imm, WhichResult;
5776
5777   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5778   return (EltSize >= 32 ||
5779           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5780           isVREVMask(M, VT, 64) ||
5781           isVREVMask(M, VT, 32) ||
5782           isVREVMask(M, VT, 16) ||
5783           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5784           isVTBLMask(M, VT) ||
5785           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5786           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5787 }
5788
5789 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5790 /// the specified operations to build the shuffle.
5791 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5792                                       SDValue RHS, SelectionDAG &DAG,
5793                                       SDLoc dl) {
5794   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5795   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5796   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5797
5798   enum {
5799     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5800     OP_VREV,
5801     OP_VDUP0,
5802     OP_VDUP1,
5803     OP_VDUP2,
5804     OP_VDUP3,
5805     OP_VEXT1,
5806     OP_VEXT2,
5807     OP_VEXT3,
5808     OP_VUZPL, // VUZP, left result
5809     OP_VUZPR, // VUZP, right result
5810     OP_VZIPL, // VZIP, left result
5811     OP_VZIPR, // VZIP, right result
5812     OP_VTRNL, // VTRN, left result
5813     OP_VTRNR  // VTRN, right result
5814   };
5815
5816   if (OpNum == OP_COPY) {
5817     if (LHSID == (1*9+2)*9+3) return LHS;
5818     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5819     return RHS;
5820   }
5821
5822   SDValue OpLHS, OpRHS;
5823   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5824   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5825   EVT VT = OpLHS.getValueType();
5826
5827   switch (OpNum) {
5828   default: llvm_unreachable("Unknown shuffle opcode!");
5829   case OP_VREV:
5830     // VREV divides the vector in half and swaps within the half.
5831     if (VT.getVectorElementType() == MVT::i32 ||
5832         VT.getVectorElementType() == MVT::f32)
5833       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5834     // vrev <4 x i16> -> VREV32
5835     if (VT.getVectorElementType() == MVT::i16)
5836       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5837     // vrev <4 x i8> -> VREV16
5838     assert(VT.getVectorElementType() == MVT::i8);
5839     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5840   case OP_VDUP0:
5841   case OP_VDUP1:
5842   case OP_VDUP2:
5843   case OP_VDUP3:
5844     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5845                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5846   case OP_VEXT1:
5847   case OP_VEXT2:
5848   case OP_VEXT3:
5849     return DAG.getNode(ARMISD::VEXT, dl, VT,
5850                        OpLHS, OpRHS,
5851                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5852   case OP_VUZPL:
5853   case OP_VUZPR:
5854     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5855                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5856   case OP_VZIPL:
5857   case OP_VZIPR:
5858     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5859                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5860   case OP_VTRNL:
5861   case OP_VTRNR:
5862     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5863                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5864   }
5865 }
5866
5867 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5868                                        ArrayRef<int> ShuffleMask,
5869                                        SelectionDAG &DAG) {
5870   // Check to see if we can use the VTBL instruction.
5871   SDValue V1 = Op.getOperand(0);
5872   SDValue V2 = Op.getOperand(1);
5873   SDLoc DL(Op);
5874
5875   SmallVector<SDValue, 8> VTBLMask;
5876   for (ArrayRef<int>::iterator
5877          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5878     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5879
5880   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5881     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5882                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5883
5884   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5885                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5886 }
5887
5888 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5889                                                       SelectionDAG &DAG) {
5890   SDLoc DL(Op);
5891   SDValue OpLHS = Op.getOperand(0);
5892   EVT VT = OpLHS.getValueType();
5893
5894   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5895          "Expect an v8i16/v16i8 type");
5896   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5897   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5898   // extract the first 8 bytes into the top double word and the last 8 bytes
5899   // into the bottom double word. The v8i16 case is similar.
5900   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5901   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5902                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5903 }
5904
5905 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5906   SDValue V1 = Op.getOperand(0);
5907   SDValue V2 = Op.getOperand(1);
5908   SDLoc dl(Op);
5909   EVT VT = Op.getValueType();
5910   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5911
5912   // Convert shuffles that are directly supported on NEON to target-specific
5913   // DAG nodes, instead of keeping them as shuffles and matching them again
5914   // during code selection.  This is more efficient and avoids the possibility
5915   // of inconsistencies between legalization and selection.
5916   // FIXME: floating-point vectors should be canonicalized to integer vectors
5917   // of the same time so that they get CSEd properly.
5918   ArrayRef<int> ShuffleMask = SVN->getMask();
5919
5920   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5921   if (EltSize <= 32) {
5922     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5923       int Lane = SVN->getSplatIndex();
5924       // If this is undef splat, generate it via "just" vdup, if possible.
5925       if (Lane == -1) Lane = 0;
5926
5927       // Test if V1 is a SCALAR_TO_VECTOR.
5928       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5929         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5930       }
5931       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5932       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5933       // reaches it).
5934       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5935           !isa<ConstantSDNode>(V1.getOperand(0))) {
5936         bool IsScalarToVector = true;
5937         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5938           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5939             IsScalarToVector = false;
5940             break;
5941           }
5942         if (IsScalarToVector)
5943           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5944       }
5945       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5946                          DAG.getConstant(Lane, dl, MVT::i32));
5947     }
5948
5949     bool ReverseVEXT;
5950     unsigned Imm;
5951     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5952       if (ReverseVEXT)
5953         std::swap(V1, V2);
5954       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5955                          DAG.getConstant(Imm, dl, MVT::i32));
5956     }
5957
5958     if (isVREVMask(ShuffleMask, VT, 64))
5959       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5960     if (isVREVMask(ShuffleMask, VT, 32))
5961       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5962     if (isVREVMask(ShuffleMask, VT, 16))
5963       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5964
5965     if (V2->getOpcode() == ISD::UNDEF &&
5966         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5967       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5968                          DAG.getConstant(Imm, dl, MVT::i32));
5969     }
5970
5971     // Check for Neon shuffles that modify both input vectors in place.
5972     // If both results are used, i.e., if there are two shuffles with the same
5973     // source operands and with masks corresponding to both results of one of
5974     // these operations, DAG memoization will ensure that a single node is
5975     // used for both shuffles.
5976     unsigned WhichResult;
5977     bool isV_UNDEF;
5978     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5979             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5980       if (isV_UNDEF)
5981         V2 = V1;
5982       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5983           .getValue(WhichResult);
5984     }
5985
5986     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5987     // shuffles that produce a result larger than their operands with:
5988     //   shuffle(concat(v1, undef), concat(v2, undef))
5989     // ->
5990     //   shuffle(concat(v1, v2), undef)
5991     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5992     //
5993     // This is useful in the general case, but there are special cases where
5994     // native shuffles produce larger results: the two-result ops.
5995     //
5996     // Look through the concat when lowering them:
5997     //   shuffle(concat(v1, v2), undef)
5998     // ->
5999     //   concat(VZIP(v1, v2):0, :1)
6000     //
6001     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6002         V2->getOpcode() == ISD::UNDEF) {
6003       SDValue SubV1 = V1->getOperand(0);
6004       SDValue SubV2 = V1->getOperand(1);
6005       EVT SubVT = SubV1.getValueType();
6006
6007       // We expect these to have been canonicalized to -1.
6008       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6009         return i < (int)VT.getVectorNumElements();
6010       }) && "Unexpected shuffle index into UNDEF operand!");
6011
6012       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6013               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6014         if (isV_UNDEF)
6015           SubV2 = SubV1;
6016         assert((WhichResult == 0) &&
6017                "In-place shuffle of concat can only have one result!");
6018         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6019                                   SubV1, SubV2);
6020         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6021                            Res.getValue(1));
6022       }
6023     }
6024   }
6025
6026   // If the shuffle is not directly supported and it has 4 elements, use
6027   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6028   unsigned NumElts = VT.getVectorNumElements();
6029   if (NumElts == 4) {
6030     unsigned PFIndexes[4];
6031     for (unsigned i = 0; i != 4; ++i) {
6032       if (ShuffleMask[i] < 0)
6033         PFIndexes[i] = 8;
6034       else
6035         PFIndexes[i] = ShuffleMask[i];
6036     }
6037
6038     // Compute the index in the perfect shuffle table.
6039     unsigned PFTableIndex =
6040       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6041     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6042     unsigned Cost = (PFEntry >> 30);
6043
6044     if (Cost <= 4)
6045       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6046   }
6047
6048   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6049   if (EltSize >= 32) {
6050     // Do the expansion with floating-point types, since that is what the VFP
6051     // registers are defined to use, and since i64 is not legal.
6052     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6053     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6054     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6055     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6056     SmallVector<SDValue, 8> Ops;
6057     for (unsigned i = 0; i < NumElts; ++i) {
6058       if (ShuffleMask[i] < 0)
6059         Ops.push_back(DAG.getUNDEF(EltVT));
6060       else
6061         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6062                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6063                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6064                                                   dl, MVT::i32)));
6065     }
6066     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6067     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6068   }
6069
6070   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6071     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6072
6073   if (VT == MVT::v8i8) {
6074     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6075     if (NewOp.getNode())
6076       return NewOp;
6077   }
6078
6079   return SDValue();
6080 }
6081
6082 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6083   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6084   SDValue Lane = Op.getOperand(2);
6085   if (!isa<ConstantSDNode>(Lane))
6086     return SDValue();
6087
6088   return Op;
6089 }
6090
6091 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6092   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6093   SDValue Lane = Op.getOperand(1);
6094   if (!isa<ConstantSDNode>(Lane))
6095     return SDValue();
6096
6097   SDValue Vec = Op.getOperand(0);
6098   if (Op.getValueType() == MVT::i32 &&
6099       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6100     SDLoc dl(Op);
6101     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6102   }
6103
6104   return Op;
6105 }
6106
6107 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6108   // The only time a CONCAT_VECTORS operation can have legal types is when
6109   // two 64-bit vectors are concatenated to a 128-bit vector.
6110   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6111          "unexpected CONCAT_VECTORS");
6112   SDLoc dl(Op);
6113   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6114   SDValue Op0 = Op.getOperand(0);
6115   SDValue Op1 = Op.getOperand(1);
6116   if (Op0.getOpcode() != ISD::UNDEF)
6117     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6118                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6119                       DAG.getIntPtrConstant(0, dl));
6120   if (Op1.getOpcode() != ISD::UNDEF)
6121     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6122                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6123                       DAG.getIntPtrConstant(1, dl));
6124   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6125 }
6126
6127 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6128 /// element has been zero/sign-extended, depending on the isSigned parameter,
6129 /// from an integer type half its size.
6130 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6131                                    bool isSigned) {
6132   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6133   EVT VT = N->getValueType(0);
6134   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6135     SDNode *BVN = N->getOperand(0).getNode();
6136     if (BVN->getValueType(0) != MVT::v4i32 ||
6137         BVN->getOpcode() != ISD::BUILD_VECTOR)
6138       return false;
6139     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6140     unsigned HiElt = 1 - LoElt;
6141     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6142     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6143     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6144     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6145     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6146       return false;
6147     if (isSigned) {
6148       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6149           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6150         return true;
6151     } else {
6152       if (Hi0->isNullValue() && Hi1->isNullValue())
6153         return true;
6154     }
6155     return false;
6156   }
6157
6158   if (N->getOpcode() != ISD::BUILD_VECTOR)
6159     return false;
6160
6161   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6162     SDNode *Elt = N->getOperand(i).getNode();
6163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6164       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6165       unsigned HalfSize = EltSize / 2;
6166       if (isSigned) {
6167         if (!isIntN(HalfSize, C->getSExtValue()))
6168           return false;
6169       } else {
6170         if (!isUIntN(HalfSize, C->getZExtValue()))
6171           return false;
6172       }
6173       continue;
6174     }
6175     return false;
6176   }
6177
6178   return true;
6179 }
6180
6181 /// isSignExtended - Check if a node is a vector value that is sign-extended
6182 /// or a constant BUILD_VECTOR with sign-extended elements.
6183 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6184   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6185     return true;
6186   if (isExtendedBUILD_VECTOR(N, DAG, true))
6187     return true;
6188   return false;
6189 }
6190
6191 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6192 /// or a constant BUILD_VECTOR with zero-extended elements.
6193 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6194   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6195     return true;
6196   if (isExtendedBUILD_VECTOR(N, DAG, false))
6197     return true;
6198   return false;
6199 }
6200
6201 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6202   if (OrigVT.getSizeInBits() >= 64)
6203     return OrigVT;
6204
6205   assert(OrigVT.isSimple() && "Expecting a simple value type");
6206
6207   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6208   switch (OrigSimpleTy) {
6209   default: llvm_unreachable("Unexpected Vector Type");
6210   case MVT::v2i8:
6211   case MVT::v2i16:
6212      return MVT::v2i32;
6213   case MVT::v4i8:
6214     return  MVT::v4i16;
6215   }
6216 }
6217
6218 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6219 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6220 /// We insert the required extension here to get the vector to fill a D register.
6221 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6222                                             const EVT &OrigTy,
6223                                             const EVT &ExtTy,
6224                                             unsigned ExtOpcode) {
6225   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6226   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6227   // 64-bits we need to insert a new extension so that it will be 64-bits.
6228   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6229   if (OrigTy.getSizeInBits() >= 64)
6230     return N;
6231
6232   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6233   EVT NewVT = getExtensionTo64Bits(OrigTy);
6234
6235   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6236 }
6237
6238 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6239 /// does not do any sign/zero extension. If the original vector is less
6240 /// than 64 bits, an appropriate extension will be added after the load to
6241 /// reach a total size of 64 bits. We have to add the extension separately
6242 /// because ARM does not have a sign/zero extending load for vectors.
6243 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6244   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6245
6246   // The load already has the right type.
6247   if (ExtendedTy == LD->getMemoryVT())
6248     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6249                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6250                 LD->isNonTemporal(), LD->isInvariant(),
6251                 LD->getAlignment());
6252
6253   // We need to create a zextload/sextload. We cannot just create a load
6254   // followed by a zext/zext node because LowerMUL is also run during normal
6255   // operation legalization where we can't create illegal types.
6256   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6257                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6258                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6259                         LD->isNonTemporal(), LD->getAlignment());
6260 }
6261
6262 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6263 /// extending load, or BUILD_VECTOR with extended elements, return the
6264 /// unextended value. The unextended vector should be 64 bits so that it can
6265 /// be used as an operand to a VMULL instruction. If the original vector size
6266 /// before extension is less than 64 bits we add a an extension to resize
6267 /// the vector to 64 bits.
6268 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6269   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6270     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6271                                         N->getOperand(0)->getValueType(0),
6272                                         N->getValueType(0),
6273                                         N->getOpcode());
6274
6275   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6276     return SkipLoadExtensionForVMULL(LD, DAG);
6277
6278   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6279   // have been legalized as a BITCAST from v4i32.
6280   if (N->getOpcode() == ISD::BITCAST) {
6281     SDNode *BVN = N->getOperand(0).getNode();
6282     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6283            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6284     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6285     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6286                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6287   }
6288   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6289   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6290   EVT VT = N->getValueType(0);
6291   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6292   unsigned NumElts = VT.getVectorNumElements();
6293   MVT TruncVT = MVT::getIntegerVT(EltSize);
6294   SmallVector<SDValue, 8> Ops;
6295   SDLoc dl(N);
6296   for (unsigned i = 0; i != NumElts; ++i) {
6297     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6298     const APInt &CInt = C->getAPIntValue();
6299     // Element types smaller than 32 bits are not legal, so use i32 elements.
6300     // The values are implicitly truncated so sext vs. zext doesn't matter.
6301     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6302   }
6303   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6304                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6305 }
6306
6307 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6308   unsigned Opcode = N->getOpcode();
6309   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6310     SDNode *N0 = N->getOperand(0).getNode();
6311     SDNode *N1 = N->getOperand(1).getNode();
6312     return N0->hasOneUse() && N1->hasOneUse() &&
6313       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6314   }
6315   return false;
6316 }
6317
6318 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6319   unsigned Opcode = N->getOpcode();
6320   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6321     SDNode *N0 = N->getOperand(0).getNode();
6322     SDNode *N1 = N->getOperand(1).getNode();
6323     return N0->hasOneUse() && N1->hasOneUse() &&
6324       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6325   }
6326   return false;
6327 }
6328
6329 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6330   // Multiplications are only custom-lowered for 128-bit vectors so that
6331   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6332   EVT VT = Op.getValueType();
6333   assert(VT.is128BitVector() && VT.isInteger() &&
6334          "unexpected type for custom-lowering ISD::MUL");
6335   SDNode *N0 = Op.getOperand(0).getNode();
6336   SDNode *N1 = Op.getOperand(1).getNode();
6337   unsigned NewOpc = 0;
6338   bool isMLA = false;
6339   bool isN0SExt = isSignExtended(N0, DAG);
6340   bool isN1SExt = isSignExtended(N1, DAG);
6341   if (isN0SExt && isN1SExt)
6342     NewOpc = ARMISD::VMULLs;
6343   else {
6344     bool isN0ZExt = isZeroExtended(N0, DAG);
6345     bool isN1ZExt = isZeroExtended(N1, DAG);
6346     if (isN0ZExt && isN1ZExt)
6347       NewOpc = ARMISD::VMULLu;
6348     else if (isN1SExt || isN1ZExt) {
6349       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6350       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6351       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6352         NewOpc = ARMISD::VMULLs;
6353         isMLA = true;
6354       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6355         NewOpc = ARMISD::VMULLu;
6356         isMLA = true;
6357       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6358         std::swap(N0, N1);
6359         NewOpc = ARMISD::VMULLu;
6360         isMLA = true;
6361       }
6362     }
6363
6364     if (!NewOpc) {
6365       if (VT == MVT::v2i64)
6366         // Fall through to expand this.  It is not legal.
6367         return SDValue();
6368       else
6369         // Other vector multiplications are legal.
6370         return Op;
6371     }
6372   }
6373
6374   // Legalize to a VMULL instruction.
6375   SDLoc DL(Op);
6376   SDValue Op0;
6377   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6378   if (!isMLA) {
6379     Op0 = SkipExtensionForVMULL(N0, DAG);
6380     assert(Op0.getValueType().is64BitVector() &&
6381            Op1.getValueType().is64BitVector() &&
6382            "unexpected types for extended operands to VMULL");
6383     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6384   }
6385
6386   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6387   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6388   //   vmull q0, d4, d6
6389   //   vmlal q0, d5, d6
6390   // is faster than
6391   //   vaddl q0, d4, d5
6392   //   vmovl q1, d6
6393   //   vmul  q0, q0, q1
6394   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6395   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6396   EVT Op1VT = Op1.getValueType();
6397   return DAG.getNode(N0->getOpcode(), DL, VT,
6398                      DAG.getNode(NewOpc, DL, VT,
6399                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6400                      DAG.getNode(NewOpc, DL, VT,
6401                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6402 }
6403
6404 static SDValue
6405 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6406   // Convert to float
6407   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6408   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6409   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6410   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6411   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6412   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6413   // Get reciprocal estimate.
6414   // float4 recip = vrecpeq_f32(yf);
6415   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6416                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6417                    Y);
6418   // Because char has a smaller range than uchar, we can actually get away
6419   // without any newton steps.  This requires that we use a weird bias
6420   // of 0xb000, however (again, this has been exhaustively tested).
6421   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6422   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6423   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6424   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6425   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6426   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6427   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6428   // Convert back to short.
6429   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6430   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6431   return X;
6432 }
6433
6434 static SDValue
6435 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6436   SDValue N2;
6437   // Convert to float.
6438   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6439   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6440   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6441   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6442   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6443   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6444
6445   // Use reciprocal estimate and one refinement step.
6446   // float4 recip = vrecpeq_f32(yf);
6447   // recip *= vrecpsq_f32(yf, recip);
6448   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6449                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6450                    N1);
6451   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6452                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6453                    N1, N2);
6454   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6455   // Because short has a smaller range than ushort, we can actually get away
6456   // with only a single newton step.  This requires that we use a weird bias
6457   // of 89, however (again, this has been exhaustively tested).
6458   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6459   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6460   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6461   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6462   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6463   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6464   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6465   // Convert back to integer and return.
6466   // return vmovn_s32(vcvt_s32_f32(result));
6467   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6468   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6469   return N0;
6470 }
6471
6472 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6473   EVT VT = Op.getValueType();
6474   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6475          "unexpected type for custom-lowering ISD::SDIV");
6476
6477   SDLoc dl(Op);
6478   SDValue N0 = Op.getOperand(0);
6479   SDValue N1 = Op.getOperand(1);
6480   SDValue N2, N3;
6481
6482   if (VT == MVT::v8i8) {
6483     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6484     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6485
6486     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6487                      DAG.getIntPtrConstant(4, dl));
6488     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6489                      DAG.getIntPtrConstant(4, dl));
6490     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6491                      DAG.getIntPtrConstant(0, dl));
6492     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6493                      DAG.getIntPtrConstant(0, dl));
6494
6495     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6496     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6497
6498     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6499     N0 = LowerCONCAT_VECTORS(N0, DAG);
6500
6501     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6502     return N0;
6503   }
6504   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6505 }
6506
6507 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6508   EVT VT = Op.getValueType();
6509   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6510          "unexpected type for custom-lowering ISD::UDIV");
6511
6512   SDLoc dl(Op);
6513   SDValue N0 = Op.getOperand(0);
6514   SDValue N1 = Op.getOperand(1);
6515   SDValue N2, N3;
6516
6517   if (VT == MVT::v8i8) {
6518     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6519     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6520
6521     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6522                      DAG.getIntPtrConstant(4, dl));
6523     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6524                      DAG.getIntPtrConstant(4, dl));
6525     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6526                      DAG.getIntPtrConstant(0, dl));
6527     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6528                      DAG.getIntPtrConstant(0, dl));
6529
6530     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6531     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6532
6533     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6534     N0 = LowerCONCAT_VECTORS(N0, DAG);
6535
6536     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6537                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6538                                      MVT::i32),
6539                      N0);
6540     return N0;
6541   }
6542
6543   // v4i16 sdiv ... Convert to float.
6544   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6545   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6546   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6547   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6548   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6549   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6550
6551   // Use reciprocal estimate and two refinement steps.
6552   // float4 recip = vrecpeq_f32(yf);
6553   // recip *= vrecpsq_f32(yf, recip);
6554   // recip *= vrecpsq_f32(yf, recip);
6555   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6556                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6557                    BN1);
6558   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6559                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6560                    BN1, N2);
6561   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6562   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6563                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6564                    BN1, N2);
6565   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6566   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6567   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6568   // and that it will never cause us to return an answer too large).
6569   // float4 result = as_float4(as_int4(xf*recip) + 2);
6570   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6571   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6572   N1 = DAG.getConstant(2, dl, MVT::i32);
6573   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6574   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6575   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6576   // Convert back to integer and return.
6577   // return vmovn_u32(vcvt_s32_f32(result));
6578   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6579   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6580   return N0;
6581 }
6582
6583 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6584   EVT VT = Op.getNode()->getValueType(0);
6585   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6586
6587   unsigned Opc;
6588   bool ExtraOp = false;
6589   switch (Op.getOpcode()) {
6590   default: llvm_unreachable("Invalid code");
6591   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6592   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6593   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6594   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6595   }
6596
6597   if (!ExtraOp)
6598     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6599                        Op.getOperand(1));
6600   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6601                      Op.getOperand(1), Op.getOperand(2));
6602 }
6603
6604 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6605   assert(Subtarget->isTargetDarwin());
6606
6607   // For iOS, we want to call an alternative entry point: __sincos_stret,
6608   // return values are passed via sret.
6609   SDLoc dl(Op);
6610   SDValue Arg = Op.getOperand(0);
6611   EVT ArgVT = Arg.getValueType();
6612   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6613   auto PtrVT = getPointerTy(DAG.getDataLayout());
6614
6615   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6616
6617   // Pair of floats / doubles used to pass the result.
6618   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6619
6620   // Create stack object for sret.
6621   auto &DL = DAG.getDataLayout();
6622   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6623   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6624   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6625   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6626
6627   ArgListTy Args;
6628   ArgListEntry Entry;
6629
6630   Entry.Node = SRet;
6631   Entry.Ty = RetTy->getPointerTo();
6632   Entry.isSExt = false;
6633   Entry.isZExt = false;
6634   Entry.isSRet = true;
6635   Args.push_back(Entry);
6636
6637   Entry.Node = Arg;
6638   Entry.Ty = ArgTy;
6639   Entry.isSExt = false;
6640   Entry.isZExt = false;
6641   Args.push_back(Entry);
6642
6643   const char *LibcallName  = (ArgVT == MVT::f64)
6644   ? "__sincos_stret" : "__sincosf_stret";
6645   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6646
6647   TargetLowering::CallLoweringInfo CLI(DAG);
6648   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6649     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6650                std::move(Args), 0)
6651     .setDiscardResult();
6652
6653   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6654
6655   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6656                                 MachinePointerInfo(), false, false, false, 0);
6657
6658   // Address of cos field.
6659   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6660                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6661   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6662                                 MachinePointerInfo(), false, false, false, 0);
6663
6664   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6665   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6666                      LoadSin.getValue(0), LoadCos.getValue(0));
6667 }
6668
6669 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6670   // Monotonic load/store is legal for all targets
6671   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6672     return Op;
6673
6674   // Acquire/Release load/store is not legal for targets without a
6675   // dmb or equivalent available.
6676   return SDValue();
6677 }
6678
6679 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6680                                     SmallVectorImpl<SDValue> &Results,
6681                                     SelectionDAG &DAG,
6682                                     const ARMSubtarget *Subtarget) {
6683   SDLoc DL(N);
6684   SDValue Cycles32, OutChain;
6685
6686   if (Subtarget->hasPerfMon()) {
6687     // Under Power Management extensions, the cycle-count is:
6688     //    mrc p15, #0, <Rt>, c9, c13, #0
6689     SDValue Ops[] = { N->getOperand(0), // Chain
6690                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6691                       DAG.getConstant(15, DL, MVT::i32),
6692                       DAG.getConstant(0, DL, MVT::i32),
6693                       DAG.getConstant(9, DL, MVT::i32),
6694                       DAG.getConstant(13, DL, MVT::i32),
6695                       DAG.getConstant(0, DL, MVT::i32)
6696     };
6697
6698     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6699                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6700     OutChain = Cycles32.getValue(1);
6701   } else {
6702     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6703     // there are older ARM CPUs that have implementation-specific ways of
6704     // obtaining this information (FIXME!).
6705     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6706     OutChain = DAG.getEntryNode();
6707   }
6708
6709
6710   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6711                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6712   Results.push_back(Cycles64);
6713   Results.push_back(OutChain);
6714 }
6715
6716 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6717   switch (Op.getOpcode()) {
6718   default: llvm_unreachable("Don't know how to custom lower this!");
6719   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6720   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6721   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6722   case ISD::GlobalAddress:
6723     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6724     default: llvm_unreachable("unknown object format");
6725     case Triple::COFF:
6726       return LowerGlobalAddressWindows(Op, DAG);
6727     case Triple::ELF:
6728       return LowerGlobalAddressELF(Op, DAG);
6729     case Triple::MachO:
6730       return LowerGlobalAddressDarwin(Op, DAG);
6731     }
6732   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6733   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6734   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6735   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6736   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6737   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6738   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6739   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6740   case ISD::SINT_TO_FP:
6741   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6742   case ISD::FP_TO_SINT:
6743   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6744   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6745   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6746   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6747   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6748   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6749   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6750   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6751   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6752                                                                Subtarget);
6753   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6754   case ISD::SHL:
6755   case ISD::SRL:
6756   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6757   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6758   case ISD::SRL_PARTS:
6759   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6760   case ISD::CTTZ:
6761   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6762   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6763   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6764   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6765   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6766   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6767   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6768   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6769   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6770   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6771   case ISD::MUL:           return LowerMUL(Op, DAG);
6772   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6773   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6774   case ISD::ADDC:
6775   case ISD::ADDE:
6776   case ISD::SUBC:
6777   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6778   case ISD::SADDO:
6779   case ISD::UADDO:
6780   case ISD::SSUBO:
6781   case ISD::USUBO:
6782     return LowerXALUO(Op, DAG);
6783   case ISD::ATOMIC_LOAD:
6784   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6785   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6786   case ISD::SDIVREM:
6787   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6788   case ISD::DYNAMIC_STACKALLOC:
6789     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6790       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6791     llvm_unreachable("Don't know how to custom lower this!");
6792   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6793   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6794   }
6795 }
6796
6797 /// ReplaceNodeResults - Replace the results of node with an illegal result
6798 /// type with new values built out of custom code.
6799 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6800                                            SmallVectorImpl<SDValue>&Results,
6801                                            SelectionDAG &DAG) const {
6802   SDValue Res;
6803   switch (N->getOpcode()) {
6804   default:
6805     llvm_unreachable("Don't know how to custom expand this!");
6806   case ISD::READ_REGISTER:
6807     ExpandREAD_REGISTER(N, Results, DAG);
6808     break;
6809   case ISD::BITCAST:
6810     Res = ExpandBITCAST(N, DAG);
6811     break;
6812   case ISD::SRL:
6813   case ISD::SRA:
6814     Res = Expand64BitShift(N, DAG, Subtarget);
6815     break;
6816   case ISD::READCYCLECOUNTER:
6817     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6818     return;
6819   }
6820   if (Res.getNode())
6821     Results.push_back(Res);
6822 }
6823
6824 //===----------------------------------------------------------------------===//
6825 //                           ARM Scheduler Hooks
6826 //===----------------------------------------------------------------------===//
6827
6828 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6829 /// registers the function context.
6830 void ARMTargetLowering::
6831 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6832                        MachineBasicBlock *DispatchBB, int FI) const {
6833   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6834   DebugLoc dl = MI->getDebugLoc();
6835   MachineFunction *MF = MBB->getParent();
6836   MachineRegisterInfo *MRI = &MF->getRegInfo();
6837   MachineConstantPool *MCP = MF->getConstantPool();
6838   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6839   const Function *F = MF->getFunction();
6840
6841   bool isThumb = Subtarget->isThumb();
6842   bool isThumb2 = Subtarget->isThumb2();
6843
6844   unsigned PCLabelId = AFI->createPICLabelUId();
6845   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6846   ARMConstantPoolValue *CPV =
6847     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6848   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6849
6850   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6851                                            : &ARM::GPRRegClass;
6852
6853   // Grab constant pool and fixed stack memory operands.
6854   MachineMemOperand *CPMMO =
6855     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6856                              MachineMemOperand::MOLoad, 4, 4);
6857
6858   MachineMemOperand *FIMMOSt =
6859     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6860                              MachineMemOperand::MOStore, 4, 4);
6861
6862   // Load the address of the dispatch MBB into the jump buffer.
6863   if (isThumb2) {
6864     // Incoming value: jbuf
6865     //   ldr.n  r5, LCPI1_1
6866     //   orr    r5, r5, #1
6867     //   add    r5, pc
6868     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6869     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6870     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6871                    .addConstantPoolIndex(CPI)
6872                    .addMemOperand(CPMMO));
6873     // Set the low bit because of thumb mode.
6874     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6875     AddDefaultCC(
6876       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6877                      .addReg(NewVReg1, RegState::Kill)
6878                      .addImm(0x01)));
6879     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6880     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6881       .addReg(NewVReg2, RegState::Kill)
6882       .addImm(PCLabelId);
6883     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6884                    .addReg(NewVReg3, RegState::Kill)
6885                    .addFrameIndex(FI)
6886                    .addImm(36)  // &jbuf[1] :: pc
6887                    .addMemOperand(FIMMOSt));
6888   } else if (isThumb) {
6889     // Incoming value: jbuf
6890     //   ldr.n  r1, LCPI1_4
6891     //   add    r1, pc
6892     //   mov    r2, #1
6893     //   orrs   r1, r2
6894     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6895     //   str    r1, [r2]
6896     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6897     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6898                    .addConstantPoolIndex(CPI)
6899                    .addMemOperand(CPMMO));
6900     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6901     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6902       .addReg(NewVReg1, RegState::Kill)
6903       .addImm(PCLabelId);
6904     // Set the low bit because of thumb mode.
6905     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6906     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6907                    .addReg(ARM::CPSR, RegState::Define)
6908                    .addImm(1));
6909     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6910     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6911                    .addReg(ARM::CPSR, RegState::Define)
6912                    .addReg(NewVReg2, RegState::Kill)
6913                    .addReg(NewVReg3, RegState::Kill));
6914     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6915     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6916             .addFrameIndex(FI)
6917             .addImm(36); // &jbuf[1] :: pc
6918     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6919                    .addReg(NewVReg4, RegState::Kill)
6920                    .addReg(NewVReg5, RegState::Kill)
6921                    .addImm(0)
6922                    .addMemOperand(FIMMOSt));
6923   } else {
6924     // Incoming value: jbuf
6925     //   ldr  r1, LCPI1_1
6926     //   add  r1, pc, r1
6927     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6928     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6929     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6930                    .addConstantPoolIndex(CPI)
6931                    .addImm(0)
6932                    .addMemOperand(CPMMO));
6933     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6934     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6935                    .addReg(NewVReg1, RegState::Kill)
6936                    .addImm(PCLabelId));
6937     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6938                    .addReg(NewVReg2, RegState::Kill)
6939                    .addFrameIndex(FI)
6940                    .addImm(36)  // &jbuf[1] :: pc
6941                    .addMemOperand(FIMMOSt));
6942   }
6943 }
6944
6945 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6946                                               MachineBasicBlock *MBB) const {
6947   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6948   DebugLoc dl = MI->getDebugLoc();
6949   MachineFunction *MF = MBB->getParent();
6950   MachineRegisterInfo *MRI = &MF->getRegInfo();
6951   MachineFrameInfo *MFI = MF->getFrameInfo();
6952   int FI = MFI->getFunctionContextIndex();
6953
6954   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6955                                                         : &ARM::GPRnopcRegClass;
6956
6957   // Get a mapping of the call site numbers to all of the landing pads they're
6958   // associated with.
6959   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6960   unsigned MaxCSNum = 0;
6961   MachineModuleInfo &MMI = MF->getMMI();
6962   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6963        ++BB) {
6964     if (!BB->isLandingPad()) continue;
6965
6966     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6967     // pad.
6968     for (MachineBasicBlock::iterator
6969            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6970       if (!II->isEHLabel()) continue;
6971
6972       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6973       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6974
6975       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6976       for (SmallVectorImpl<unsigned>::iterator
6977              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6978            CSI != CSE; ++CSI) {
6979         CallSiteNumToLPad[*CSI].push_back(BB);
6980         MaxCSNum = std::max(MaxCSNum, *CSI);
6981       }
6982       break;
6983     }
6984   }
6985
6986   // Get an ordered list of the machine basic blocks for the jump table.
6987   std::vector<MachineBasicBlock*> LPadList;
6988   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6989   LPadList.reserve(CallSiteNumToLPad.size());
6990   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6991     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6992     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6993            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6994       LPadList.push_back(*II);
6995       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6996     }
6997   }
6998
6999   assert(!LPadList.empty() &&
7000          "No landing pad destinations for the dispatch jump table!");
7001
7002   // Create the jump table and associated information.
7003   MachineJumpTableInfo *JTI =
7004     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7005   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7006   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7007
7008   // Create the MBBs for the dispatch code.
7009
7010   // Shove the dispatch's address into the return slot in the function context.
7011   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7012   DispatchBB->setIsLandingPad();
7013
7014   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7015   unsigned trap_opcode;
7016   if (Subtarget->isThumb())
7017     trap_opcode = ARM::tTRAP;
7018   else
7019     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7020
7021   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7022   DispatchBB->addSuccessor(TrapBB);
7023
7024   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7025   DispatchBB->addSuccessor(DispContBB);
7026
7027   // Insert and MBBs.
7028   MF->insert(MF->end(), DispatchBB);
7029   MF->insert(MF->end(), DispContBB);
7030   MF->insert(MF->end(), TrapBB);
7031
7032   // Insert code into the entry block that creates and registers the function
7033   // context.
7034   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7035
7036   MachineMemOperand *FIMMOLd =
7037     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
7038                              MachineMemOperand::MOLoad |
7039                              MachineMemOperand::MOVolatile, 4, 4);
7040
7041   MachineInstrBuilder MIB;
7042   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7043
7044   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7045   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7046
7047   // Add a register mask with no preserved registers.  This results in all
7048   // registers being marked as clobbered.
7049   MIB.addRegMask(RI.getNoPreservedMask());
7050
7051   unsigned NumLPads = LPadList.size();
7052   if (Subtarget->isThumb2()) {
7053     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7054     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7055                    .addFrameIndex(FI)
7056                    .addImm(4)
7057                    .addMemOperand(FIMMOLd));
7058
7059     if (NumLPads < 256) {
7060       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7061                      .addReg(NewVReg1)
7062                      .addImm(LPadList.size()));
7063     } else {
7064       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7065       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7066                      .addImm(NumLPads & 0xFFFF));
7067
7068       unsigned VReg2 = VReg1;
7069       if ((NumLPads & 0xFFFF0000) != 0) {
7070         VReg2 = MRI->createVirtualRegister(TRC);
7071         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7072                        .addReg(VReg1)
7073                        .addImm(NumLPads >> 16));
7074       }
7075
7076       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7077                      .addReg(NewVReg1)
7078                      .addReg(VReg2));
7079     }
7080
7081     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7082       .addMBB(TrapBB)
7083       .addImm(ARMCC::HI)
7084       .addReg(ARM::CPSR);
7085
7086     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7087     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7088                    .addJumpTableIndex(MJTI));
7089
7090     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7091     AddDefaultCC(
7092       AddDefaultPred(
7093         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7094         .addReg(NewVReg3, RegState::Kill)
7095         .addReg(NewVReg1)
7096         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7097
7098     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7099       .addReg(NewVReg4, RegState::Kill)
7100       .addReg(NewVReg1)
7101       .addJumpTableIndex(MJTI);
7102   } else if (Subtarget->isThumb()) {
7103     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7104     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7105                    .addFrameIndex(FI)
7106                    .addImm(1)
7107                    .addMemOperand(FIMMOLd));
7108
7109     if (NumLPads < 256) {
7110       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7111                      .addReg(NewVReg1)
7112                      .addImm(NumLPads));
7113     } else {
7114       MachineConstantPool *ConstantPool = MF->getConstantPool();
7115       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7116       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7117
7118       // MachineConstantPool wants an explicit alignment.
7119       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7120       if (Align == 0)
7121         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7122       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7123
7124       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7125       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7126                      .addReg(VReg1, RegState::Define)
7127                      .addConstantPoolIndex(Idx));
7128       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7129                      .addReg(NewVReg1)
7130                      .addReg(VReg1));
7131     }
7132
7133     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7134       .addMBB(TrapBB)
7135       .addImm(ARMCC::HI)
7136       .addReg(ARM::CPSR);
7137
7138     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7139     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7140                    .addReg(ARM::CPSR, RegState::Define)
7141                    .addReg(NewVReg1)
7142                    .addImm(2));
7143
7144     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7145     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7146                    .addJumpTableIndex(MJTI));
7147
7148     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7149     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7150                    .addReg(ARM::CPSR, RegState::Define)
7151                    .addReg(NewVReg2, RegState::Kill)
7152                    .addReg(NewVReg3));
7153
7154     MachineMemOperand *JTMMOLd =
7155       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7156                                MachineMemOperand::MOLoad, 4, 4);
7157
7158     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7159     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7160                    .addReg(NewVReg4, RegState::Kill)
7161                    .addImm(0)
7162                    .addMemOperand(JTMMOLd));
7163
7164     unsigned NewVReg6 = NewVReg5;
7165     if (RelocM == Reloc::PIC_) {
7166       NewVReg6 = MRI->createVirtualRegister(TRC);
7167       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7168                      .addReg(ARM::CPSR, RegState::Define)
7169                      .addReg(NewVReg5, RegState::Kill)
7170                      .addReg(NewVReg3));
7171     }
7172
7173     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7174       .addReg(NewVReg6, RegState::Kill)
7175       .addJumpTableIndex(MJTI);
7176   } else {
7177     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7178     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7179                    .addFrameIndex(FI)
7180                    .addImm(4)
7181                    .addMemOperand(FIMMOLd));
7182
7183     if (NumLPads < 256) {
7184       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7185                      .addReg(NewVReg1)
7186                      .addImm(NumLPads));
7187     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7188       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7189       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7190                      .addImm(NumLPads & 0xFFFF));
7191
7192       unsigned VReg2 = VReg1;
7193       if ((NumLPads & 0xFFFF0000) != 0) {
7194         VReg2 = MRI->createVirtualRegister(TRC);
7195         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7196                        .addReg(VReg1)
7197                        .addImm(NumLPads >> 16));
7198       }
7199
7200       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7201                      .addReg(NewVReg1)
7202                      .addReg(VReg2));
7203     } else {
7204       MachineConstantPool *ConstantPool = MF->getConstantPool();
7205       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7206       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7207
7208       // MachineConstantPool wants an explicit alignment.
7209       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7210       if (Align == 0)
7211         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7212       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7213
7214       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7215       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7216                      .addReg(VReg1, RegState::Define)
7217                      .addConstantPoolIndex(Idx)
7218                      .addImm(0));
7219       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7220                      .addReg(NewVReg1)
7221                      .addReg(VReg1, RegState::Kill));
7222     }
7223
7224     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7225       .addMBB(TrapBB)
7226       .addImm(ARMCC::HI)
7227       .addReg(ARM::CPSR);
7228
7229     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7230     AddDefaultCC(
7231       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7232                      .addReg(NewVReg1)
7233                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7234     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7235     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7236                    .addJumpTableIndex(MJTI));
7237
7238     MachineMemOperand *JTMMOLd =
7239       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7240                                MachineMemOperand::MOLoad, 4, 4);
7241     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7242     AddDefaultPred(
7243       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7244       .addReg(NewVReg3, RegState::Kill)
7245       .addReg(NewVReg4)
7246       .addImm(0)
7247       .addMemOperand(JTMMOLd));
7248
7249     if (RelocM == Reloc::PIC_) {
7250       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7251         .addReg(NewVReg5, RegState::Kill)
7252         .addReg(NewVReg4)
7253         .addJumpTableIndex(MJTI);
7254     } else {
7255       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7256         .addReg(NewVReg5, RegState::Kill)
7257         .addJumpTableIndex(MJTI);
7258     }
7259   }
7260
7261   // Add the jump table entries as successors to the MBB.
7262   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7263   for (std::vector<MachineBasicBlock*>::iterator
7264          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7265     MachineBasicBlock *CurMBB = *I;
7266     if (SeenMBBs.insert(CurMBB).second)
7267       DispContBB->addSuccessor(CurMBB);
7268   }
7269
7270   // N.B. the order the invoke BBs are processed in doesn't matter here.
7271   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7272   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7273   for (MachineBasicBlock *BB : InvokeBBs) {
7274
7275     // Remove the landing pad successor from the invoke block and replace it
7276     // with the new dispatch block.
7277     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7278                                                   BB->succ_end());
7279     while (!Successors.empty()) {
7280       MachineBasicBlock *SMBB = Successors.pop_back_val();
7281       if (SMBB->isLandingPad()) {
7282         BB->removeSuccessor(SMBB);
7283         MBBLPads.push_back(SMBB);
7284       }
7285     }
7286
7287     BB->addSuccessor(DispatchBB);
7288
7289     // Find the invoke call and mark all of the callee-saved registers as
7290     // 'implicit defined' so that they're spilled. This prevents code from
7291     // moving instructions to before the EH block, where they will never be
7292     // executed.
7293     for (MachineBasicBlock::reverse_iterator
7294            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7295       if (!II->isCall()) continue;
7296
7297       DenseMap<unsigned, bool> DefRegs;
7298       for (MachineInstr::mop_iterator
7299              OI = II->operands_begin(), OE = II->operands_end();
7300            OI != OE; ++OI) {
7301         if (!OI->isReg()) continue;
7302         DefRegs[OI->getReg()] = true;
7303       }
7304
7305       MachineInstrBuilder MIB(*MF, &*II);
7306
7307       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7308         unsigned Reg = SavedRegs[i];
7309         if (Subtarget->isThumb2() &&
7310             !ARM::tGPRRegClass.contains(Reg) &&
7311             !ARM::hGPRRegClass.contains(Reg))
7312           continue;
7313         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7314           continue;
7315         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7316           continue;
7317         if (!DefRegs[Reg])
7318           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7319       }
7320
7321       break;
7322     }
7323   }
7324
7325   // Mark all former landing pads as non-landing pads. The dispatch is the only
7326   // landing pad now.
7327   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7328          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7329     (*I)->setIsLandingPad(false);
7330
7331   // The instruction is gone now.
7332   MI->eraseFromParent();
7333 }
7334
7335 static
7336 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7337   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7338        E = MBB->succ_end(); I != E; ++I)
7339     if (*I != Succ)
7340       return *I;
7341   llvm_unreachable("Expecting a BB with two successors!");
7342 }
7343
7344 /// Return the load opcode for a given load size. If load size >= 8,
7345 /// neon opcode will be returned.
7346 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7347   if (LdSize >= 8)
7348     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7349                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7350   if (IsThumb1)
7351     return LdSize == 4 ? ARM::tLDRi
7352                        : LdSize == 2 ? ARM::tLDRHi
7353                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7354   if (IsThumb2)
7355     return LdSize == 4 ? ARM::t2LDR_POST
7356                        : LdSize == 2 ? ARM::t2LDRH_POST
7357                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7358   return LdSize == 4 ? ARM::LDR_POST_IMM
7359                      : LdSize == 2 ? ARM::LDRH_POST
7360                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7361 }
7362
7363 /// Return the store opcode for a given store size. If store size >= 8,
7364 /// neon opcode will be returned.
7365 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7366   if (StSize >= 8)
7367     return StSize == 16 ? ARM::VST1q32wb_fixed
7368                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7369   if (IsThumb1)
7370     return StSize == 4 ? ARM::tSTRi
7371                        : StSize == 2 ? ARM::tSTRHi
7372                                      : StSize == 1 ? ARM::tSTRBi : 0;
7373   if (IsThumb2)
7374     return StSize == 4 ? ARM::t2STR_POST
7375                        : StSize == 2 ? ARM::t2STRH_POST
7376                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7377   return StSize == 4 ? ARM::STR_POST_IMM
7378                      : StSize == 2 ? ARM::STRH_POST
7379                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7380 }
7381
7382 /// Emit a post-increment load operation with given size. The instructions
7383 /// will be added to BB at Pos.
7384 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7385                        const TargetInstrInfo *TII, DebugLoc dl,
7386                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7387                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7388   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7389   assert(LdOpc != 0 && "Should have a load opcode");
7390   if (LdSize >= 8) {
7391     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7392                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7393                        .addImm(0));
7394   } else if (IsThumb1) {
7395     // load + update AddrIn
7396     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7397                        .addReg(AddrIn).addImm(0));
7398     MachineInstrBuilder MIB =
7399         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7400     MIB = AddDefaultT1CC(MIB);
7401     MIB.addReg(AddrIn).addImm(LdSize);
7402     AddDefaultPred(MIB);
7403   } else if (IsThumb2) {
7404     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7405                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7406                        .addImm(LdSize));
7407   } else { // arm
7408     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7409                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7410                        .addReg(0).addImm(LdSize));
7411   }
7412 }
7413
7414 /// Emit a post-increment store operation with given size. The instructions
7415 /// will be added to BB at Pos.
7416 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7417                        const TargetInstrInfo *TII, DebugLoc dl,
7418                        unsigned StSize, unsigned Data, unsigned AddrIn,
7419                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7420   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7421   assert(StOpc != 0 && "Should have a store opcode");
7422   if (StSize >= 8) {
7423     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7424                        .addReg(AddrIn).addImm(0).addReg(Data));
7425   } else if (IsThumb1) {
7426     // store + update AddrIn
7427     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7428                        .addReg(AddrIn).addImm(0));
7429     MachineInstrBuilder MIB =
7430         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7431     MIB = AddDefaultT1CC(MIB);
7432     MIB.addReg(AddrIn).addImm(StSize);
7433     AddDefaultPred(MIB);
7434   } else if (IsThumb2) {
7435     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7436                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7437   } else { // arm
7438     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7439                        .addReg(Data).addReg(AddrIn).addReg(0)
7440                        .addImm(StSize));
7441   }
7442 }
7443
7444 MachineBasicBlock *
7445 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7446                                    MachineBasicBlock *BB) const {
7447   // This pseudo instruction has 3 operands: dst, src, size
7448   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7449   // Otherwise, we will generate unrolled scalar copies.
7450   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7451   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7452   MachineFunction::iterator It = BB;
7453   ++It;
7454
7455   unsigned dest = MI->getOperand(0).getReg();
7456   unsigned src = MI->getOperand(1).getReg();
7457   unsigned SizeVal = MI->getOperand(2).getImm();
7458   unsigned Align = MI->getOperand(3).getImm();
7459   DebugLoc dl = MI->getDebugLoc();
7460
7461   MachineFunction *MF = BB->getParent();
7462   MachineRegisterInfo &MRI = MF->getRegInfo();
7463   unsigned UnitSize = 0;
7464   const TargetRegisterClass *TRC = nullptr;
7465   const TargetRegisterClass *VecTRC = nullptr;
7466
7467   bool IsThumb1 = Subtarget->isThumb1Only();
7468   bool IsThumb2 = Subtarget->isThumb2();
7469
7470   if (Align & 1) {
7471     UnitSize = 1;
7472   } else if (Align & 2) {
7473     UnitSize = 2;
7474   } else {
7475     // Check whether we can use NEON instructions.
7476     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7477         Subtarget->hasNEON()) {
7478       if ((Align % 16 == 0) && SizeVal >= 16)
7479         UnitSize = 16;
7480       else if ((Align % 8 == 0) && SizeVal >= 8)
7481         UnitSize = 8;
7482     }
7483     // Can't use NEON instructions.
7484     if (UnitSize == 0)
7485       UnitSize = 4;
7486   }
7487
7488   // Select the correct opcode and register class for unit size load/store
7489   bool IsNeon = UnitSize >= 8;
7490   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7491   if (IsNeon)
7492     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7493                             : UnitSize == 8 ? &ARM::DPRRegClass
7494                                             : nullptr;
7495
7496   unsigned BytesLeft = SizeVal % UnitSize;
7497   unsigned LoopSize = SizeVal - BytesLeft;
7498
7499   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7500     // Use LDR and STR to copy.
7501     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7502     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7503     unsigned srcIn = src;
7504     unsigned destIn = dest;
7505     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7506       unsigned srcOut = MRI.createVirtualRegister(TRC);
7507       unsigned destOut = MRI.createVirtualRegister(TRC);
7508       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7509       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7510                  IsThumb1, IsThumb2);
7511       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7512                  IsThumb1, IsThumb2);
7513       srcIn = srcOut;
7514       destIn = destOut;
7515     }
7516
7517     // Handle the leftover bytes with LDRB and STRB.
7518     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7519     // [destOut] = STRB_POST(scratch, destIn, 1)
7520     for (unsigned i = 0; i < BytesLeft; i++) {
7521       unsigned srcOut = MRI.createVirtualRegister(TRC);
7522       unsigned destOut = MRI.createVirtualRegister(TRC);
7523       unsigned scratch = MRI.createVirtualRegister(TRC);
7524       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7525                  IsThumb1, IsThumb2);
7526       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7527                  IsThumb1, IsThumb2);
7528       srcIn = srcOut;
7529       destIn = destOut;
7530     }
7531     MI->eraseFromParent();   // The instruction is gone now.
7532     return BB;
7533   }
7534
7535   // Expand the pseudo op to a loop.
7536   // thisMBB:
7537   //   ...
7538   //   movw varEnd, # --> with thumb2
7539   //   movt varEnd, #
7540   //   ldrcp varEnd, idx --> without thumb2
7541   //   fallthrough --> loopMBB
7542   // loopMBB:
7543   //   PHI varPhi, varEnd, varLoop
7544   //   PHI srcPhi, src, srcLoop
7545   //   PHI destPhi, dst, destLoop
7546   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7547   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7548   //   subs varLoop, varPhi, #UnitSize
7549   //   bne loopMBB
7550   //   fallthrough --> exitMBB
7551   // exitMBB:
7552   //   epilogue to handle left-over bytes
7553   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7554   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7555   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7556   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7557   MF->insert(It, loopMBB);
7558   MF->insert(It, exitMBB);
7559
7560   // Transfer the remainder of BB and its successor edges to exitMBB.
7561   exitMBB->splice(exitMBB->begin(), BB,
7562                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7563   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7564
7565   // Load an immediate to varEnd.
7566   unsigned varEnd = MRI.createVirtualRegister(TRC);
7567   if (Subtarget->useMovt(*MF)) {
7568     unsigned Vtmp = varEnd;
7569     if ((LoopSize & 0xFFFF0000) != 0)
7570       Vtmp = MRI.createVirtualRegister(TRC);
7571     AddDefaultPred(BuildMI(BB, dl,
7572                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7573                            Vtmp).addImm(LoopSize & 0xFFFF));
7574
7575     if ((LoopSize & 0xFFFF0000) != 0)
7576       AddDefaultPred(BuildMI(BB, dl,
7577                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7578                              varEnd)
7579                          .addReg(Vtmp)
7580                          .addImm(LoopSize >> 16));
7581   } else {
7582     MachineConstantPool *ConstantPool = MF->getConstantPool();
7583     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7584     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7585
7586     // MachineConstantPool wants an explicit alignment.
7587     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7588     if (Align == 0)
7589       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7590     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7591
7592     if (IsThumb1)
7593       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7594           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7595     else
7596       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7597           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7598   }
7599   BB->addSuccessor(loopMBB);
7600
7601   // Generate the loop body:
7602   //   varPhi = PHI(varLoop, varEnd)
7603   //   srcPhi = PHI(srcLoop, src)
7604   //   destPhi = PHI(destLoop, dst)
7605   MachineBasicBlock *entryBB = BB;
7606   BB = loopMBB;
7607   unsigned varLoop = MRI.createVirtualRegister(TRC);
7608   unsigned varPhi = MRI.createVirtualRegister(TRC);
7609   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7610   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7611   unsigned destLoop = MRI.createVirtualRegister(TRC);
7612   unsigned destPhi = MRI.createVirtualRegister(TRC);
7613
7614   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7615     .addReg(varLoop).addMBB(loopMBB)
7616     .addReg(varEnd).addMBB(entryBB);
7617   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7618     .addReg(srcLoop).addMBB(loopMBB)
7619     .addReg(src).addMBB(entryBB);
7620   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7621     .addReg(destLoop).addMBB(loopMBB)
7622     .addReg(dest).addMBB(entryBB);
7623
7624   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7625   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7626   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7627   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7628              IsThumb1, IsThumb2);
7629   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7630              IsThumb1, IsThumb2);
7631
7632   // Decrement loop variable by UnitSize.
7633   if (IsThumb1) {
7634     MachineInstrBuilder MIB =
7635         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7636     MIB = AddDefaultT1CC(MIB);
7637     MIB.addReg(varPhi).addImm(UnitSize);
7638     AddDefaultPred(MIB);
7639   } else {
7640     MachineInstrBuilder MIB =
7641         BuildMI(*BB, BB->end(), dl,
7642                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7643     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7644     MIB->getOperand(5).setReg(ARM::CPSR);
7645     MIB->getOperand(5).setIsDef(true);
7646   }
7647   BuildMI(*BB, BB->end(), dl,
7648           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7649       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7650
7651   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7652   BB->addSuccessor(loopMBB);
7653   BB->addSuccessor(exitMBB);
7654
7655   // Add epilogue to handle BytesLeft.
7656   BB = exitMBB;
7657   MachineInstr *StartOfExit = exitMBB->begin();
7658
7659   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7660   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7661   unsigned srcIn = srcLoop;
7662   unsigned destIn = destLoop;
7663   for (unsigned i = 0; i < BytesLeft; i++) {
7664     unsigned srcOut = MRI.createVirtualRegister(TRC);
7665     unsigned destOut = MRI.createVirtualRegister(TRC);
7666     unsigned scratch = MRI.createVirtualRegister(TRC);
7667     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7668                IsThumb1, IsThumb2);
7669     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7670                IsThumb1, IsThumb2);
7671     srcIn = srcOut;
7672     destIn = destOut;
7673   }
7674
7675   MI->eraseFromParent();   // The instruction is gone now.
7676   return BB;
7677 }
7678
7679 MachineBasicBlock *
7680 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7681                                        MachineBasicBlock *MBB) const {
7682   const TargetMachine &TM = getTargetMachine();
7683   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7684   DebugLoc DL = MI->getDebugLoc();
7685
7686   assert(Subtarget->isTargetWindows() &&
7687          "__chkstk is only supported on Windows");
7688   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7689
7690   // __chkstk takes the number of words to allocate on the stack in R4, and
7691   // returns the stack adjustment in number of bytes in R4.  This will not
7692   // clober any other registers (other than the obvious lr).
7693   //
7694   // Although, technically, IP should be considered a register which may be
7695   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7696   // thumb-2 environment, so there is no interworking required.  As a result, we
7697   // do not expect a veneer to be emitted by the linker, clobbering IP.
7698   //
7699   // Each module receives its own copy of __chkstk, so no import thunk is
7700   // required, again, ensuring that IP is not clobbered.
7701   //
7702   // Finally, although some linkers may theoretically provide a trampoline for
7703   // out of range calls (which is quite common due to a 32M range limitation of
7704   // branches for Thumb), we can generate the long-call version via
7705   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7706   // IP.
7707
7708   switch (TM.getCodeModel()) {
7709   case CodeModel::Small:
7710   case CodeModel::Medium:
7711   case CodeModel::Default:
7712   case CodeModel::Kernel:
7713     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7714       .addImm((unsigned)ARMCC::AL).addReg(0)
7715       .addExternalSymbol("__chkstk")
7716       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7717       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7718       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7719     break;
7720   case CodeModel::Large:
7721   case CodeModel::JITDefault: {
7722     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7723     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7724
7725     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7726       .addExternalSymbol("__chkstk");
7727     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7728       .addImm((unsigned)ARMCC::AL).addReg(0)
7729       .addReg(Reg, RegState::Kill)
7730       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7731       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7732       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7733     break;
7734   }
7735   }
7736
7737   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7738                                       ARM::SP)
7739                               .addReg(ARM::SP).addReg(ARM::R4)));
7740
7741   MI->eraseFromParent();
7742   return MBB;
7743 }
7744
7745 MachineBasicBlock *
7746 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7747                                                MachineBasicBlock *BB) const {
7748   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7749   DebugLoc dl = MI->getDebugLoc();
7750   bool isThumb2 = Subtarget->isThumb2();
7751   switch (MI->getOpcode()) {
7752   default: {
7753     MI->dump();
7754     llvm_unreachable("Unexpected instr type to insert");
7755   }
7756   // The Thumb2 pre-indexed stores have the same MI operands, they just
7757   // define them differently in the .td files from the isel patterns, so
7758   // they need pseudos.
7759   case ARM::t2STR_preidx:
7760     MI->setDesc(TII->get(ARM::t2STR_PRE));
7761     return BB;
7762   case ARM::t2STRB_preidx:
7763     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7764     return BB;
7765   case ARM::t2STRH_preidx:
7766     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7767     return BB;
7768
7769   case ARM::STRi_preidx:
7770   case ARM::STRBi_preidx: {
7771     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7772       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7773     // Decode the offset.
7774     unsigned Offset = MI->getOperand(4).getImm();
7775     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7776     Offset = ARM_AM::getAM2Offset(Offset);
7777     if (isSub)
7778       Offset = -Offset;
7779
7780     MachineMemOperand *MMO = *MI->memoperands_begin();
7781     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7782       .addOperand(MI->getOperand(0))  // Rn_wb
7783       .addOperand(MI->getOperand(1))  // Rt
7784       .addOperand(MI->getOperand(2))  // Rn
7785       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7786       .addOperand(MI->getOperand(5))  // pred
7787       .addOperand(MI->getOperand(6))
7788       .addMemOperand(MMO);
7789     MI->eraseFromParent();
7790     return BB;
7791   }
7792   case ARM::STRr_preidx:
7793   case ARM::STRBr_preidx:
7794   case ARM::STRH_preidx: {
7795     unsigned NewOpc;
7796     switch (MI->getOpcode()) {
7797     default: llvm_unreachable("unexpected opcode!");
7798     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7799     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7800     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7801     }
7802     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7803     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7804       MIB.addOperand(MI->getOperand(i));
7805     MI->eraseFromParent();
7806     return BB;
7807   }
7808
7809   case ARM::tMOVCCr_pseudo: {
7810     // To "insert" a SELECT_CC instruction, we actually have to insert the
7811     // diamond control-flow pattern.  The incoming instruction knows the
7812     // destination vreg to set, the condition code register to branch on, the
7813     // true/false values to select between, and a branch opcode to use.
7814     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7815     MachineFunction::iterator It = BB;
7816     ++It;
7817
7818     //  thisMBB:
7819     //  ...
7820     //   TrueVal = ...
7821     //   cmpTY ccX, r1, r2
7822     //   bCC copy1MBB
7823     //   fallthrough --> copy0MBB
7824     MachineBasicBlock *thisMBB  = BB;
7825     MachineFunction *F = BB->getParent();
7826     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7827     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7828     F->insert(It, copy0MBB);
7829     F->insert(It, sinkMBB);
7830
7831     // Transfer the remainder of BB and its successor edges to sinkMBB.
7832     sinkMBB->splice(sinkMBB->begin(), BB,
7833                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7834     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7835
7836     BB->addSuccessor(copy0MBB);
7837     BB->addSuccessor(sinkMBB);
7838
7839     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7840       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7841
7842     //  copy0MBB:
7843     //   %FalseValue = ...
7844     //   # fallthrough to sinkMBB
7845     BB = copy0MBB;
7846
7847     // Update machine-CFG edges
7848     BB->addSuccessor(sinkMBB);
7849
7850     //  sinkMBB:
7851     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7852     //  ...
7853     BB = sinkMBB;
7854     BuildMI(*BB, BB->begin(), dl,
7855             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7856       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7857       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7858
7859     MI->eraseFromParent();   // The pseudo instruction is gone now.
7860     return BB;
7861   }
7862
7863   case ARM::BCCi64:
7864   case ARM::BCCZi64: {
7865     // If there is an unconditional branch to the other successor, remove it.
7866     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7867
7868     // Compare both parts that make up the double comparison separately for
7869     // equality.
7870     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7871
7872     unsigned LHS1 = MI->getOperand(1).getReg();
7873     unsigned LHS2 = MI->getOperand(2).getReg();
7874     if (RHSisZero) {
7875       AddDefaultPred(BuildMI(BB, dl,
7876                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7877                      .addReg(LHS1).addImm(0));
7878       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7879         .addReg(LHS2).addImm(0)
7880         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7881     } else {
7882       unsigned RHS1 = MI->getOperand(3).getReg();
7883       unsigned RHS2 = MI->getOperand(4).getReg();
7884       AddDefaultPred(BuildMI(BB, dl,
7885                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7886                      .addReg(LHS1).addReg(RHS1));
7887       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7888         .addReg(LHS2).addReg(RHS2)
7889         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7890     }
7891
7892     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7893     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7894     if (MI->getOperand(0).getImm() == ARMCC::NE)
7895       std::swap(destMBB, exitMBB);
7896
7897     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7898       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7899     if (isThumb2)
7900       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7901     else
7902       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7903
7904     MI->eraseFromParent();   // The pseudo instruction is gone now.
7905     return BB;
7906   }
7907
7908   case ARM::Int_eh_sjlj_setjmp:
7909   case ARM::Int_eh_sjlj_setjmp_nofp:
7910   case ARM::tInt_eh_sjlj_setjmp:
7911   case ARM::t2Int_eh_sjlj_setjmp:
7912   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7913     return BB;
7914
7915   case ARM::Int_eh_sjlj_setup_dispatch:
7916     EmitSjLjDispatchBlock(MI, BB);
7917     return BB;
7918
7919   case ARM::ABS:
7920   case ARM::t2ABS: {
7921     // To insert an ABS instruction, we have to insert the
7922     // diamond control-flow pattern.  The incoming instruction knows the
7923     // source vreg to test against 0, the destination vreg to set,
7924     // the condition code register to branch on, the
7925     // true/false values to select between, and a branch opcode to use.
7926     // It transforms
7927     //     V1 = ABS V0
7928     // into
7929     //     V2 = MOVS V0
7930     //     BCC                      (branch to SinkBB if V0 >= 0)
7931     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7932     //     SinkBB: V1 = PHI(V2, V3)
7933     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7934     MachineFunction::iterator BBI = BB;
7935     ++BBI;
7936     MachineFunction *Fn = BB->getParent();
7937     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7938     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7939     Fn->insert(BBI, RSBBB);
7940     Fn->insert(BBI, SinkBB);
7941
7942     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7943     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7944     bool ABSSrcKIll = MI->getOperand(1).isKill();
7945     bool isThumb2 = Subtarget->isThumb2();
7946     MachineRegisterInfo &MRI = Fn->getRegInfo();
7947     // In Thumb mode S must not be specified if source register is the SP or
7948     // PC and if destination register is the SP, so restrict register class
7949     unsigned NewRsbDstReg =
7950       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7951
7952     // Transfer the remainder of BB and its successor edges to sinkMBB.
7953     SinkBB->splice(SinkBB->begin(), BB,
7954                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7955     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7956
7957     BB->addSuccessor(RSBBB);
7958     BB->addSuccessor(SinkBB);
7959
7960     // fall through to SinkMBB
7961     RSBBB->addSuccessor(SinkBB);
7962
7963     // insert a cmp at the end of BB
7964     AddDefaultPred(BuildMI(BB, dl,
7965                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7966                    .addReg(ABSSrcReg).addImm(0));
7967
7968     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7969     BuildMI(BB, dl,
7970       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7971       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7972
7973     // insert rsbri in RSBBB
7974     // Note: BCC and rsbri will be converted into predicated rsbmi
7975     // by if-conversion pass
7976     BuildMI(*RSBBB, RSBBB->begin(), dl,
7977       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7978       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7979       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7980
7981     // insert PHI in SinkBB,
7982     // reuse ABSDstReg to not change uses of ABS instruction
7983     BuildMI(*SinkBB, SinkBB->begin(), dl,
7984       TII->get(ARM::PHI), ABSDstReg)
7985       .addReg(NewRsbDstReg).addMBB(RSBBB)
7986       .addReg(ABSSrcReg).addMBB(BB);
7987
7988     // remove ABS instruction
7989     MI->eraseFromParent();
7990
7991     // return last added BB
7992     return SinkBB;
7993   }
7994   case ARM::COPY_STRUCT_BYVAL_I32:
7995     ++NumLoopByVals;
7996     return EmitStructByval(MI, BB);
7997   case ARM::WIN__CHKSTK:
7998     return EmitLowered__chkstk(MI, BB);
7999   }
8000 }
8001
8002 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8003                                                       SDNode *Node) const {
8004   const MCInstrDesc *MCID = &MI->getDesc();
8005   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8006   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8007   // operand is still set to noreg. If needed, set the optional operand's
8008   // register to CPSR, and remove the redundant implicit def.
8009   //
8010   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8011
8012   // Rename pseudo opcodes.
8013   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8014   if (NewOpc) {
8015     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8016     MCID = &TII->get(NewOpc);
8017
8018     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8019            "converted opcode should be the same except for cc_out");
8020
8021     MI->setDesc(*MCID);
8022
8023     // Add the optional cc_out operand
8024     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8025   }
8026   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8027
8028   // Any ARM instruction that sets the 's' bit should specify an optional
8029   // "cc_out" operand in the last operand position.
8030   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8031     assert(!NewOpc && "Optional cc_out operand required");
8032     return;
8033   }
8034   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8035   // since we already have an optional CPSR def.
8036   bool definesCPSR = false;
8037   bool deadCPSR = false;
8038   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8039        i != e; ++i) {
8040     const MachineOperand &MO = MI->getOperand(i);
8041     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8042       definesCPSR = true;
8043       if (MO.isDead())
8044         deadCPSR = true;
8045       MI->RemoveOperand(i);
8046       break;
8047     }
8048   }
8049   if (!definesCPSR) {
8050     assert(!NewOpc && "Optional cc_out operand required");
8051     return;
8052   }
8053   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8054   if (deadCPSR) {
8055     assert(!MI->getOperand(ccOutIdx).getReg() &&
8056            "expect uninitialized optional cc_out operand");
8057     return;
8058   }
8059
8060   // If this instruction was defined with an optional CPSR def and its dag node
8061   // had a live implicit CPSR def, then activate the optional CPSR def.
8062   MachineOperand &MO = MI->getOperand(ccOutIdx);
8063   MO.setReg(ARM::CPSR);
8064   MO.setIsDef(true);
8065 }
8066
8067 //===----------------------------------------------------------------------===//
8068 //                           ARM Optimization Hooks
8069 //===----------------------------------------------------------------------===//
8070
8071 // Helper function that checks if N is a null or all ones constant.
8072 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8073   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8074   if (!C)
8075     return false;
8076   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8077 }
8078
8079 // Return true if N is conditionally 0 or all ones.
8080 // Detects these expressions where cc is an i1 value:
8081 //
8082 //   (select cc 0, y)   [AllOnes=0]
8083 //   (select cc y, 0)   [AllOnes=0]
8084 //   (zext cc)          [AllOnes=0]
8085 //   (sext cc)          [AllOnes=0/1]
8086 //   (select cc -1, y)  [AllOnes=1]
8087 //   (select cc y, -1)  [AllOnes=1]
8088 //
8089 // Invert is set when N is the null/all ones constant when CC is false.
8090 // OtherOp is set to the alternative value of N.
8091 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8092                                        SDValue &CC, bool &Invert,
8093                                        SDValue &OtherOp,
8094                                        SelectionDAG &DAG) {
8095   switch (N->getOpcode()) {
8096   default: return false;
8097   case ISD::SELECT: {
8098     CC = N->getOperand(0);
8099     SDValue N1 = N->getOperand(1);
8100     SDValue N2 = N->getOperand(2);
8101     if (isZeroOrAllOnes(N1, AllOnes)) {
8102       Invert = false;
8103       OtherOp = N2;
8104       return true;
8105     }
8106     if (isZeroOrAllOnes(N2, AllOnes)) {
8107       Invert = true;
8108       OtherOp = N1;
8109       return true;
8110     }
8111     return false;
8112   }
8113   case ISD::ZERO_EXTEND:
8114     // (zext cc) can never be the all ones value.
8115     if (AllOnes)
8116       return false;
8117     // Fall through.
8118   case ISD::SIGN_EXTEND: {
8119     SDLoc dl(N);
8120     EVT VT = N->getValueType(0);
8121     CC = N->getOperand(0);
8122     if (CC.getValueType() != MVT::i1)
8123       return false;
8124     Invert = !AllOnes;
8125     if (AllOnes)
8126       // When looking for an AllOnes constant, N is an sext, and the 'other'
8127       // value is 0.
8128       OtherOp = DAG.getConstant(0, dl, VT);
8129     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8130       // When looking for a 0 constant, N can be zext or sext.
8131       OtherOp = DAG.getConstant(1, dl, VT);
8132     else
8133       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8134                                 VT);
8135     return true;
8136   }
8137   }
8138 }
8139
8140 // Combine a constant select operand into its use:
8141 //
8142 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8143 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8144 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8145 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8146 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8147 //
8148 // The transform is rejected if the select doesn't have a constant operand that
8149 // is null, or all ones when AllOnes is set.
8150 //
8151 // Also recognize sext/zext from i1:
8152 //
8153 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8154 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8155 //
8156 // These transformations eventually create predicated instructions.
8157 //
8158 // @param N       The node to transform.
8159 // @param Slct    The N operand that is a select.
8160 // @param OtherOp The other N operand (x above).
8161 // @param DCI     Context.
8162 // @param AllOnes Require the select constant to be all ones instead of null.
8163 // @returns The new node, or SDValue() on failure.
8164 static
8165 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8166                             TargetLowering::DAGCombinerInfo &DCI,
8167                             bool AllOnes = false) {
8168   SelectionDAG &DAG = DCI.DAG;
8169   EVT VT = N->getValueType(0);
8170   SDValue NonConstantVal;
8171   SDValue CCOp;
8172   bool SwapSelectOps;
8173   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8174                                   NonConstantVal, DAG))
8175     return SDValue();
8176
8177   // Slct is now know to be the desired identity constant when CC is true.
8178   SDValue TrueVal = OtherOp;
8179   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8180                                  OtherOp, NonConstantVal);
8181   // Unless SwapSelectOps says CC should be false.
8182   if (SwapSelectOps)
8183     std::swap(TrueVal, FalseVal);
8184
8185   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8186                      CCOp, TrueVal, FalseVal);
8187 }
8188
8189 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8190 static
8191 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8192                                        TargetLowering::DAGCombinerInfo &DCI) {
8193   SDValue N0 = N->getOperand(0);
8194   SDValue N1 = N->getOperand(1);
8195   if (N0.getNode()->hasOneUse()) {
8196     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8197     if (Result.getNode())
8198       return Result;
8199   }
8200   if (N1.getNode()->hasOneUse()) {
8201     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8202     if (Result.getNode())
8203       return Result;
8204   }
8205   return SDValue();
8206 }
8207
8208 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8209 // (only after legalization).
8210 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8211                                  TargetLowering::DAGCombinerInfo &DCI,
8212                                  const ARMSubtarget *Subtarget) {
8213
8214   // Only perform optimization if after legalize, and if NEON is available. We
8215   // also expected both operands to be BUILD_VECTORs.
8216   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8217       || N0.getOpcode() != ISD::BUILD_VECTOR
8218       || N1.getOpcode() != ISD::BUILD_VECTOR)
8219     return SDValue();
8220
8221   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8222   EVT VT = N->getValueType(0);
8223   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8224     return SDValue();
8225
8226   // Check that the vector operands are of the right form.
8227   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8228   // operands, where N is the size of the formed vector.
8229   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8230   // index such that we have a pair wise add pattern.
8231
8232   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8233   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8234     return SDValue();
8235   SDValue Vec = N0->getOperand(0)->getOperand(0);
8236   SDNode *V = Vec.getNode();
8237   unsigned nextIndex = 0;
8238
8239   // For each operands to the ADD which are BUILD_VECTORs,
8240   // check to see if each of their operands are an EXTRACT_VECTOR with
8241   // the same vector and appropriate index.
8242   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8243     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8244         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8245
8246       SDValue ExtVec0 = N0->getOperand(i);
8247       SDValue ExtVec1 = N1->getOperand(i);
8248
8249       // First operand is the vector, verify its the same.
8250       if (V != ExtVec0->getOperand(0).getNode() ||
8251           V != ExtVec1->getOperand(0).getNode())
8252         return SDValue();
8253
8254       // Second is the constant, verify its correct.
8255       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8256       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8257
8258       // For the constant, we want to see all the even or all the odd.
8259       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8260           || C1->getZExtValue() != nextIndex+1)
8261         return SDValue();
8262
8263       // Increment index.
8264       nextIndex+=2;
8265     } else
8266       return SDValue();
8267   }
8268
8269   // Create VPADDL node.
8270   SelectionDAG &DAG = DCI.DAG;
8271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8272
8273   SDLoc dl(N);
8274
8275   // Build operand list.
8276   SmallVector<SDValue, 8> Ops;
8277   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8278                                 TLI.getPointerTy(DAG.getDataLayout())));
8279
8280   // Input is the vector.
8281   Ops.push_back(Vec);
8282
8283   // Get widened type and narrowed type.
8284   MVT widenType;
8285   unsigned numElem = VT.getVectorNumElements();
8286   
8287   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8288   switch (inputLaneType.getSimpleVT().SimpleTy) {
8289     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8290     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8291     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8292     default:
8293       llvm_unreachable("Invalid vector element type for padd optimization.");
8294   }
8295
8296   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8297   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8298   return DAG.getNode(ExtOp, dl, VT, tmp);
8299 }
8300
8301 static SDValue findMUL_LOHI(SDValue V) {
8302   if (V->getOpcode() == ISD::UMUL_LOHI ||
8303       V->getOpcode() == ISD::SMUL_LOHI)
8304     return V;
8305   return SDValue();
8306 }
8307
8308 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8309                                      TargetLowering::DAGCombinerInfo &DCI,
8310                                      const ARMSubtarget *Subtarget) {
8311
8312   if (Subtarget->isThumb1Only()) return SDValue();
8313
8314   // Only perform the checks after legalize when the pattern is available.
8315   if (DCI.isBeforeLegalize()) return SDValue();
8316
8317   // Look for multiply add opportunities.
8318   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8319   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8320   // a glue link from the first add to the second add.
8321   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8322   // a S/UMLAL instruction.
8323   //                  UMUL_LOHI
8324   //                 / :lo    \ :hi
8325   //                /          \          [no multiline comment]
8326   //    loAdd ->  ADDE         |
8327   //                 \ :glue  /
8328   //                  \      /
8329   //                    ADDC   <- hiAdd
8330   //
8331   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8332   SDValue AddcOp0 = AddcNode->getOperand(0);
8333   SDValue AddcOp1 = AddcNode->getOperand(1);
8334
8335   // Check if the two operands are from the same mul_lohi node.
8336   if (AddcOp0.getNode() == AddcOp1.getNode())
8337     return SDValue();
8338
8339   assert(AddcNode->getNumValues() == 2 &&
8340          AddcNode->getValueType(0) == MVT::i32 &&
8341          "Expect ADDC with two result values. First: i32");
8342
8343   // Check that we have a glued ADDC node.
8344   if (AddcNode->getValueType(1) != MVT::Glue)
8345     return SDValue();
8346
8347   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8348   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8349       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8350       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8351       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8352     return SDValue();
8353
8354   // Look for the glued ADDE.
8355   SDNode* AddeNode = AddcNode->getGluedUser();
8356   if (!AddeNode)
8357     return SDValue();
8358
8359   // Make sure it is really an ADDE.
8360   if (AddeNode->getOpcode() != ISD::ADDE)
8361     return SDValue();
8362
8363   assert(AddeNode->getNumOperands() == 3 &&
8364          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8365          "ADDE node has the wrong inputs");
8366
8367   // Check for the triangle shape.
8368   SDValue AddeOp0 = AddeNode->getOperand(0);
8369   SDValue AddeOp1 = AddeNode->getOperand(1);
8370
8371   // Make sure that the ADDE operands are not coming from the same node.
8372   if (AddeOp0.getNode() == AddeOp1.getNode())
8373     return SDValue();
8374
8375   // Find the MUL_LOHI node walking up ADDE's operands.
8376   bool IsLeftOperandMUL = false;
8377   SDValue MULOp = findMUL_LOHI(AddeOp0);
8378   if (MULOp == SDValue())
8379    MULOp = findMUL_LOHI(AddeOp1);
8380   else
8381     IsLeftOperandMUL = true;
8382   if (MULOp == SDValue())
8383     return SDValue();
8384
8385   // Figure out the right opcode.
8386   unsigned Opc = MULOp->getOpcode();
8387   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8388
8389   // Figure out the high and low input values to the MLAL node.
8390   SDValue* HiAdd = nullptr;
8391   SDValue* LoMul = nullptr;
8392   SDValue* LowAdd = nullptr;
8393
8394   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8395   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8396     return SDValue();
8397
8398   if (IsLeftOperandMUL)
8399     HiAdd = &AddeOp1;
8400   else
8401     HiAdd = &AddeOp0;
8402
8403
8404   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8405   // whose low result is fed to the ADDC we are checking.
8406
8407   if (AddcOp0 == MULOp.getValue(0)) {
8408     LoMul = &AddcOp0;
8409     LowAdd = &AddcOp1;
8410   }
8411   if (AddcOp1 == MULOp.getValue(0)) {
8412     LoMul = &AddcOp1;
8413     LowAdd = &AddcOp0;
8414   }
8415
8416   if (!LoMul)
8417     return SDValue();
8418
8419   // Create the merged node.
8420   SelectionDAG &DAG = DCI.DAG;
8421
8422   // Build operand list.
8423   SmallVector<SDValue, 8> Ops;
8424   Ops.push_back(LoMul->getOperand(0));
8425   Ops.push_back(LoMul->getOperand(1));
8426   Ops.push_back(*LowAdd);
8427   Ops.push_back(*HiAdd);
8428
8429   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8430                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8431
8432   // Replace the ADDs' nodes uses by the MLA node's values.
8433   SDValue HiMLALResult(MLALNode.getNode(), 1);
8434   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8435
8436   SDValue LoMLALResult(MLALNode.getNode(), 0);
8437   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8438
8439   // Return original node to notify the driver to stop replacing.
8440   SDValue resNode(AddcNode, 0);
8441   return resNode;
8442 }
8443
8444 /// PerformADDCCombine - Target-specific dag combine transform from
8445 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8446 static SDValue PerformADDCCombine(SDNode *N,
8447                                  TargetLowering::DAGCombinerInfo &DCI,
8448                                  const ARMSubtarget *Subtarget) {
8449
8450   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8451
8452 }
8453
8454 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8455 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8456 /// called with the default operands, and if that fails, with commuted
8457 /// operands.
8458 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8459                                           TargetLowering::DAGCombinerInfo &DCI,
8460                                           const ARMSubtarget *Subtarget){
8461
8462   // Attempt to create vpaddl for this add.
8463   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8464   if (Result.getNode())
8465     return Result;
8466
8467   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8468   if (N0.getNode()->hasOneUse()) {
8469     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8470     if (Result.getNode()) return Result;
8471   }
8472   return SDValue();
8473 }
8474
8475 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8476 ///
8477 static SDValue PerformADDCombine(SDNode *N,
8478                                  TargetLowering::DAGCombinerInfo &DCI,
8479                                  const ARMSubtarget *Subtarget) {
8480   SDValue N0 = N->getOperand(0);
8481   SDValue N1 = N->getOperand(1);
8482
8483   // First try with the default operand order.
8484   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8485   if (Result.getNode())
8486     return Result;
8487
8488   // If that didn't work, try again with the operands commuted.
8489   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8490 }
8491
8492 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8493 ///
8494 static SDValue PerformSUBCombine(SDNode *N,
8495                                  TargetLowering::DAGCombinerInfo &DCI) {
8496   SDValue N0 = N->getOperand(0);
8497   SDValue N1 = N->getOperand(1);
8498
8499   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8500   if (N1.getNode()->hasOneUse()) {
8501     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8502     if (Result.getNode()) return Result;
8503   }
8504
8505   return SDValue();
8506 }
8507
8508 /// PerformVMULCombine
8509 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8510 /// special multiplier accumulator forwarding.
8511 ///   vmul d3, d0, d2
8512 ///   vmla d3, d1, d2
8513 /// is faster than
8514 ///   vadd d3, d0, d1
8515 ///   vmul d3, d3, d2
8516 //  However, for (A + B) * (A + B),
8517 //    vadd d2, d0, d1
8518 //    vmul d3, d0, d2
8519 //    vmla d3, d1, d2
8520 //  is slower than
8521 //    vadd d2, d0, d1
8522 //    vmul d3, d2, d2
8523 static SDValue PerformVMULCombine(SDNode *N,
8524                                   TargetLowering::DAGCombinerInfo &DCI,
8525                                   const ARMSubtarget *Subtarget) {
8526   if (!Subtarget->hasVMLxForwarding())
8527     return SDValue();
8528
8529   SelectionDAG &DAG = DCI.DAG;
8530   SDValue N0 = N->getOperand(0);
8531   SDValue N1 = N->getOperand(1);
8532   unsigned Opcode = N0.getOpcode();
8533   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8534       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8535     Opcode = N1.getOpcode();
8536     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8537         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8538       return SDValue();
8539     std::swap(N0, N1);
8540   }
8541
8542   if (N0 == N1)
8543     return SDValue();
8544
8545   EVT VT = N->getValueType(0);
8546   SDLoc DL(N);
8547   SDValue N00 = N0->getOperand(0);
8548   SDValue N01 = N0->getOperand(1);
8549   return DAG.getNode(Opcode, DL, VT,
8550                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8551                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8552 }
8553
8554 static SDValue PerformMULCombine(SDNode *N,
8555                                  TargetLowering::DAGCombinerInfo &DCI,
8556                                  const ARMSubtarget *Subtarget) {
8557   SelectionDAG &DAG = DCI.DAG;
8558
8559   if (Subtarget->isThumb1Only())
8560     return SDValue();
8561
8562   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8563     return SDValue();
8564
8565   EVT VT = N->getValueType(0);
8566   if (VT.is64BitVector() || VT.is128BitVector())
8567     return PerformVMULCombine(N, DCI, Subtarget);
8568   if (VT != MVT::i32)
8569     return SDValue();
8570
8571   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8572   if (!C)
8573     return SDValue();
8574
8575   int64_t MulAmt = C->getSExtValue();
8576   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8577
8578   ShiftAmt = ShiftAmt & (32 - 1);
8579   SDValue V = N->getOperand(0);
8580   SDLoc DL(N);
8581
8582   SDValue Res;
8583   MulAmt >>= ShiftAmt;
8584
8585   if (MulAmt >= 0) {
8586     if (isPowerOf2_32(MulAmt - 1)) {
8587       // (mul x, 2^N + 1) => (add (shl x, N), x)
8588       Res = DAG.getNode(ISD::ADD, DL, VT,
8589                         V,
8590                         DAG.getNode(ISD::SHL, DL, VT,
8591                                     V,
8592                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8593                                                     MVT::i32)));
8594     } else if (isPowerOf2_32(MulAmt + 1)) {
8595       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8596       Res = DAG.getNode(ISD::SUB, DL, VT,
8597                         DAG.getNode(ISD::SHL, DL, VT,
8598                                     V,
8599                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8600                                                     MVT::i32)),
8601                         V);
8602     } else
8603       return SDValue();
8604   } else {
8605     uint64_t MulAmtAbs = -MulAmt;
8606     if (isPowerOf2_32(MulAmtAbs + 1)) {
8607       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8608       Res = DAG.getNode(ISD::SUB, DL, VT,
8609                         V,
8610                         DAG.getNode(ISD::SHL, DL, VT,
8611                                     V,
8612                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8613                                                     MVT::i32)));
8614     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8615       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8616       Res = DAG.getNode(ISD::ADD, DL, VT,
8617                         V,
8618                         DAG.getNode(ISD::SHL, DL, VT,
8619                                     V,
8620                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8621                                                     MVT::i32)));
8622       Res = DAG.getNode(ISD::SUB, DL, VT,
8623                         DAG.getConstant(0, DL, MVT::i32), Res);
8624
8625     } else
8626       return SDValue();
8627   }
8628
8629   if (ShiftAmt != 0)
8630     Res = DAG.getNode(ISD::SHL, DL, VT,
8631                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8632
8633   // Do not add new nodes to DAG combiner worklist.
8634   DCI.CombineTo(N, Res, false);
8635   return SDValue();
8636 }
8637
8638 static SDValue PerformANDCombine(SDNode *N,
8639                                  TargetLowering::DAGCombinerInfo &DCI,
8640                                  const ARMSubtarget *Subtarget) {
8641
8642   // Attempt to use immediate-form VBIC
8643   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8644   SDLoc dl(N);
8645   EVT VT = N->getValueType(0);
8646   SelectionDAG &DAG = DCI.DAG;
8647
8648   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8649     return SDValue();
8650
8651   APInt SplatBits, SplatUndef;
8652   unsigned SplatBitSize;
8653   bool HasAnyUndefs;
8654   if (BVN &&
8655       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8656     if (SplatBitSize <= 64) {
8657       EVT VbicVT;
8658       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8659                                       SplatUndef.getZExtValue(), SplatBitSize,
8660                                       DAG, dl, VbicVT, VT.is128BitVector(),
8661                                       OtherModImm);
8662       if (Val.getNode()) {
8663         SDValue Input =
8664           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8665         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8666         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8667       }
8668     }
8669   }
8670
8671   if (!Subtarget->isThumb1Only()) {
8672     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8673     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8674     if (Result.getNode())
8675       return Result;
8676   }
8677
8678   return SDValue();
8679 }
8680
8681 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8682 static SDValue PerformORCombine(SDNode *N,
8683                                 TargetLowering::DAGCombinerInfo &DCI,
8684                                 const ARMSubtarget *Subtarget) {
8685   // Attempt to use immediate-form VORR
8686   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8687   SDLoc dl(N);
8688   EVT VT = N->getValueType(0);
8689   SelectionDAG &DAG = DCI.DAG;
8690
8691   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8692     return SDValue();
8693
8694   APInt SplatBits, SplatUndef;
8695   unsigned SplatBitSize;
8696   bool HasAnyUndefs;
8697   if (BVN && Subtarget->hasNEON() &&
8698       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8699     if (SplatBitSize <= 64) {
8700       EVT VorrVT;
8701       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8702                                       SplatUndef.getZExtValue(), SplatBitSize,
8703                                       DAG, dl, VorrVT, VT.is128BitVector(),
8704                                       OtherModImm);
8705       if (Val.getNode()) {
8706         SDValue Input =
8707           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8708         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8709         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8710       }
8711     }
8712   }
8713
8714   if (!Subtarget->isThumb1Only()) {
8715     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8716     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8717     if (Result.getNode())
8718       return Result;
8719   }
8720
8721   // The code below optimizes (or (and X, Y), Z).
8722   // The AND operand needs to have a single user to make these optimizations
8723   // profitable.
8724   SDValue N0 = N->getOperand(0);
8725   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8726     return SDValue();
8727   SDValue N1 = N->getOperand(1);
8728
8729   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8730   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8731       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8732     APInt SplatUndef;
8733     unsigned SplatBitSize;
8734     bool HasAnyUndefs;
8735
8736     APInt SplatBits0, SplatBits1;
8737     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8738     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8739     // Ensure that the second operand of both ands are constants
8740     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8741                                       HasAnyUndefs) && !HasAnyUndefs) {
8742         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8743                                           HasAnyUndefs) && !HasAnyUndefs) {
8744             // Ensure that the bit width of the constants are the same and that
8745             // the splat arguments are logical inverses as per the pattern we
8746             // are trying to simplify.
8747             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8748                 SplatBits0 == ~SplatBits1) {
8749                 // Canonicalize the vector type to make instruction selection
8750                 // simpler.
8751                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8752                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8753                                              N0->getOperand(1),
8754                                              N0->getOperand(0),
8755                                              N1->getOperand(0));
8756                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8757             }
8758         }
8759     }
8760   }
8761
8762   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8763   // reasonable.
8764
8765   // BFI is only available on V6T2+
8766   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8767     return SDValue();
8768
8769   SDLoc DL(N);
8770   // 1) or (and A, mask), val => ARMbfi A, val, mask
8771   //      iff (val & mask) == val
8772   //
8773   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8774   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8775   //          && mask == ~mask2
8776   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8777   //          && ~mask == mask2
8778   //  (i.e., copy a bitfield value into another bitfield of the same width)
8779
8780   if (VT != MVT::i32)
8781     return SDValue();
8782
8783   SDValue N00 = N0.getOperand(0);
8784
8785   // The value and the mask need to be constants so we can verify this is
8786   // actually a bitfield set. If the mask is 0xffff, we can do better
8787   // via a movt instruction, so don't use BFI in that case.
8788   SDValue MaskOp = N0.getOperand(1);
8789   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8790   if (!MaskC)
8791     return SDValue();
8792   unsigned Mask = MaskC->getZExtValue();
8793   if (Mask == 0xffff)
8794     return SDValue();
8795   SDValue Res;
8796   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8797   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8798   if (N1C) {
8799     unsigned Val = N1C->getZExtValue();
8800     if ((Val & ~Mask) != Val)
8801       return SDValue();
8802
8803     if (ARM::isBitFieldInvertedMask(Mask)) {
8804       Val >>= countTrailingZeros(~Mask);
8805
8806       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8807                         DAG.getConstant(Val, DL, MVT::i32),
8808                         DAG.getConstant(Mask, DL, MVT::i32));
8809
8810       // Do not add new nodes to DAG combiner worklist.
8811       DCI.CombineTo(N, Res, false);
8812       return SDValue();
8813     }
8814   } else if (N1.getOpcode() == ISD::AND) {
8815     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8816     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8817     if (!N11C)
8818       return SDValue();
8819     unsigned Mask2 = N11C->getZExtValue();
8820
8821     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8822     // as is to match.
8823     if (ARM::isBitFieldInvertedMask(Mask) &&
8824         (Mask == ~Mask2)) {
8825       // The pack halfword instruction works better for masks that fit it,
8826       // so use that when it's available.
8827       if (Subtarget->hasT2ExtractPack() &&
8828           (Mask == 0xffff || Mask == 0xffff0000))
8829         return SDValue();
8830       // 2a
8831       unsigned amt = countTrailingZeros(Mask2);
8832       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8833                         DAG.getConstant(amt, DL, MVT::i32));
8834       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8835                         DAG.getConstant(Mask, DL, MVT::i32));
8836       // Do not add new nodes to DAG combiner worklist.
8837       DCI.CombineTo(N, Res, false);
8838       return SDValue();
8839     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8840                (~Mask == Mask2)) {
8841       // The pack halfword instruction works better for masks that fit it,
8842       // so use that when it's available.
8843       if (Subtarget->hasT2ExtractPack() &&
8844           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8845         return SDValue();
8846       // 2b
8847       unsigned lsb = countTrailingZeros(Mask);
8848       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8849                         DAG.getConstant(lsb, DL, MVT::i32));
8850       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8851                         DAG.getConstant(Mask2, DL, MVT::i32));
8852       // Do not add new nodes to DAG combiner worklist.
8853       DCI.CombineTo(N, Res, false);
8854       return SDValue();
8855     }
8856   }
8857
8858   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8859       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8860       ARM::isBitFieldInvertedMask(~Mask)) {
8861     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8862     // where lsb(mask) == #shamt and masked bits of B are known zero.
8863     SDValue ShAmt = N00.getOperand(1);
8864     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8865     unsigned LSB = countTrailingZeros(Mask);
8866     if (ShAmtC != LSB)
8867       return SDValue();
8868
8869     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8870                       DAG.getConstant(~Mask, DL, MVT::i32));
8871
8872     // Do not add new nodes to DAG combiner worklist.
8873     DCI.CombineTo(N, Res, false);
8874   }
8875
8876   return SDValue();
8877 }
8878
8879 static SDValue PerformXORCombine(SDNode *N,
8880                                  TargetLowering::DAGCombinerInfo &DCI,
8881                                  const ARMSubtarget *Subtarget) {
8882   EVT VT = N->getValueType(0);
8883   SelectionDAG &DAG = DCI.DAG;
8884
8885   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8886     return SDValue();
8887
8888   if (!Subtarget->isThumb1Only()) {
8889     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8890     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8891     if (Result.getNode())
8892       return Result;
8893   }
8894
8895   return SDValue();
8896 }
8897
8898 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8899 /// the bits being cleared by the AND are not demanded by the BFI.
8900 static SDValue PerformBFICombine(SDNode *N,
8901                                  TargetLowering::DAGCombinerInfo &DCI) {
8902   SDValue N1 = N->getOperand(1);
8903   if (N1.getOpcode() == ISD::AND) {
8904     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8905     if (!N11C)
8906       return SDValue();
8907     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8908     unsigned LSB = countTrailingZeros(~InvMask);
8909     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8910     assert(Width <
8911                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8912            "undefined behavior");
8913     unsigned Mask = (1u << Width) - 1;
8914     unsigned Mask2 = N11C->getZExtValue();
8915     if ((Mask & (~Mask2)) == 0)
8916       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8917                              N->getOperand(0), N1.getOperand(0),
8918                              N->getOperand(2));
8919   }
8920   return SDValue();
8921 }
8922
8923 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8924 /// ARMISD::VMOVRRD.
8925 static SDValue PerformVMOVRRDCombine(SDNode *N,
8926                                      TargetLowering::DAGCombinerInfo &DCI,
8927                                      const ARMSubtarget *Subtarget) {
8928   // vmovrrd(vmovdrr x, y) -> x,y
8929   SDValue InDouble = N->getOperand(0);
8930   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8931     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8932
8933   // vmovrrd(load f64) -> (load i32), (load i32)
8934   SDNode *InNode = InDouble.getNode();
8935   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8936       InNode->getValueType(0) == MVT::f64 &&
8937       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8938       !cast<LoadSDNode>(InNode)->isVolatile()) {
8939     // TODO: Should this be done for non-FrameIndex operands?
8940     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8941
8942     SelectionDAG &DAG = DCI.DAG;
8943     SDLoc DL(LD);
8944     SDValue BasePtr = LD->getBasePtr();
8945     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8946                                  LD->getPointerInfo(), LD->isVolatile(),
8947                                  LD->isNonTemporal(), LD->isInvariant(),
8948                                  LD->getAlignment());
8949
8950     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8951                                     DAG.getConstant(4, DL, MVT::i32));
8952     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8953                                  LD->getPointerInfo(), LD->isVolatile(),
8954                                  LD->isNonTemporal(), LD->isInvariant(),
8955                                  std::min(4U, LD->getAlignment() / 2));
8956
8957     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8958     if (DCI.DAG.getDataLayout().isBigEndian())
8959       std::swap (NewLD1, NewLD2);
8960     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8961     return Result;
8962   }
8963
8964   return SDValue();
8965 }
8966
8967 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8968 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8969 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8970   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8971   SDValue Op0 = N->getOperand(0);
8972   SDValue Op1 = N->getOperand(1);
8973   if (Op0.getOpcode() == ISD::BITCAST)
8974     Op0 = Op0.getOperand(0);
8975   if (Op1.getOpcode() == ISD::BITCAST)
8976     Op1 = Op1.getOperand(0);
8977   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8978       Op0.getNode() == Op1.getNode() &&
8979       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8980     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8981                        N->getValueType(0), Op0.getOperand(0));
8982   return SDValue();
8983 }
8984
8985 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8986 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8987 /// i64 vector to have f64 elements, since the value can then be loaded
8988 /// directly into a VFP register.
8989 static bool hasNormalLoadOperand(SDNode *N) {
8990   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8991   for (unsigned i = 0; i < NumElts; ++i) {
8992     SDNode *Elt = N->getOperand(i).getNode();
8993     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8994       return true;
8995   }
8996   return false;
8997 }
8998
8999 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9000 /// ISD::BUILD_VECTOR.
9001 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9002                                           TargetLowering::DAGCombinerInfo &DCI,
9003                                           const ARMSubtarget *Subtarget) {
9004   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9005   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9006   // into a pair of GPRs, which is fine when the value is used as a scalar,
9007   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9008   SelectionDAG &DAG = DCI.DAG;
9009   if (N->getNumOperands() == 2) {
9010     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9011     if (RV.getNode())
9012       return RV;
9013   }
9014
9015   // Load i64 elements as f64 values so that type legalization does not split
9016   // them up into i32 values.
9017   EVT VT = N->getValueType(0);
9018   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9019     return SDValue();
9020   SDLoc dl(N);
9021   SmallVector<SDValue, 8> Ops;
9022   unsigned NumElts = VT.getVectorNumElements();
9023   for (unsigned i = 0; i < NumElts; ++i) {
9024     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9025     Ops.push_back(V);
9026     // Make the DAGCombiner fold the bitcast.
9027     DCI.AddToWorklist(V.getNode());
9028   }
9029   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9030   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9031   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9032 }
9033
9034 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9035 static SDValue
9036 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9037   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9038   // At that time, we may have inserted bitcasts from integer to float.
9039   // If these bitcasts have survived DAGCombine, change the lowering of this
9040   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9041   // force to use floating point types.
9042
9043   // Make sure we can change the type of the vector.
9044   // This is possible iff:
9045   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9046   //    1.1. Vector is used only once.
9047   //    1.2. Use is a bit convert to an integer type.
9048   // 2. The size of its operands are 32-bits (64-bits are not legal).
9049   EVT VT = N->getValueType(0);
9050   EVT EltVT = VT.getVectorElementType();
9051
9052   // Check 1.1. and 2.
9053   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9054     return SDValue();
9055
9056   // By construction, the input type must be float.
9057   assert(EltVT == MVT::f32 && "Unexpected type!");
9058
9059   // Check 1.2.
9060   SDNode *Use = *N->use_begin();
9061   if (Use->getOpcode() != ISD::BITCAST ||
9062       Use->getValueType(0).isFloatingPoint())
9063     return SDValue();
9064
9065   // Check profitability.
9066   // Model is, if more than half of the relevant operands are bitcast from
9067   // i32, turn the build_vector into a sequence of insert_vector_elt.
9068   // Relevant operands are everything that is not statically
9069   // (i.e., at compile time) bitcasted.
9070   unsigned NumOfBitCastedElts = 0;
9071   unsigned NumElts = VT.getVectorNumElements();
9072   unsigned NumOfRelevantElts = NumElts;
9073   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9074     SDValue Elt = N->getOperand(Idx);
9075     if (Elt->getOpcode() == ISD::BITCAST) {
9076       // Assume only bit cast to i32 will go away.
9077       if (Elt->getOperand(0).getValueType() == MVT::i32)
9078         ++NumOfBitCastedElts;
9079     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9080       // Constants are statically casted, thus do not count them as
9081       // relevant operands.
9082       --NumOfRelevantElts;
9083   }
9084
9085   // Check if more than half of the elements require a non-free bitcast.
9086   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9087     return SDValue();
9088
9089   SelectionDAG &DAG = DCI.DAG;
9090   // Create the new vector type.
9091   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9092   // Check if the type is legal.
9093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9094   if (!TLI.isTypeLegal(VecVT))
9095     return SDValue();
9096
9097   // Combine:
9098   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9099   // => BITCAST INSERT_VECTOR_ELT
9100   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9101   //                      (BITCAST EN), N.
9102   SDValue Vec = DAG.getUNDEF(VecVT);
9103   SDLoc dl(N);
9104   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9105     SDValue V = N->getOperand(Idx);
9106     if (V.getOpcode() == ISD::UNDEF)
9107       continue;
9108     if (V.getOpcode() == ISD::BITCAST &&
9109         V->getOperand(0).getValueType() == MVT::i32)
9110       // Fold obvious case.
9111       V = V.getOperand(0);
9112     else {
9113       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9114       // Make the DAGCombiner fold the bitcasts.
9115       DCI.AddToWorklist(V.getNode());
9116     }
9117     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9118     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9119   }
9120   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9121   // Make the DAGCombiner fold the bitcasts.
9122   DCI.AddToWorklist(Vec.getNode());
9123   return Vec;
9124 }
9125
9126 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9127 /// ISD::INSERT_VECTOR_ELT.
9128 static SDValue PerformInsertEltCombine(SDNode *N,
9129                                        TargetLowering::DAGCombinerInfo &DCI) {
9130   // Bitcast an i64 load inserted into a vector to f64.
9131   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9132   EVT VT = N->getValueType(0);
9133   SDNode *Elt = N->getOperand(1).getNode();
9134   if (VT.getVectorElementType() != MVT::i64 ||
9135       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9136     return SDValue();
9137
9138   SelectionDAG &DAG = DCI.DAG;
9139   SDLoc dl(N);
9140   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9141                                  VT.getVectorNumElements());
9142   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9143   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9144   // Make the DAGCombiner fold the bitcasts.
9145   DCI.AddToWorklist(Vec.getNode());
9146   DCI.AddToWorklist(V.getNode());
9147   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9148                                Vec, V, N->getOperand(2));
9149   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9150 }
9151
9152 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9153 /// ISD::VECTOR_SHUFFLE.
9154 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9155   // The LLVM shufflevector instruction does not require the shuffle mask
9156   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9157   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9158   // operands do not match the mask length, they are extended by concatenating
9159   // them with undef vectors.  That is probably the right thing for other
9160   // targets, but for NEON it is better to concatenate two double-register
9161   // size vector operands into a single quad-register size vector.  Do that
9162   // transformation here:
9163   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9164   //   shuffle(concat(v1, v2), undef)
9165   SDValue Op0 = N->getOperand(0);
9166   SDValue Op1 = N->getOperand(1);
9167   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9168       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9169       Op0.getNumOperands() != 2 ||
9170       Op1.getNumOperands() != 2)
9171     return SDValue();
9172   SDValue Concat0Op1 = Op0.getOperand(1);
9173   SDValue Concat1Op1 = Op1.getOperand(1);
9174   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9175       Concat1Op1.getOpcode() != ISD::UNDEF)
9176     return SDValue();
9177   // Skip the transformation if any of the types are illegal.
9178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9179   EVT VT = N->getValueType(0);
9180   if (!TLI.isTypeLegal(VT) ||
9181       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9182       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9183     return SDValue();
9184
9185   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9186                                   Op0.getOperand(0), Op1.getOperand(0));
9187   // Translate the shuffle mask.
9188   SmallVector<int, 16> NewMask;
9189   unsigned NumElts = VT.getVectorNumElements();
9190   unsigned HalfElts = NumElts/2;
9191   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9192   for (unsigned n = 0; n < NumElts; ++n) {
9193     int MaskElt = SVN->getMaskElt(n);
9194     int NewElt = -1;
9195     if (MaskElt < (int)HalfElts)
9196       NewElt = MaskElt;
9197     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9198       NewElt = HalfElts + MaskElt - NumElts;
9199     NewMask.push_back(NewElt);
9200   }
9201   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9202                               DAG.getUNDEF(VT), NewMask.data());
9203 }
9204
9205 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9206 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9207 /// base address updates.
9208 /// For generic load/stores, the memory type is assumed to be a vector.
9209 /// The caller is assumed to have checked legality.
9210 static SDValue CombineBaseUpdate(SDNode *N,
9211                                  TargetLowering::DAGCombinerInfo &DCI) {
9212   SelectionDAG &DAG = DCI.DAG;
9213   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9214                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9215   const bool isStore = N->getOpcode() == ISD::STORE;
9216   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9217   SDValue Addr = N->getOperand(AddrOpIdx);
9218   MemSDNode *MemN = cast<MemSDNode>(N);
9219   SDLoc dl(N);
9220
9221   // Search for a use of the address operand that is an increment.
9222   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9223          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9224     SDNode *User = *UI;
9225     if (User->getOpcode() != ISD::ADD ||
9226         UI.getUse().getResNo() != Addr.getResNo())
9227       continue;
9228
9229     // Check that the add is independent of the load/store.  Otherwise, folding
9230     // it would create a cycle.
9231     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9232       continue;
9233
9234     // Find the new opcode for the updating load/store.
9235     bool isLoadOp = true;
9236     bool isLaneOp = false;
9237     unsigned NewOpc = 0;
9238     unsigned NumVecs = 0;
9239     if (isIntrinsic) {
9240       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9241       switch (IntNo) {
9242       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9243       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9244         NumVecs = 1; break;
9245       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9246         NumVecs = 2; break;
9247       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9248         NumVecs = 3; break;
9249       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9250         NumVecs = 4; break;
9251       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9252         NumVecs = 2; isLaneOp = true; break;
9253       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9254         NumVecs = 3; isLaneOp = true; break;
9255       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9256         NumVecs = 4; isLaneOp = true; break;
9257       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9258         NumVecs = 1; isLoadOp = false; break;
9259       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9260         NumVecs = 2; isLoadOp = false; break;
9261       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9262         NumVecs = 3; isLoadOp = false; break;
9263       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9264         NumVecs = 4; isLoadOp = false; break;
9265       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9266         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9267       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9268         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9269       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9270         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9271       }
9272     } else {
9273       isLaneOp = true;
9274       switch (N->getOpcode()) {
9275       default: llvm_unreachable("unexpected opcode for Neon base update");
9276       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9277       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9278       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9279       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9280         NumVecs = 1; isLaneOp = false; break;
9281       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9282         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9283       }
9284     }
9285
9286     // Find the size of memory referenced by the load/store.
9287     EVT VecTy;
9288     if (isLoadOp) {
9289       VecTy = N->getValueType(0);
9290     } else if (isIntrinsic) {
9291       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9292     } else {
9293       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9294       VecTy = N->getOperand(1).getValueType();
9295     }
9296
9297     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9298     if (isLaneOp)
9299       NumBytes /= VecTy.getVectorNumElements();
9300
9301     // If the increment is a constant, it must match the memory ref size.
9302     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9303     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9304       uint64_t IncVal = CInc->getZExtValue();
9305       if (IncVal != NumBytes)
9306         continue;
9307     } else if (NumBytes >= 3 * 16) {
9308       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9309       // separate instructions that make it harder to use a non-constant update.
9310       continue;
9311     }
9312
9313     // OK, we found an ADD we can fold into the base update.
9314     // Now, create a _UPD node, taking care of not breaking alignment.
9315
9316     EVT AlignedVecTy = VecTy;
9317     unsigned Alignment = MemN->getAlignment();
9318
9319     // If this is a less-than-standard-aligned load/store, change the type to
9320     // match the standard alignment.
9321     // The alignment is overlooked when selecting _UPD variants; and it's
9322     // easier to introduce bitcasts here than fix that.
9323     // There are 3 ways to get to this base-update combine:
9324     // - intrinsics: they are assumed to be properly aligned (to the standard
9325     //   alignment of the memory type), so we don't need to do anything.
9326     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9327     //   intrinsics, so, likewise, there's nothing to do.
9328     // - generic load/store instructions: the alignment is specified as an
9329     //   explicit operand, rather than implicitly as the standard alignment
9330     //   of the memory type (like the intrisics).  We need to change the
9331     //   memory type to match the explicit alignment.  That way, we don't
9332     //   generate non-standard-aligned ARMISD::VLDx nodes.
9333     if (isa<LSBaseSDNode>(N)) {
9334       if (Alignment == 0)
9335         Alignment = 1;
9336       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9337         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9338         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9339         assert(!isLaneOp && "Unexpected generic load/store lane.");
9340         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9341         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9342       }
9343       // Don't set an explicit alignment on regular load/stores that we want
9344       // to transform to VLD/VST 1_UPD nodes.
9345       // This matches the behavior of regular load/stores, which only get an
9346       // explicit alignment if the MMO alignment is larger than the standard
9347       // alignment of the memory type.
9348       // Intrinsics, however, always get an explicit alignment, set to the
9349       // alignment of the MMO.
9350       Alignment = 1;
9351     }
9352
9353     // Create the new updating load/store node.
9354     // First, create an SDVTList for the new updating node's results.
9355     EVT Tys[6];
9356     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9357     unsigned n;
9358     for (n = 0; n < NumResultVecs; ++n)
9359       Tys[n] = AlignedVecTy;
9360     Tys[n++] = MVT::i32;
9361     Tys[n] = MVT::Other;
9362     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9363
9364     // Then, gather the new node's operands.
9365     SmallVector<SDValue, 8> Ops;
9366     Ops.push_back(N->getOperand(0)); // incoming chain
9367     Ops.push_back(N->getOperand(AddrOpIdx));
9368     Ops.push_back(Inc);
9369
9370     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9371       // Try to match the intrinsic's signature
9372       Ops.push_back(StN->getValue());
9373     } else {
9374       // Loads (and of course intrinsics) match the intrinsics' signature,
9375       // so just add all but the alignment operand.
9376       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9377         Ops.push_back(N->getOperand(i));
9378     }
9379
9380     // For all node types, the alignment operand is always the last one.
9381     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9382
9383     // If this is a non-standard-aligned STORE, the penultimate operand is the
9384     // stored value.  Bitcast it to the aligned type.
9385     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9386       SDValue &StVal = Ops[Ops.size()-2];
9387       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9388     }
9389
9390     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9391                                            Ops, AlignedVecTy,
9392                                            MemN->getMemOperand());
9393
9394     // Update the uses.
9395     SmallVector<SDValue, 5> NewResults;
9396     for (unsigned i = 0; i < NumResultVecs; ++i)
9397       NewResults.push_back(SDValue(UpdN.getNode(), i));
9398
9399     // If this is an non-standard-aligned LOAD, the first result is the loaded
9400     // value.  Bitcast it to the expected result type.
9401     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9402       SDValue &LdVal = NewResults[0];
9403       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9404     }
9405
9406     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9407     DCI.CombineTo(N, NewResults);
9408     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9409
9410     break;
9411   }
9412   return SDValue();
9413 }
9414
9415 static SDValue PerformVLDCombine(SDNode *N,
9416                                  TargetLowering::DAGCombinerInfo &DCI) {
9417   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9418     return SDValue();
9419
9420   return CombineBaseUpdate(N, DCI);
9421 }
9422
9423 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9424 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9425 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9426 /// return true.
9427 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9428   SelectionDAG &DAG = DCI.DAG;
9429   EVT VT = N->getValueType(0);
9430   // vldN-dup instructions only support 64-bit vectors for N > 1.
9431   if (!VT.is64BitVector())
9432     return false;
9433
9434   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9435   SDNode *VLD = N->getOperand(0).getNode();
9436   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9437     return false;
9438   unsigned NumVecs = 0;
9439   unsigned NewOpc = 0;
9440   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9441   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9442     NumVecs = 2;
9443     NewOpc = ARMISD::VLD2DUP;
9444   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9445     NumVecs = 3;
9446     NewOpc = ARMISD::VLD3DUP;
9447   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9448     NumVecs = 4;
9449     NewOpc = ARMISD::VLD4DUP;
9450   } else {
9451     return false;
9452   }
9453
9454   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9455   // numbers match the load.
9456   unsigned VLDLaneNo =
9457     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9458   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9459        UI != UE; ++UI) {
9460     // Ignore uses of the chain result.
9461     if (UI.getUse().getResNo() == NumVecs)
9462       continue;
9463     SDNode *User = *UI;
9464     if (User->getOpcode() != ARMISD::VDUPLANE ||
9465         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9466       return false;
9467   }
9468
9469   // Create the vldN-dup node.
9470   EVT Tys[5];
9471   unsigned n;
9472   for (n = 0; n < NumVecs; ++n)
9473     Tys[n] = VT;
9474   Tys[n] = MVT::Other;
9475   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9476   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9477   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9478   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9479                                            Ops, VLDMemInt->getMemoryVT(),
9480                                            VLDMemInt->getMemOperand());
9481
9482   // Update the uses.
9483   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9484        UI != UE; ++UI) {
9485     unsigned ResNo = UI.getUse().getResNo();
9486     // Ignore uses of the chain result.
9487     if (ResNo == NumVecs)
9488       continue;
9489     SDNode *User = *UI;
9490     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9491   }
9492
9493   // Now the vldN-lane intrinsic is dead except for its chain result.
9494   // Update uses of the chain.
9495   std::vector<SDValue> VLDDupResults;
9496   for (unsigned n = 0; n < NumVecs; ++n)
9497     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9498   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9499   DCI.CombineTo(VLD, VLDDupResults);
9500
9501   return true;
9502 }
9503
9504 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9505 /// ARMISD::VDUPLANE.
9506 static SDValue PerformVDUPLANECombine(SDNode *N,
9507                                       TargetLowering::DAGCombinerInfo &DCI) {
9508   SDValue Op = N->getOperand(0);
9509
9510   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9511   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9512   if (CombineVLDDUP(N, DCI))
9513     return SDValue(N, 0);
9514
9515   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9516   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9517   while (Op.getOpcode() == ISD::BITCAST)
9518     Op = Op.getOperand(0);
9519   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9520     return SDValue();
9521
9522   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9523   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9524   // The canonical VMOV for a zero vector uses a 32-bit element size.
9525   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9526   unsigned EltBits;
9527   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9528     EltSize = 8;
9529   EVT VT = N->getValueType(0);
9530   if (EltSize > VT.getVectorElementType().getSizeInBits())
9531     return SDValue();
9532
9533   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9534 }
9535
9536 static SDValue PerformLOADCombine(SDNode *N,
9537                                   TargetLowering::DAGCombinerInfo &DCI) {
9538   EVT VT = N->getValueType(0);
9539
9540   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9541   if (ISD::isNormalLoad(N) && VT.isVector() &&
9542       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9543     return CombineBaseUpdate(N, DCI);
9544
9545   return SDValue();
9546 }
9547
9548 /// PerformSTORECombine - Target-specific dag combine xforms for
9549 /// ISD::STORE.
9550 static SDValue PerformSTORECombine(SDNode *N,
9551                                    TargetLowering::DAGCombinerInfo &DCI) {
9552   StoreSDNode *St = cast<StoreSDNode>(N);
9553   if (St->isVolatile())
9554     return SDValue();
9555
9556   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9557   // pack all of the elements in one place.  Next, store to memory in fewer
9558   // chunks.
9559   SDValue StVal = St->getValue();
9560   EVT VT = StVal.getValueType();
9561   if (St->isTruncatingStore() && VT.isVector()) {
9562     SelectionDAG &DAG = DCI.DAG;
9563     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9564     EVT StVT = St->getMemoryVT();
9565     unsigned NumElems = VT.getVectorNumElements();
9566     assert(StVT != VT && "Cannot truncate to the same type");
9567     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9568     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9569
9570     // From, To sizes and ElemCount must be pow of two
9571     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9572
9573     // We are going to use the original vector elt for storing.
9574     // Accumulated smaller vector elements must be a multiple of the store size.
9575     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9576
9577     unsigned SizeRatio  = FromEltSz / ToEltSz;
9578     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9579
9580     // Create a type on which we perform the shuffle.
9581     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9582                                      NumElems*SizeRatio);
9583     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9584
9585     SDLoc DL(St);
9586     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9587     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9588     for (unsigned i = 0; i < NumElems; ++i)
9589       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9590                           ? (i + 1) * SizeRatio - 1
9591                           : i * SizeRatio;
9592
9593     // Can't shuffle using an illegal type.
9594     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9595
9596     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9597                                 DAG.getUNDEF(WideVec.getValueType()),
9598                                 ShuffleVec.data());
9599     // At this point all of the data is stored at the bottom of the
9600     // register. We now need to save it to mem.
9601
9602     // Find the largest store unit
9603     MVT StoreType = MVT::i8;
9604     for (MVT Tp : MVT::integer_valuetypes()) {
9605       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9606         StoreType = Tp;
9607     }
9608     // Didn't find a legal store type.
9609     if (!TLI.isTypeLegal(StoreType))
9610       return SDValue();
9611
9612     // Bitcast the original vector into a vector of store-size units
9613     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9614             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9615     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9616     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9617     SmallVector<SDValue, 8> Chains;
9618     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9619                                         TLI.getPointerTy(DAG.getDataLayout()));
9620     SDValue BasePtr = St->getBasePtr();
9621
9622     // Perform one or more big stores into memory.
9623     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9624     for (unsigned I = 0; I < E; I++) {
9625       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9626                                    StoreType, ShuffWide,
9627                                    DAG.getIntPtrConstant(I, DL));
9628       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9629                                 St->getPointerInfo(), St->isVolatile(),
9630                                 St->isNonTemporal(), St->getAlignment());
9631       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9632                             Increment);
9633       Chains.push_back(Ch);
9634     }
9635     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9636   }
9637
9638   if (!ISD::isNormalStore(St))
9639     return SDValue();
9640
9641   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9642   // ARM stores of arguments in the same cache line.
9643   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9644       StVal.getNode()->hasOneUse()) {
9645     SelectionDAG  &DAG = DCI.DAG;
9646     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9647     SDLoc DL(St);
9648     SDValue BasePtr = St->getBasePtr();
9649     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9650                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9651                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9652                                   St->isNonTemporal(), St->getAlignment());
9653
9654     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9655                                     DAG.getConstant(4, DL, MVT::i32));
9656     return DAG.getStore(NewST1.getValue(0), DL,
9657                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9658                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9659                         St->isNonTemporal(),
9660                         std::min(4U, St->getAlignment() / 2));
9661   }
9662
9663   if (StVal.getValueType() == MVT::i64 &&
9664       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9665
9666     // Bitcast an i64 store extracted from a vector to f64.
9667     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9668     SelectionDAG &DAG = DCI.DAG;
9669     SDLoc dl(StVal);
9670     SDValue IntVec = StVal.getOperand(0);
9671     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9672                                    IntVec.getValueType().getVectorNumElements());
9673     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9674     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9675                                  Vec, StVal.getOperand(1));
9676     dl = SDLoc(N);
9677     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9678     // Make the DAGCombiner fold the bitcasts.
9679     DCI.AddToWorklist(Vec.getNode());
9680     DCI.AddToWorklist(ExtElt.getNode());
9681     DCI.AddToWorklist(V.getNode());
9682     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9683                         St->getPointerInfo(), St->isVolatile(),
9684                         St->isNonTemporal(), St->getAlignment(),
9685                         St->getAAInfo());
9686   }
9687
9688   // If this is a legal vector store, try to combine it into a VST1_UPD.
9689   if (ISD::isNormalStore(N) && VT.isVector() &&
9690       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9691     return CombineBaseUpdate(N, DCI);
9692
9693   return SDValue();
9694 }
9695
9696 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9697 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9698 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9699 {
9700   integerPart cN;
9701   integerPart c0 = 0;
9702   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9703        I != E; I++) {
9704     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9705     if (!C)
9706       return false;
9707
9708     bool isExact;
9709     APFloat APF = C->getValueAPF();
9710     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9711         != APFloat::opOK || !isExact)
9712       return false;
9713
9714     c0 = (I == 0) ? cN : c0;
9715     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9716       return false;
9717   }
9718   C = c0;
9719   return true;
9720 }
9721
9722 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9723 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9724 /// when the VMUL has a constant operand that is a power of 2.
9725 ///
9726 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9727 ///  vmul.f32        d16, d17, d16
9728 ///  vcvt.s32.f32    d16, d16
9729 /// becomes:
9730 ///  vcvt.s32.f32    d16, d16, #3
9731 static SDValue PerformVCVTCombine(SDNode *N,
9732                                   TargetLowering::DAGCombinerInfo &DCI,
9733                                   const ARMSubtarget *Subtarget) {
9734   SelectionDAG &DAG = DCI.DAG;
9735   SDValue Op = N->getOperand(0);
9736
9737   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9738       Op.getOpcode() != ISD::FMUL)
9739     return SDValue();
9740
9741   uint64_t C;
9742   SDValue N0 = Op->getOperand(0);
9743   SDValue ConstVec = Op->getOperand(1);
9744   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9745
9746   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9747       !isConstVecPow2(ConstVec, isSigned, C))
9748     return SDValue();
9749
9750   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9751   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9752   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9753   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9754       NumLanes > 4) {
9755     // These instructions only exist converting from f32 to i32. We can handle
9756     // smaller integers by generating an extra truncate, but larger ones would
9757     // be lossy. We also can't handle more then 4 lanes, since these intructions
9758     // only support v2i32/v4i32 types.
9759     return SDValue();
9760   }
9761
9762   SDLoc dl(N);
9763   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9764     Intrinsic::arm_neon_vcvtfp2fxu;
9765   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9766                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9767                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9768                                  N0,
9769                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9770
9771   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9772     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9773
9774   return FixConv;
9775 }
9776
9777 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9778 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9779 /// when the VDIV has a constant operand that is a power of 2.
9780 ///
9781 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9782 ///  vcvt.f32.s32    d16, d16
9783 ///  vdiv.f32        d16, d17, d16
9784 /// becomes:
9785 ///  vcvt.f32.s32    d16, d16, #3
9786 static SDValue PerformVDIVCombine(SDNode *N,
9787                                   TargetLowering::DAGCombinerInfo &DCI,
9788                                   const ARMSubtarget *Subtarget) {
9789   SelectionDAG &DAG = DCI.DAG;
9790   SDValue Op = N->getOperand(0);
9791   unsigned OpOpcode = Op.getNode()->getOpcode();
9792
9793   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9794       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9795     return SDValue();
9796
9797   uint64_t C;
9798   SDValue ConstVec = N->getOperand(1);
9799   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9800
9801   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9802       !isConstVecPow2(ConstVec, isSigned, C))
9803     return SDValue();
9804
9805   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9806   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9807   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9808     // These instructions only exist converting from i32 to f32. We can handle
9809     // smaller integers by generating an extra extend, but larger ones would
9810     // be lossy.
9811     return SDValue();
9812   }
9813
9814   SDLoc dl(N);
9815   SDValue ConvInput = Op.getOperand(0);
9816   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9817   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9818     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9819                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9820                             ConvInput);
9821
9822   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9823     Intrinsic::arm_neon_vcvtfxu2fp;
9824   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9825                      Op.getValueType(),
9826                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9827                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9828 }
9829
9830 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9831 /// operand of a vector shift operation, where all the elements of the
9832 /// build_vector must have the same constant integer value.
9833 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9834   // Ignore bit_converts.
9835   while (Op.getOpcode() == ISD::BITCAST)
9836     Op = Op.getOperand(0);
9837   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9838   APInt SplatBits, SplatUndef;
9839   unsigned SplatBitSize;
9840   bool HasAnyUndefs;
9841   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9842                                       HasAnyUndefs, ElementBits) ||
9843       SplatBitSize > ElementBits)
9844     return false;
9845   Cnt = SplatBits.getSExtValue();
9846   return true;
9847 }
9848
9849 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9850 /// operand of a vector shift left operation.  That value must be in the range:
9851 ///   0 <= Value < ElementBits for a left shift; or
9852 ///   0 <= Value <= ElementBits for a long left shift.
9853 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9854   assert(VT.isVector() && "vector shift count is not a vector type");
9855   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9856   if (! getVShiftImm(Op, ElementBits, Cnt))
9857     return false;
9858   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9859 }
9860
9861 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9862 /// operand of a vector shift right operation.  For a shift opcode, the value
9863 /// is positive, but for an intrinsic the value count must be negative. The
9864 /// absolute value must be in the range:
9865 ///   1 <= |Value| <= ElementBits for a right shift; or
9866 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9867 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9868                          int64_t &Cnt) {
9869   assert(VT.isVector() && "vector shift count is not a vector type");
9870   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9871   if (! getVShiftImm(Op, ElementBits, Cnt))
9872     return false;
9873   if (!isIntrinsic)
9874     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9875   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9876     Cnt = -Cnt;
9877     return true;
9878   }
9879   return false;
9880 }
9881
9882 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9883 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9884   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9885   switch (IntNo) {
9886   default:
9887     // Don't do anything for most intrinsics.
9888     break;
9889
9890   case Intrinsic::arm_neon_vabds:
9891     if (!N->getValueType(0).isInteger())
9892       return SDValue();
9893     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9894                        N->getOperand(1), N->getOperand(2));
9895   case Intrinsic::arm_neon_vabdu:
9896     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9897                        N->getOperand(1), N->getOperand(2));
9898
9899   // Vector shifts: check for immediate versions and lower them.
9900   // Note: This is done during DAG combining instead of DAG legalizing because
9901   // the build_vectors for 64-bit vector element shift counts are generally
9902   // not legal, and it is hard to see their values after they get legalized to
9903   // loads from a constant pool.
9904   case Intrinsic::arm_neon_vshifts:
9905   case Intrinsic::arm_neon_vshiftu:
9906   case Intrinsic::arm_neon_vrshifts:
9907   case Intrinsic::arm_neon_vrshiftu:
9908   case Intrinsic::arm_neon_vrshiftn:
9909   case Intrinsic::arm_neon_vqshifts:
9910   case Intrinsic::arm_neon_vqshiftu:
9911   case Intrinsic::arm_neon_vqshiftsu:
9912   case Intrinsic::arm_neon_vqshiftns:
9913   case Intrinsic::arm_neon_vqshiftnu:
9914   case Intrinsic::arm_neon_vqshiftnsu:
9915   case Intrinsic::arm_neon_vqrshiftns:
9916   case Intrinsic::arm_neon_vqrshiftnu:
9917   case Intrinsic::arm_neon_vqrshiftnsu: {
9918     EVT VT = N->getOperand(1).getValueType();
9919     int64_t Cnt;
9920     unsigned VShiftOpc = 0;
9921
9922     switch (IntNo) {
9923     case Intrinsic::arm_neon_vshifts:
9924     case Intrinsic::arm_neon_vshiftu:
9925       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9926         VShiftOpc = ARMISD::VSHL;
9927         break;
9928       }
9929       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9930         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9931                      ARMISD::VSHRs : ARMISD::VSHRu);
9932         break;
9933       }
9934       return SDValue();
9935
9936     case Intrinsic::arm_neon_vrshifts:
9937     case Intrinsic::arm_neon_vrshiftu:
9938       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9939         break;
9940       return SDValue();
9941
9942     case Intrinsic::arm_neon_vqshifts:
9943     case Intrinsic::arm_neon_vqshiftu:
9944       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9945         break;
9946       return SDValue();
9947
9948     case Intrinsic::arm_neon_vqshiftsu:
9949       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9950         break;
9951       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9952
9953     case Intrinsic::arm_neon_vrshiftn:
9954     case Intrinsic::arm_neon_vqshiftns:
9955     case Intrinsic::arm_neon_vqshiftnu:
9956     case Intrinsic::arm_neon_vqshiftnsu:
9957     case Intrinsic::arm_neon_vqrshiftns:
9958     case Intrinsic::arm_neon_vqrshiftnu:
9959     case Intrinsic::arm_neon_vqrshiftnsu:
9960       // Narrowing shifts require an immediate right shift.
9961       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9962         break;
9963       llvm_unreachable("invalid shift count for narrowing vector shift "
9964                        "intrinsic");
9965
9966     default:
9967       llvm_unreachable("unhandled vector shift");
9968     }
9969
9970     switch (IntNo) {
9971     case Intrinsic::arm_neon_vshifts:
9972     case Intrinsic::arm_neon_vshiftu:
9973       // Opcode already set above.
9974       break;
9975     case Intrinsic::arm_neon_vrshifts:
9976       VShiftOpc = ARMISD::VRSHRs; break;
9977     case Intrinsic::arm_neon_vrshiftu:
9978       VShiftOpc = ARMISD::VRSHRu; break;
9979     case Intrinsic::arm_neon_vrshiftn:
9980       VShiftOpc = ARMISD::VRSHRN; break;
9981     case Intrinsic::arm_neon_vqshifts:
9982       VShiftOpc = ARMISD::VQSHLs; break;
9983     case Intrinsic::arm_neon_vqshiftu:
9984       VShiftOpc = ARMISD::VQSHLu; break;
9985     case Intrinsic::arm_neon_vqshiftsu:
9986       VShiftOpc = ARMISD::VQSHLsu; break;
9987     case Intrinsic::arm_neon_vqshiftns:
9988       VShiftOpc = ARMISD::VQSHRNs; break;
9989     case Intrinsic::arm_neon_vqshiftnu:
9990       VShiftOpc = ARMISD::VQSHRNu; break;
9991     case Intrinsic::arm_neon_vqshiftnsu:
9992       VShiftOpc = ARMISD::VQSHRNsu; break;
9993     case Intrinsic::arm_neon_vqrshiftns:
9994       VShiftOpc = ARMISD::VQRSHRNs; break;
9995     case Intrinsic::arm_neon_vqrshiftnu:
9996       VShiftOpc = ARMISD::VQRSHRNu; break;
9997     case Intrinsic::arm_neon_vqrshiftnsu:
9998       VShiftOpc = ARMISD::VQRSHRNsu; break;
9999     }
10000
10001     SDLoc dl(N);
10002     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10003                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10004   }
10005
10006   case Intrinsic::arm_neon_vshiftins: {
10007     EVT VT = N->getOperand(1).getValueType();
10008     int64_t Cnt;
10009     unsigned VShiftOpc = 0;
10010
10011     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10012       VShiftOpc = ARMISD::VSLI;
10013     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10014       VShiftOpc = ARMISD::VSRI;
10015     else {
10016       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10017     }
10018
10019     SDLoc dl(N);
10020     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10021                        N->getOperand(1), N->getOperand(2),
10022                        DAG.getConstant(Cnt, dl, MVT::i32));
10023   }
10024
10025   case Intrinsic::arm_neon_vqrshifts:
10026   case Intrinsic::arm_neon_vqrshiftu:
10027     // No immediate versions of these to check for.
10028     break;
10029   }
10030
10031   return SDValue();
10032 }
10033
10034 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10035 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10036 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10037 /// vector element shift counts are generally not legal, and it is hard to see
10038 /// their values after they get legalized to loads from a constant pool.
10039 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10040                                    const ARMSubtarget *ST) {
10041   EVT VT = N->getValueType(0);
10042   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10043     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10044     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10045     SDValue N1 = N->getOperand(1);
10046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10047       SDValue N0 = N->getOperand(0);
10048       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10049           DAG.MaskedValueIsZero(N0.getOperand(0),
10050                                 APInt::getHighBitsSet(32, 16)))
10051         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10052     }
10053   }
10054
10055   // Nothing to be done for scalar shifts.
10056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10057   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10058     return SDValue();
10059
10060   assert(ST->hasNEON() && "unexpected vector shift");
10061   int64_t Cnt;
10062
10063   switch (N->getOpcode()) {
10064   default: llvm_unreachable("unexpected shift opcode");
10065
10066   case ISD::SHL:
10067     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10068       SDLoc dl(N);
10069       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10070                          DAG.getConstant(Cnt, dl, MVT::i32));
10071     }
10072     break;
10073
10074   case ISD::SRA:
10075   case ISD::SRL:
10076     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10077       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10078                             ARMISD::VSHRs : ARMISD::VSHRu);
10079       SDLoc dl(N);
10080       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10081                          DAG.getConstant(Cnt, dl, MVT::i32));
10082     }
10083   }
10084   return SDValue();
10085 }
10086
10087 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10088 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10089 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10090                                     const ARMSubtarget *ST) {
10091   SDValue N0 = N->getOperand(0);
10092
10093   // Check for sign- and zero-extensions of vector extract operations of 8-
10094   // and 16-bit vector elements.  NEON supports these directly.  They are
10095   // handled during DAG combining because type legalization will promote them
10096   // to 32-bit types and it is messy to recognize the operations after that.
10097   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10098     SDValue Vec = N0.getOperand(0);
10099     SDValue Lane = N0.getOperand(1);
10100     EVT VT = N->getValueType(0);
10101     EVT EltVT = N0.getValueType();
10102     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10103
10104     if (VT == MVT::i32 &&
10105         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10106         TLI.isTypeLegal(Vec.getValueType()) &&
10107         isa<ConstantSDNode>(Lane)) {
10108
10109       unsigned Opc = 0;
10110       switch (N->getOpcode()) {
10111       default: llvm_unreachable("unexpected opcode");
10112       case ISD::SIGN_EXTEND:
10113         Opc = ARMISD::VGETLANEs;
10114         break;
10115       case ISD::ZERO_EXTEND:
10116       case ISD::ANY_EXTEND:
10117         Opc = ARMISD::VGETLANEu;
10118         break;
10119       }
10120       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10121     }
10122   }
10123
10124   return SDValue();
10125 }
10126
10127 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10128 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10129 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10130                                        const ARMSubtarget *ST) {
10131   // If the target supports NEON, try to use vmax/vmin instructions for f32
10132   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10133   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10134   // a NaN; only do the transformation when it matches that behavior.
10135
10136   // For now only do this when using NEON for FP operations; if using VFP, it
10137   // is not obvious that the benefit outweighs the cost of switching to the
10138   // NEON pipeline.
10139   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10140       N->getValueType(0) != MVT::f32)
10141     return SDValue();
10142
10143   SDValue CondLHS = N->getOperand(0);
10144   SDValue CondRHS = N->getOperand(1);
10145   SDValue LHS = N->getOperand(2);
10146   SDValue RHS = N->getOperand(3);
10147   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10148
10149   unsigned Opcode = 0;
10150   bool IsReversed;
10151   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10152     IsReversed = false; // x CC y ? x : y
10153   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10154     IsReversed = true ; // x CC y ? y : x
10155   } else {
10156     return SDValue();
10157   }
10158
10159   bool IsUnordered;
10160   switch (CC) {
10161   default: break;
10162   case ISD::SETOLT:
10163   case ISD::SETOLE:
10164   case ISD::SETLT:
10165   case ISD::SETLE:
10166   case ISD::SETULT:
10167   case ISD::SETULE:
10168     // If LHS is NaN, an ordered comparison will be false and the result will
10169     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10170     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10171     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10172     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10173       break;
10174     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10175     // will return -0, so vmin can only be used for unsafe math or if one of
10176     // the operands is known to be nonzero.
10177     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10178         !DAG.getTarget().Options.UnsafeFPMath &&
10179         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10180       break;
10181     Opcode = IsReversed ? ISD::FMAXNAN : ISD::FMINNAN;
10182     break;
10183
10184   case ISD::SETOGT:
10185   case ISD::SETOGE:
10186   case ISD::SETGT:
10187   case ISD::SETGE:
10188   case ISD::SETUGT:
10189   case ISD::SETUGE:
10190     // If LHS is NaN, an ordered comparison will be false and the result will
10191     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10192     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10193     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10194     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10195       break;
10196     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10197     // will return +0, so vmax can only be used for unsafe math or if one of
10198     // the operands is known to be nonzero.
10199     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10200         !DAG.getTarget().Options.UnsafeFPMath &&
10201         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10202       break;
10203     Opcode = IsReversed ? ISD::FMINNAN : ISD::FMAXNAN;
10204     break;
10205   }
10206
10207   if (!Opcode)
10208     return SDValue();
10209   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10210 }
10211
10212 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10213 SDValue
10214 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10215   SDValue Cmp = N->getOperand(4);
10216   if (Cmp.getOpcode() != ARMISD::CMPZ)
10217     // Only looking at EQ and NE cases.
10218     return SDValue();
10219
10220   EVT VT = N->getValueType(0);
10221   SDLoc dl(N);
10222   SDValue LHS = Cmp.getOperand(0);
10223   SDValue RHS = Cmp.getOperand(1);
10224   SDValue FalseVal = N->getOperand(0);
10225   SDValue TrueVal = N->getOperand(1);
10226   SDValue ARMcc = N->getOperand(2);
10227   ARMCC::CondCodes CC =
10228     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10229
10230   // Simplify
10231   //   mov     r1, r0
10232   //   cmp     r1, x
10233   //   mov     r0, y
10234   //   moveq   r0, x
10235   // to
10236   //   cmp     r0, x
10237   //   movne   r0, y
10238   //
10239   //   mov     r1, r0
10240   //   cmp     r1, x
10241   //   mov     r0, x
10242   //   movne   r0, y
10243   // to
10244   //   cmp     r0, x
10245   //   movne   r0, y
10246   /// FIXME: Turn this into a target neutral optimization?
10247   SDValue Res;
10248   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10249     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10250                       N->getOperand(3), Cmp);
10251   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10252     SDValue ARMcc;
10253     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10254     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10255                       N->getOperand(3), NewCmp);
10256   }
10257
10258   if (Res.getNode()) {
10259     APInt KnownZero, KnownOne;
10260     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10261     // Capture demanded bits information that would be otherwise lost.
10262     if (KnownZero == 0xfffffffe)
10263       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10264                         DAG.getValueType(MVT::i1));
10265     else if (KnownZero == 0xffffff00)
10266       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10267                         DAG.getValueType(MVT::i8));
10268     else if (KnownZero == 0xffff0000)
10269       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10270                         DAG.getValueType(MVT::i16));
10271   }
10272
10273   return Res;
10274 }
10275
10276 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10277                                              DAGCombinerInfo &DCI) const {
10278   switch (N->getOpcode()) {
10279   default: break;
10280   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10281   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10282   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10283   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10284   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10285   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10286   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10287   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10288   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10289   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10290   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10291   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10292   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10293   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10294   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10295   case ISD::FP_TO_SINT:
10296   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10297   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10298   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10299   case ISD::SHL:
10300   case ISD::SRA:
10301   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10302   case ISD::SIGN_EXTEND:
10303   case ISD::ZERO_EXTEND:
10304   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10305   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10306   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10307   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10308   case ARMISD::VLD2DUP:
10309   case ARMISD::VLD3DUP:
10310   case ARMISD::VLD4DUP:
10311     return PerformVLDCombine(N, DCI);
10312   case ARMISD::BUILD_VECTOR:
10313     return PerformARMBUILD_VECTORCombine(N, DCI);
10314   case ISD::INTRINSIC_VOID:
10315   case ISD::INTRINSIC_W_CHAIN:
10316     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10317     case Intrinsic::arm_neon_vld1:
10318     case Intrinsic::arm_neon_vld2:
10319     case Intrinsic::arm_neon_vld3:
10320     case Intrinsic::arm_neon_vld4:
10321     case Intrinsic::arm_neon_vld2lane:
10322     case Intrinsic::arm_neon_vld3lane:
10323     case Intrinsic::arm_neon_vld4lane:
10324     case Intrinsic::arm_neon_vst1:
10325     case Intrinsic::arm_neon_vst2:
10326     case Intrinsic::arm_neon_vst3:
10327     case Intrinsic::arm_neon_vst4:
10328     case Intrinsic::arm_neon_vst2lane:
10329     case Intrinsic::arm_neon_vst3lane:
10330     case Intrinsic::arm_neon_vst4lane:
10331       return PerformVLDCombine(N, DCI);
10332     default: break;
10333     }
10334     break;
10335   }
10336   return SDValue();
10337 }
10338
10339 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10340                                                           EVT VT) const {
10341   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10342 }
10343
10344 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10345                                                        unsigned,
10346                                                        unsigned,
10347                                                        bool *Fast) const {
10348   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10349   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10350
10351   switch (VT.getSimpleVT().SimpleTy) {
10352   default:
10353     return false;
10354   case MVT::i8:
10355   case MVT::i16:
10356   case MVT::i32: {
10357     // Unaligned access can use (for example) LRDB, LRDH, LDR
10358     if (AllowsUnaligned) {
10359       if (Fast)
10360         *Fast = Subtarget->hasV7Ops();
10361       return true;
10362     }
10363     return false;
10364   }
10365   case MVT::f64:
10366   case MVT::v2f64: {
10367     // For any little-endian targets with neon, we can support unaligned ld/st
10368     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10369     // A big-endian target may also explicitly support unaligned accesses
10370     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10371       if (Fast)
10372         *Fast = true;
10373       return true;
10374     }
10375     return false;
10376   }
10377   }
10378 }
10379
10380 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10381                        unsigned AlignCheck) {
10382   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10383           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10384 }
10385
10386 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10387                                            unsigned DstAlign, unsigned SrcAlign,
10388                                            bool IsMemset, bool ZeroMemset,
10389                                            bool MemcpyStrSrc,
10390                                            MachineFunction &MF) const {
10391   const Function *F = MF.getFunction();
10392
10393   // See if we can use NEON instructions for this...
10394   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10395       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10396     bool Fast;
10397     if (Size >= 16 &&
10398         (memOpAlign(SrcAlign, DstAlign, 16) ||
10399          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10400       return MVT::v2f64;
10401     } else if (Size >= 8 &&
10402                (memOpAlign(SrcAlign, DstAlign, 8) ||
10403                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10404                  Fast))) {
10405       return MVT::f64;
10406     }
10407   }
10408
10409   // Lowering to i32/i16 if the size permits.
10410   if (Size >= 4)
10411     return MVT::i32;
10412   else if (Size >= 2)
10413     return MVT::i16;
10414
10415   // Let the target-independent logic figure it out.
10416   return MVT::Other;
10417 }
10418
10419 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10420   if (Val.getOpcode() != ISD::LOAD)
10421     return false;
10422
10423   EVT VT1 = Val.getValueType();
10424   if (!VT1.isSimple() || !VT1.isInteger() ||
10425       !VT2.isSimple() || !VT2.isInteger())
10426     return false;
10427
10428   switch (VT1.getSimpleVT().SimpleTy) {
10429   default: break;
10430   case MVT::i1:
10431   case MVT::i8:
10432   case MVT::i16:
10433     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10434     return true;
10435   }
10436
10437   return false;
10438 }
10439
10440 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10441   EVT VT = ExtVal.getValueType();
10442
10443   if (!isTypeLegal(VT))
10444     return false;
10445
10446   // Don't create a loadext if we can fold the extension into a wide/long
10447   // instruction.
10448   // If there's more than one user instruction, the loadext is desirable no
10449   // matter what.  There can be two uses by the same instruction.
10450   if (ExtVal->use_empty() ||
10451       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10452     return true;
10453
10454   SDNode *U = *ExtVal->use_begin();
10455   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10456        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10457     return false;
10458
10459   return true;
10460 }
10461
10462 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10463   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10464     return false;
10465
10466   if (!isTypeLegal(EVT::getEVT(Ty1)))
10467     return false;
10468
10469   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10470
10471   // Assuming the caller doesn't have a zeroext or signext return parameter,
10472   // truncation all the way down to i1 is valid.
10473   return true;
10474 }
10475
10476
10477 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10478   if (V < 0)
10479     return false;
10480
10481   unsigned Scale = 1;
10482   switch (VT.getSimpleVT().SimpleTy) {
10483   default: return false;
10484   case MVT::i1:
10485   case MVT::i8:
10486     // Scale == 1;
10487     break;
10488   case MVT::i16:
10489     // Scale == 2;
10490     Scale = 2;
10491     break;
10492   case MVT::i32:
10493     // Scale == 4;
10494     Scale = 4;
10495     break;
10496   }
10497
10498   if ((V & (Scale - 1)) != 0)
10499     return false;
10500   V /= Scale;
10501   return V == (V & ((1LL << 5) - 1));
10502 }
10503
10504 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10505                                       const ARMSubtarget *Subtarget) {
10506   bool isNeg = false;
10507   if (V < 0) {
10508     isNeg = true;
10509     V = - V;
10510   }
10511
10512   switch (VT.getSimpleVT().SimpleTy) {
10513   default: return false;
10514   case MVT::i1:
10515   case MVT::i8:
10516   case MVT::i16:
10517   case MVT::i32:
10518     // + imm12 or - imm8
10519     if (isNeg)
10520       return V == (V & ((1LL << 8) - 1));
10521     return V == (V & ((1LL << 12) - 1));
10522   case MVT::f32:
10523   case MVT::f64:
10524     // Same as ARM mode. FIXME: NEON?
10525     if (!Subtarget->hasVFP2())
10526       return false;
10527     if ((V & 3) != 0)
10528       return false;
10529     V >>= 2;
10530     return V == (V & ((1LL << 8) - 1));
10531   }
10532 }
10533
10534 /// isLegalAddressImmediate - Return true if the integer value can be used
10535 /// as the offset of the target addressing mode for load / store of the
10536 /// given type.
10537 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10538                                     const ARMSubtarget *Subtarget) {
10539   if (V == 0)
10540     return true;
10541
10542   if (!VT.isSimple())
10543     return false;
10544
10545   if (Subtarget->isThumb1Only())
10546     return isLegalT1AddressImmediate(V, VT);
10547   else if (Subtarget->isThumb2())
10548     return isLegalT2AddressImmediate(V, VT, Subtarget);
10549
10550   // ARM mode.
10551   if (V < 0)
10552     V = - V;
10553   switch (VT.getSimpleVT().SimpleTy) {
10554   default: return false;
10555   case MVT::i1:
10556   case MVT::i8:
10557   case MVT::i32:
10558     // +- imm12
10559     return V == (V & ((1LL << 12) - 1));
10560   case MVT::i16:
10561     // +- imm8
10562     return V == (V & ((1LL << 8) - 1));
10563   case MVT::f32:
10564   case MVT::f64:
10565     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10566       return false;
10567     if ((V & 3) != 0)
10568       return false;
10569     V >>= 2;
10570     return V == (V & ((1LL << 8) - 1));
10571   }
10572 }
10573
10574 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10575                                                       EVT VT) const {
10576   int Scale = AM.Scale;
10577   if (Scale < 0)
10578     return false;
10579
10580   switch (VT.getSimpleVT().SimpleTy) {
10581   default: return false;
10582   case MVT::i1:
10583   case MVT::i8:
10584   case MVT::i16:
10585   case MVT::i32:
10586     if (Scale == 1)
10587       return true;
10588     // r + r << imm
10589     Scale = Scale & ~1;
10590     return Scale == 2 || Scale == 4 || Scale == 8;
10591   case MVT::i64:
10592     // r + r
10593     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10594       return true;
10595     return false;
10596   case MVT::isVoid:
10597     // Note, we allow "void" uses (basically, uses that aren't loads or
10598     // stores), because arm allows folding a scale into many arithmetic
10599     // operations.  This should be made more precise and revisited later.
10600
10601     // Allow r << imm, but the imm has to be a multiple of two.
10602     if (Scale & 1) return false;
10603     return isPowerOf2_32(Scale);
10604   }
10605 }
10606
10607 /// isLegalAddressingMode - Return true if the addressing mode represented
10608 /// by AM is legal for this target, for a load/store of the specified type.
10609 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10610                                               const AddrMode &AM, Type *Ty,
10611                                               unsigned AS) const {
10612   EVT VT = getValueType(DL, Ty, true);
10613   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10614     return false;
10615
10616   // Can never fold addr of global into load/store.
10617   if (AM.BaseGV)
10618     return false;
10619
10620   switch (AM.Scale) {
10621   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10622     break;
10623   case 1:
10624     if (Subtarget->isThumb1Only())
10625       return false;
10626     // FALL THROUGH.
10627   default:
10628     // ARM doesn't support any R+R*scale+imm addr modes.
10629     if (AM.BaseOffs)
10630       return false;
10631
10632     if (!VT.isSimple())
10633       return false;
10634
10635     if (Subtarget->isThumb2())
10636       return isLegalT2ScaledAddressingMode(AM, VT);
10637
10638     int Scale = AM.Scale;
10639     switch (VT.getSimpleVT().SimpleTy) {
10640     default: return false;
10641     case MVT::i1:
10642     case MVT::i8:
10643     case MVT::i32:
10644       if (Scale < 0) Scale = -Scale;
10645       if (Scale == 1)
10646         return true;
10647       // r + r << imm
10648       return isPowerOf2_32(Scale & ~1);
10649     case MVT::i16:
10650     case MVT::i64:
10651       // r + r
10652       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10653         return true;
10654       return false;
10655
10656     case MVT::isVoid:
10657       // Note, we allow "void" uses (basically, uses that aren't loads or
10658       // stores), because arm allows folding a scale into many arithmetic
10659       // operations.  This should be made more precise and revisited later.
10660
10661       // Allow r << imm, but the imm has to be a multiple of two.
10662       if (Scale & 1) return false;
10663       return isPowerOf2_32(Scale);
10664     }
10665   }
10666   return true;
10667 }
10668
10669 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10670 /// icmp immediate, that is the target has icmp instructions which can compare
10671 /// a register against the immediate without having to materialize the
10672 /// immediate into a register.
10673 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10674   // Thumb2 and ARM modes can use cmn for negative immediates.
10675   if (!Subtarget->isThumb())
10676     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10677   if (Subtarget->isThumb2())
10678     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10679   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10680   return Imm >= 0 && Imm <= 255;
10681 }
10682
10683 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10684 /// *or sub* immediate, that is the target has add or sub instructions which can
10685 /// add a register with the immediate without having to materialize the
10686 /// immediate into a register.
10687 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10688   // Same encoding for add/sub, just flip the sign.
10689   int64_t AbsImm = std::abs(Imm);
10690   if (!Subtarget->isThumb())
10691     return ARM_AM::getSOImmVal(AbsImm) != -1;
10692   if (Subtarget->isThumb2())
10693     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10694   // Thumb1 only has 8-bit unsigned immediate.
10695   return AbsImm >= 0 && AbsImm <= 255;
10696 }
10697
10698 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10699                                       bool isSEXTLoad, SDValue &Base,
10700                                       SDValue &Offset, bool &isInc,
10701                                       SelectionDAG &DAG) {
10702   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10703     return false;
10704
10705   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10706     // AddressingMode 3
10707     Base = Ptr->getOperand(0);
10708     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10709       int RHSC = (int)RHS->getZExtValue();
10710       if (RHSC < 0 && RHSC > -256) {
10711         assert(Ptr->getOpcode() == ISD::ADD);
10712         isInc = false;
10713         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10714         return true;
10715       }
10716     }
10717     isInc = (Ptr->getOpcode() == ISD::ADD);
10718     Offset = Ptr->getOperand(1);
10719     return true;
10720   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10721     // AddressingMode 2
10722     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10723       int RHSC = (int)RHS->getZExtValue();
10724       if (RHSC < 0 && RHSC > -0x1000) {
10725         assert(Ptr->getOpcode() == ISD::ADD);
10726         isInc = false;
10727         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10728         Base = Ptr->getOperand(0);
10729         return true;
10730       }
10731     }
10732
10733     if (Ptr->getOpcode() == ISD::ADD) {
10734       isInc = true;
10735       ARM_AM::ShiftOpc ShOpcVal=
10736         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10737       if (ShOpcVal != ARM_AM::no_shift) {
10738         Base = Ptr->getOperand(1);
10739         Offset = Ptr->getOperand(0);
10740       } else {
10741         Base = Ptr->getOperand(0);
10742         Offset = Ptr->getOperand(1);
10743       }
10744       return true;
10745     }
10746
10747     isInc = (Ptr->getOpcode() == ISD::ADD);
10748     Base = Ptr->getOperand(0);
10749     Offset = Ptr->getOperand(1);
10750     return true;
10751   }
10752
10753   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10754   return false;
10755 }
10756
10757 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10758                                      bool isSEXTLoad, SDValue &Base,
10759                                      SDValue &Offset, bool &isInc,
10760                                      SelectionDAG &DAG) {
10761   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10762     return false;
10763
10764   Base = Ptr->getOperand(0);
10765   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10766     int RHSC = (int)RHS->getZExtValue();
10767     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10768       assert(Ptr->getOpcode() == ISD::ADD);
10769       isInc = false;
10770       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10771       return true;
10772     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10773       isInc = Ptr->getOpcode() == ISD::ADD;
10774       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10775       return true;
10776     }
10777   }
10778
10779   return false;
10780 }
10781
10782 /// getPreIndexedAddressParts - returns true by value, base pointer and
10783 /// offset pointer and addressing mode by reference if the node's address
10784 /// can be legally represented as pre-indexed load / store address.
10785 bool
10786 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10787                                              SDValue &Offset,
10788                                              ISD::MemIndexedMode &AM,
10789                                              SelectionDAG &DAG) const {
10790   if (Subtarget->isThumb1Only())
10791     return false;
10792
10793   EVT VT;
10794   SDValue Ptr;
10795   bool isSEXTLoad = false;
10796   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10797     Ptr = LD->getBasePtr();
10798     VT  = LD->getMemoryVT();
10799     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10800   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10801     Ptr = ST->getBasePtr();
10802     VT  = ST->getMemoryVT();
10803   } else
10804     return false;
10805
10806   bool isInc;
10807   bool isLegal = false;
10808   if (Subtarget->isThumb2())
10809     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10810                                        Offset, isInc, DAG);
10811   else
10812     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10813                                         Offset, isInc, DAG);
10814   if (!isLegal)
10815     return false;
10816
10817   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10818   return true;
10819 }
10820
10821 /// getPostIndexedAddressParts - returns true by value, base pointer and
10822 /// offset pointer and addressing mode by reference if this node can be
10823 /// combined with a load / store to form a post-indexed load / store.
10824 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10825                                                    SDValue &Base,
10826                                                    SDValue &Offset,
10827                                                    ISD::MemIndexedMode &AM,
10828                                                    SelectionDAG &DAG) const {
10829   if (Subtarget->isThumb1Only())
10830     return false;
10831
10832   EVT VT;
10833   SDValue Ptr;
10834   bool isSEXTLoad = false;
10835   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10836     VT  = LD->getMemoryVT();
10837     Ptr = LD->getBasePtr();
10838     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10839   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10840     VT  = ST->getMemoryVT();
10841     Ptr = ST->getBasePtr();
10842   } else
10843     return false;
10844
10845   bool isInc;
10846   bool isLegal = false;
10847   if (Subtarget->isThumb2())
10848     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10849                                        isInc, DAG);
10850   else
10851     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10852                                         isInc, DAG);
10853   if (!isLegal)
10854     return false;
10855
10856   if (Ptr != Base) {
10857     // Swap base ptr and offset to catch more post-index load / store when
10858     // it's legal. In Thumb2 mode, offset must be an immediate.
10859     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10860         !Subtarget->isThumb2())
10861       std::swap(Base, Offset);
10862
10863     // Post-indexed load / store update the base pointer.
10864     if (Ptr != Base)
10865       return false;
10866   }
10867
10868   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10869   return true;
10870 }
10871
10872 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10873                                                       APInt &KnownZero,
10874                                                       APInt &KnownOne,
10875                                                       const SelectionDAG &DAG,
10876                                                       unsigned Depth) const {
10877   unsigned BitWidth = KnownOne.getBitWidth();
10878   KnownZero = KnownOne = APInt(BitWidth, 0);
10879   switch (Op.getOpcode()) {
10880   default: break;
10881   case ARMISD::ADDC:
10882   case ARMISD::ADDE:
10883   case ARMISD::SUBC:
10884   case ARMISD::SUBE:
10885     // These nodes' second result is a boolean
10886     if (Op.getResNo() == 0)
10887       break;
10888     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10889     break;
10890   case ARMISD::CMOV: {
10891     // Bits are known zero/one if known on the LHS and RHS.
10892     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10893     if (KnownZero == 0 && KnownOne == 0) return;
10894
10895     APInt KnownZeroRHS, KnownOneRHS;
10896     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10897     KnownZero &= KnownZeroRHS;
10898     KnownOne  &= KnownOneRHS;
10899     return;
10900   }
10901   case ISD::INTRINSIC_W_CHAIN: {
10902     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10903     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10904     switch (IntID) {
10905     default: return;
10906     case Intrinsic::arm_ldaex:
10907     case Intrinsic::arm_ldrex: {
10908       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10909       unsigned MemBits = VT.getScalarType().getSizeInBits();
10910       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10911       return;
10912     }
10913     }
10914   }
10915   }
10916 }
10917
10918 //===----------------------------------------------------------------------===//
10919 //                           ARM Inline Assembly Support
10920 //===----------------------------------------------------------------------===//
10921
10922 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10923   // Looking for "rev" which is V6+.
10924   if (!Subtarget->hasV6Ops())
10925     return false;
10926
10927   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10928   std::string AsmStr = IA->getAsmString();
10929   SmallVector<StringRef, 4> AsmPieces;
10930   SplitString(AsmStr, AsmPieces, ";\n");
10931
10932   switch (AsmPieces.size()) {
10933   default: return false;
10934   case 1:
10935     AsmStr = AsmPieces[0];
10936     AsmPieces.clear();
10937     SplitString(AsmStr, AsmPieces, " \t,");
10938
10939     // rev $0, $1
10940     if (AsmPieces.size() == 3 &&
10941         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10942         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10943       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10944       if (Ty && Ty->getBitWidth() == 32)
10945         return IntrinsicLowering::LowerToByteSwap(CI);
10946     }
10947     break;
10948   }
10949
10950   return false;
10951 }
10952
10953 /// getConstraintType - Given a constraint letter, return the type of
10954 /// constraint it is for this target.
10955 ARMTargetLowering::ConstraintType
10956 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10957   if (Constraint.size() == 1) {
10958     switch (Constraint[0]) {
10959     default:  break;
10960     case 'l': return C_RegisterClass;
10961     case 'w': return C_RegisterClass;
10962     case 'h': return C_RegisterClass;
10963     case 'x': return C_RegisterClass;
10964     case 't': return C_RegisterClass;
10965     case 'j': return C_Other; // Constant for movw.
10966       // An address with a single base register. Due to the way we
10967       // currently handle addresses it is the same as an 'r' memory constraint.
10968     case 'Q': return C_Memory;
10969     }
10970   } else if (Constraint.size() == 2) {
10971     switch (Constraint[0]) {
10972     default: break;
10973     // All 'U+' constraints are addresses.
10974     case 'U': return C_Memory;
10975     }
10976   }
10977   return TargetLowering::getConstraintType(Constraint);
10978 }
10979
10980 /// Examine constraint type and operand type and determine a weight value.
10981 /// This object must already have been set up with the operand type
10982 /// and the current alternative constraint selected.
10983 TargetLowering::ConstraintWeight
10984 ARMTargetLowering::getSingleConstraintMatchWeight(
10985     AsmOperandInfo &info, const char *constraint) const {
10986   ConstraintWeight weight = CW_Invalid;
10987   Value *CallOperandVal = info.CallOperandVal;
10988     // If we don't have a value, we can't do a match,
10989     // but allow it at the lowest weight.
10990   if (!CallOperandVal)
10991     return CW_Default;
10992   Type *type = CallOperandVal->getType();
10993   // Look at the constraint type.
10994   switch (*constraint) {
10995   default:
10996     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10997     break;
10998   case 'l':
10999     if (type->isIntegerTy()) {
11000       if (Subtarget->isThumb())
11001         weight = CW_SpecificReg;
11002       else
11003         weight = CW_Register;
11004     }
11005     break;
11006   case 'w':
11007     if (type->isFloatingPointTy())
11008       weight = CW_Register;
11009     break;
11010   }
11011   return weight;
11012 }
11013
11014 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11015 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11016     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11017   if (Constraint.size() == 1) {
11018     // GCC ARM Constraint Letters
11019     switch (Constraint[0]) {
11020     case 'l': // Low regs or general regs.
11021       if (Subtarget->isThumb())
11022         return RCPair(0U, &ARM::tGPRRegClass);
11023       return RCPair(0U, &ARM::GPRRegClass);
11024     case 'h': // High regs or no regs.
11025       if (Subtarget->isThumb())
11026         return RCPair(0U, &ARM::hGPRRegClass);
11027       break;
11028     case 'r':
11029       if (Subtarget->isThumb1Only())
11030         return RCPair(0U, &ARM::tGPRRegClass);
11031       return RCPair(0U, &ARM::GPRRegClass);
11032     case 'w':
11033       if (VT == MVT::Other)
11034         break;
11035       if (VT == MVT::f32)
11036         return RCPair(0U, &ARM::SPRRegClass);
11037       if (VT.getSizeInBits() == 64)
11038         return RCPair(0U, &ARM::DPRRegClass);
11039       if (VT.getSizeInBits() == 128)
11040         return RCPair(0U, &ARM::QPRRegClass);
11041       break;
11042     case 'x':
11043       if (VT == MVT::Other)
11044         break;
11045       if (VT == MVT::f32)
11046         return RCPair(0U, &ARM::SPR_8RegClass);
11047       if (VT.getSizeInBits() == 64)
11048         return RCPair(0U, &ARM::DPR_8RegClass);
11049       if (VT.getSizeInBits() == 128)
11050         return RCPair(0U, &ARM::QPR_8RegClass);
11051       break;
11052     case 't':
11053       if (VT == MVT::f32)
11054         return RCPair(0U, &ARM::SPRRegClass);
11055       break;
11056     }
11057   }
11058   if (StringRef("{cc}").equals_lower(Constraint))
11059     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11060
11061   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11062 }
11063
11064 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11065 /// vector.  If it is invalid, don't add anything to Ops.
11066 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11067                                                      std::string &Constraint,
11068                                                      std::vector<SDValue>&Ops,
11069                                                      SelectionDAG &DAG) const {
11070   SDValue Result;
11071
11072   // Currently only support length 1 constraints.
11073   if (Constraint.length() != 1) return;
11074
11075   char ConstraintLetter = Constraint[0];
11076   switch (ConstraintLetter) {
11077   default: break;
11078   case 'j':
11079   case 'I': case 'J': case 'K': case 'L':
11080   case 'M': case 'N': case 'O':
11081     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11082     if (!C)
11083       return;
11084
11085     int64_t CVal64 = C->getSExtValue();
11086     int CVal = (int) CVal64;
11087     // None of these constraints allow values larger than 32 bits.  Check
11088     // that the value fits in an int.
11089     if (CVal != CVal64)
11090       return;
11091
11092     switch (ConstraintLetter) {
11093       case 'j':
11094         // Constant suitable for movw, must be between 0 and
11095         // 65535.
11096         if (Subtarget->hasV6T2Ops())
11097           if (CVal >= 0 && CVal <= 65535)
11098             break;
11099         return;
11100       case 'I':
11101         if (Subtarget->isThumb1Only()) {
11102           // This must be a constant between 0 and 255, for ADD
11103           // immediates.
11104           if (CVal >= 0 && CVal <= 255)
11105             break;
11106         } else if (Subtarget->isThumb2()) {
11107           // A constant that can be used as an immediate value in a
11108           // data-processing instruction.
11109           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11110             break;
11111         } else {
11112           // A constant that can be used as an immediate value in a
11113           // data-processing instruction.
11114           if (ARM_AM::getSOImmVal(CVal) != -1)
11115             break;
11116         }
11117         return;
11118
11119       case 'J':
11120         if (Subtarget->isThumb()) {  // FIXME thumb2
11121           // This must be a constant between -255 and -1, for negated ADD
11122           // immediates. This can be used in GCC with an "n" modifier that
11123           // prints the negated value, for use with SUB instructions. It is
11124           // not useful otherwise but is implemented for compatibility.
11125           if (CVal >= -255 && CVal <= -1)
11126             break;
11127         } else {
11128           // This must be a constant between -4095 and 4095. It is not clear
11129           // what this constraint is intended for. Implemented for
11130           // compatibility with GCC.
11131           if (CVal >= -4095 && CVal <= 4095)
11132             break;
11133         }
11134         return;
11135
11136       case 'K':
11137         if (Subtarget->isThumb1Only()) {
11138           // A 32-bit value where only one byte has a nonzero value. Exclude
11139           // zero to match GCC. This constraint is used by GCC internally for
11140           // constants that can be loaded with a move/shift combination.
11141           // It is not useful otherwise but is implemented for compatibility.
11142           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11143             break;
11144         } else if (Subtarget->isThumb2()) {
11145           // A constant whose bitwise inverse can be used as an immediate
11146           // value in a data-processing instruction. This can be used in GCC
11147           // with a "B" modifier that prints the inverted value, for use with
11148           // BIC and MVN instructions. It is not useful otherwise but is
11149           // implemented for compatibility.
11150           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11151             break;
11152         } else {
11153           // A constant whose bitwise inverse can be used as an immediate
11154           // value in a data-processing instruction. This can be used in GCC
11155           // with a "B" modifier that prints the inverted value, for use with
11156           // BIC and MVN instructions. It is not useful otherwise but is
11157           // implemented for compatibility.
11158           if (ARM_AM::getSOImmVal(~CVal) != -1)
11159             break;
11160         }
11161         return;
11162
11163       case 'L':
11164         if (Subtarget->isThumb1Only()) {
11165           // This must be a constant between -7 and 7,
11166           // for 3-operand ADD/SUB immediate instructions.
11167           if (CVal >= -7 && CVal < 7)
11168             break;
11169         } else if (Subtarget->isThumb2()) {
11170           // A constant whose negation can be used as an immediate value in a
11171           // data-processing instruction. This can be used in GCC with an "n"
11172           // modifier that prints the negated value, for use with SUB
11173           // instructions. It is not useful otherwise but is implemented for
11174           // compatibility.
11175           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11176             break;
11177         } else {
11178           // A constant whose negation can be used as an immediate value in a
11179           // data-processing instruction. This can be used in GCC with an "n"
11180           // modifier that prints the negated value, for use with SUB
11181           // instructions. It is not useful otherwise but is implemented for
11182           // compatibility.
11183           if (ARM_AM::getSOImmVal(-CVal) != -1)
11184             break;
11185         }
11186         return;
11187
11188       case 'M':
11189         if (Subtarget->isThumb()) { // FIXME thumb2
11190           // This must be a multiple of 4 between 0 and 1020, for
11191           // ADD sp + immediate.
11192           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11193             break;
11194         } else {
11195           // A power of two or a constant between 0 and 32.  This is used in
11196           // GCC for the shift amount on shifted register operands, but it is
11197           // useful in general for any shift amounts.
11198           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11199             break;
11200         }
11201         return;
11202
11203       case 'N':
11204         if (Subtarget->isThumb()) {  // FIXME thumb2
11205           // This must be a constant between 0 and 31, for shift amounts.
11206           if (CVal >= 0 && CVal <= 31)
11207             break;
11208         }
11209         return;
11210
11211       case 'O':
11212         if (Subtarget->isThumb()) {  // FIXME thumb2
11213           // This must be a multiple of 4 between -508 and 508, for
11214           // ADD/SUB sp = sp + immediate.
11215           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11216             break;
11217         }
11218         return;
11219     }
11220     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11221     break;
11222   }
11223
11224   if (Result.getNode()) {
11225     Ops.push_back(Result);
11226     return;
11227   }
11228   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11229 }
11230
11231 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11232   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11233          "Register-based DivRem lowering only");
11234   unsigned Opcode = Op->getOpcode();
11235   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11236          "Invalid opcode for Div/Rem lowering");
11237   bool isSigned = (Opcode == ISD::SDIVREM);
11238   EVT VT = Op->getValueType(0);
11239   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11240
11241   RTLIB::Libcall LC;
11242   switch (VT.getSimpleVT().SimpleTy) {
11243   default: llvm_unreachable("Unexpected request for libcall!");
11244   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11245   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11246   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11247   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11248   }
11249
11250   SDValue InChain = DAG.getEntryNode();
11251
11252   TargetLowering::ArgListTy Args;
11253   TargetLowering::ArgListEntry Entry;
11254   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11255     EVT ArgVT = Op->getOperand(i).getValueType();
11256     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11257     Entry.Node = Op->getOperand(i);
11258     Entry.Ty = ArgTy;
11259     Entry.isSExt = isSigned;
11260     Entry.isZExt = !isSigned;
11261     Args.push_back(Entry);
11262   }
11263
11264   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11265                                          getPointerTy(DAG.getDataLayout()));
11266
11267   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11268
11269   SDLoc dl(Op);
11270   TargetLowering::CallLoweringInfo CLI(DAG);
11271   CLI.setDebugLoc(dl).setChain(InChain)
11272     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11273     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11274
11275   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11276   return CallInfo.first;
11277 }
11278
11279 SDValue
11280 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11281   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11282   SDLoc DL(Op);
11283
11284   // Get the inputs.
11285   SDValue Chain = Op.getOperand(0);
11286   SDValue Size  = Op.getOperand(1);
11287
11288   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11289                               DAG.getConstant(2, DL, MVT::i32));
11290
11291   SDValue Flag;
11292   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11293   Flag = Chain.getValue(1);
11294
11295   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11296   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11297
11298   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11299   Chain = NewSP.getValue(1);
11300
11301   SDValue Ops[2] = { NewSP, Chain };
11302   return DAG.getMergeValues(Ops, DL);
11303 }
11304
11305 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11306   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11307          "Unexpected type for custom-lowering FP_EXTEND");
11308
11309   RTLIB::Libcall LC;
11310   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11311
11312   SDValue SrcVal = Op.getOperand(0);
11313   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11314                      /*isSigned*/ false, SDLoc(Op)).first;
11315 }
11316
11317 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11318   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11319          Subtarget->isFPOnlySP() &&
11320          "Unexpected type for custom-lowering FP_ROUND");
11321
11322   RTLIB::Libcall LC;
11323   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11324
11325   SDValue SrcVal = Op.getOperand(0);
11326   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11327                      /*isSigned*/ false, SDLoc(Op)).first;
11328 }
11329
11330 bool
11331 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11332   // The ARM target isn't yet aware of offsets.
11333   return false;
11334 }
11335
11336 bool ARM::isBitFieldInvertedMask(unsigned v) {
11337   if (v == 0xffffffff)
11338     return false;
11339
11340   // there can be 1's on either or both "outsides", all the "inside"
11341   // bits must be 0's
11342   return isShiftedMask_32(~v);
11343 }
11344
11345 /// isFPImmLegal - Returns true if the target can instruction select the
11346 /// specified FP immediate natively. If false, the legalizer will
11347 /// materialize the FP immediate as a load from a constant pool.
11348 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11349   if (!Subtarget->hasVFP3())
11350     return false;
11351   if (VT == MVT::f32)
11352     return ARM_AM::getFP32Imm(Imm) != -1;
11353   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11354     return ARM_AM::getFP64Imm(Imm) != -1;
11355   return false;
11356 }
11357
11358 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11359 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11360 /// specified in the intrinsic calls.
11361 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11362                                            const CallInst &I,
11363                                            unsigned Intrinsic) const {
11364   switch (Intrinsic) {
11365   case Intrinsic::arm_neon_vld1:
11366   case Intrinsic::arm_neon_vld2:
11367   case Intrinsic::arm_neon_vld3:
11368   case Intrinsic::arm_neon_vld4:
11369   case Intrinsic::arm_neon_vld2lane:
11370   case Intrinsic::arm_neon_vld3lane:
11371   case Intrinsic::arm_neon_vld4lane: {
11372     Info.opc = ISD::INTRINSIC_W_CHAIN;
11373     // Conservatively set memVT to the entire set of vectors loaded.
11374     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11375     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11376     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11377     Info.ptrVal = I.getArgOperand(0);
11378     Info.offset = 0;
11379     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11380     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11381     Info.vol = false; // volatile loads with NEON intrinsics not supported
11382     Info.readMem = true;
11383     Info.writeMem = false;
11384     return true;
11385   }
11386   case Intrinsic::arm_neon_vst1:
11387   case Intrinsic::arm_neon_vst2:
11388   case Intrinsic::arm_neon_vst3:
11389   case Intrinsic::arm_neon_vst4:
11390   case Intrinsic::arm_neon_vst2lane:
11391   case Intrinsic::arm_neon_vst3lane:
11392   case Intrinsic::arm_neon_vst4lane: {
11393     Info.opc = ISD::INTRINSIC_VOID;
11394     // Conservatively set memVT to the entire set of vectors stored.
11395     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11396     unsigned NumElts = 0;
11397     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11398       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11399       if (!ArgTy->isVectorTy())
11400         break;
11401       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11402     }
11403     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11404     Info.ptrVal = I.getArgOperand(0);
11405     Info.offset = 0;
11406     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11407     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11408     Info.vol = false; // volatile stores with NEON intrinsics not supported
11409     Info.readMem = false;
11410     Info.writeMem = true;
11411     return true;
11412   }
11413   case Intrinsic::arm_ldaex:
11414   case Intrinsic::arm_ldrex: {
11415     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11416     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11417     Info.opc = ISD::INTRINSIC_W_CHAIN;
11418     Info.memVT = MVT::getVT(PtrTy->getElementType());
11419     Info.ptrVal = I.getArgOperand(0);
11420     Info.offset = 0;
11421     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11422     Info.vol = true;
11423     Info.readMem = true;
11424     Info.writeMem = false;
11425     return true;
11426   }
11427   case Intrinsic::arm_stlex:
11428   case Intrinsic::arm_strex: {
11429     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11430     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11431     Info.opc = ISD::INTRINSIC_W_CHAIN;
11432     Info.memVT = MVT::getVT(PtrTy->getElementType());
11433     Info.ptrVal = I.getArgOperand(1);
11434     Info.offset = 0;
11435     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11436     Info.vol = true;
11437     Info.readMem = false;
11438     Info.writeMem = true;
11439     return true;
11440   }
11441   case Intrinsic::arm_stlexd:
11442   case Intrinsic::arm_strexd: {
11443     Info.opc = ISD::INTRINSIC_W_CHAIN;
11444     Info.memVT = MVT::i64;
11445     Info.ptrVal = I.getArgOperand(2);
11446     Info.offset = 0;
11447     Info.align = 8;
11448     Info.vol = true;
11449     Info.readMem = false;
11450     Info.writeMem = true;
11451     return true;
11452   }
11453   case Intrinsic::arm_ldaexd:
11454   case Intrinsic::arm_ldrexd: {
11455     Info.opc = ISD::INTRINSIC_W_CHAIN;
11456     Info.memVT = MVT::i64;
11457     Info.ptrVal = I.getArgOperand(0);
11458     Info.offset = 0;
11459     Info.align = 8;
11460     Info.vol = true;
11461     Info.readMem = true;
11462     Info.writeMem = false;
11463     return true;
11464   }
11465   default:
11466     break;
11467   }
11468
11469   return false;
11470 }
11471
11472 /// \brief Returns true if it is beneficial to convert a load of a constant
11473 /// to just the constant itself.
11474 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11475                                                           Type *Ty) const {
11476   assert(Ty->isIntegerTy());
11477
11478   unsigned Bits = Ty->getPrimitiveSizeInBits();
11479   if (Bits == 0 || Bits > 32)
11480     return false;
11481   return true;
11482 }
11483
11484 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11485
11486 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11487                                         ARM_MB::MemBOpt Domain) const {
11488   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11489
11490   // First, if the target has no DMB, see what fallback we can use.
11491   if (!Subtarget->hasDataBarrier()) {
11492     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11493     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11494     // here.
11495     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11496       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11497       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11498                         Builder.getInt32(0), Builder.getInt32(7),
11499                         Builder.getInt32(10), Builder.getInt32(5)};
11500       return Builder.CreateCall(MCR, args);
11501     } else {
11502       // Instead of using barriers, atomic accesses on these subtargets use
11503       // libcalls.
11504       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11505     }
11506   } else {
11507     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11508     // Only a full system barrier exists in the M-class architectures.
11509     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11510     Constant *CDomain = Builder.getInt32(Domain);
11511     return Builder.CreateCall(DMB, CDomain);
11512   }
11513 }
11514
11515 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11516 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11517                                          AtomicOrdering Ord, bool IsStore,
11518                                          bool IsLoad) const {
11519   if (!getInsertFencesForAtomic())
11520     return nullptr;
11521
11522   switch (Ord) {
11523   case NotAtomic:
11524   case Unordered:
11525     llvm_unreachable("Invalid fence: unordered/non-atomic");
11526   case Monotonic:
11527   case Acquire:
11528     return nullptr; // Nothing to do
11529   case SequentiallyConsistent:
11530     if (!IsStore)
11531       return nullptr; // Nothing to do
11532     /*FALLTHROUGH*/
11533   case Release:
11534   case AcquireRelease:
11535     if (Subtarget->isSwift())
11536       return makeDMB(Builder, ARM_MB::ISHST);
11537     // FIXME: add a comment with a link to documentation justifying this.
11538     else
11539       return makeDMB(Builder, ARM_MB::ISH);
11540   }
11541   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11542 }
11543
11544 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11545                                           AtomicOrdering Ord, bool IsStore,
11546                                           bool IsLoad) const {
11547   if (!getInsertFencesForAtomic())
11548     return nullptr;
11549
11550   switch (Ord) {
11551   case NotAtomic:
11552   case Unordered:
11553     llvm_unreachable("Invalid fence: unordered/not-atomic");
11554   case Monotonic:
11555   case Release:
11556     return nullptr; // Nothing to do
11557   case Acquire:
11558   case AcquireRelease:
11559   case SequentiallyConsistent:
11560     return makeDMB(Builder, ARM_MB::ISH);
11561   }
11562   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11563 }
11564
11565 // Loads and stores less than 64-bits are already atomic; ones above that
11566 // are doomed anyway, so defer to the default libcall and blame the OS when
11567 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11568 // anything for those.
11569 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11570   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11571   return (Size == 64) && !Subtarget->isMClass();
11572 }
11573
11574 // Loads and stores less than 64-bits are already atomic; ones above that
11575 // are doomed anyway, so defer to the default libcall and blame the OS when
11576 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11577 // anything for those.
11578 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11579 // guarantee, see DDI0406C ARM architecture reference manual,
11580 // sections A8.8.72-74 LDRD)
11581 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11582   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11583   return (Size == 64) && !Subtarget->isMClass();
11584 }
11585
11586 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11587 // and up to 64 bits on the non-M profiles
11588 TargetLoweringBase::AtomicRMWExpansionKind
11589 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11590   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11591   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11592              ? AtomicRMWExpansionKind::LLSC
11593              : AtomicRMWExpansionKind::None;
11594 }
11595
11596 // This has so far only been implemented for MachO.
11597 bool ARMTargetLowering::useLoadStackGuardNode() const {
11598   return Subtarget->isTargetMachO();
11599 }
11600
11601 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11602                                                   unsigned &Cost) const {
11603   // If we do not have NEON, vector types are not natively supported.
11604   if (!Subtarget->hasNEON())
11605     return false;
11606
11607   // Floating point values and vector values map to the same register file.
11608   // Therefore, although we could do a store extract of a vector type, this is
11609   // better to leave at float as we have more freedom in the addressing mode for
11610   // those.
11611   if (VectorTy->isFPOrFPVectorTy())
11612     return false;
11613
11614   // If the index is unknown at compile time, this is very expensive to lower
11615   // and it is not possible to combine the store with the extract.
11616   if (!isa<ConstantInt>(Idx))
11617     return false;
11618
11619   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11620   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11621   // We can do a store + vector extract on any vector that fits perfectly in a D
11622   // or Q register.
11623   if (BitWidth == 64 || BitWidth == 128) {
11624     Cost = 0;
11625     return true;
11626   }
11627   return false;
11628 }
11629
11630 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11631                                          AtomicOrdering Ord) const {
11632   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11633   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11634   bool IsAcquire = isAtLeastAcquire(Ord);
11635
11636   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11637   // intrinsic must return {i32, i32} and we have to recombine them into a
11638   // single i64 here.
11639   if (ValTy->getPrimitiveSizeInBits() == 64) {
11640     Intrinsic::ID Int =
11641         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11642     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11643
11644     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11645     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11646
11647     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11648     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11649     if (!Subtarget->isLittle())
11650       std::swap (Lo, Hi);
11651     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11652     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11653     return Builder.CreateOr(
11654         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11655   }
11656
11657   Type *Tys[] = { Addr->getType() };
11658   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11659   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11660
11661   return Builder.CreateTruncOrBitCast(
11662       Builder.CreateCall(Ldrex, Addr),
11663       cast<PointerType>(Addr->getType())->getElementType());
11664 }
11665
11666 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11667                                                Value *Addr,
11668                                                AtomicOrdering Ord) const {
11669   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11670   bool IsRelease = isAtLeastRelease(Ord);
11671
11672   // Since the intrinsics must have legal type, the i64 intrinsics take two
11673   // parameters: "i32, i32". We must marshal Val into the appropriate form
11674   // before the call.
11675   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11676     Intrinsic::ID Int =
11677         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11678     Function *Strex = Intrinsic::getDeclaration(M, Int);
11679     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11680
11681     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11682     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11683     if (!Subtarget->isLittle())
11684       std::swap (Lo, Hi);
11685     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11686     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11687   }
11688
11689   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11690   Type *Tys[] = { Addr->getType() };
11691   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11692
11693   return Builder.CreateCall(
11694       Strex, {Builder.CreateZExtOrBitCast(
11695                   Val, Strex->getFunctionType()->getParamType(0)),
11696               Addr});
11697 }
11698
11699 /// \brief Lower an interleaved load into a vldN intrinsic.
11700 ///
11701 /// E.g. Lower an interleaved load (Factor = 2):
11702 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11703 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11704 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11705 ///
11706 ///      Into:
11707 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11708 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11709 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11710 bool ARMTargetLowering::lowerInterleavedLoad(
11711     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11712     ArrayRef<unsigned> Indices, unsigned Factor) const {
11713   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11714          "Invalid interleave factor");
11715   assert(!Shuffles.empty() && "Empty shufflevector input");
11716   assert(Shuffles.size() == Indices.size() &&
11717          "Unmatched number of shufflevectors and indices");
11718
11719   VectorType *VecTy = Shuffles[0]->getType();
11720   Type *EltTy = VecTy->getVectorElementType();
11721
11722   const DataLayout &DL = LI->getModule()->getDataLayout();
11723   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11724   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11725
11726   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11727   // support i64/f64 element).
11728   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11729     return false;
11730
11731   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11732   // load integer vectors first and then convert to pointer vectors.
11733   if (EltTy->isPointerTy())
11734     VecTy =
11735         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11736
11737   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11738                                             Intrinsic::arm_neon_vld3,
11739                                             Intrinsic::arm_neon_vld4};
11740
11741   Function *VldnFunc =
11742       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11743
11744   IRBuilder<> Builder(LI);
11745   SmallVector<Value *, 2> Ops;
11746
11747   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11748   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11749   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11750
11751   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11752
11753   // Replace uses of each shufflevector with the corresponding vector loaded
11754   // by ldN.
11755   for (unsigned i = 0; i < Shuffles.size(); i++) {
11756     ShuffleVectorInst *SV = Shuffles[i];
11757     unsigned Index = Indices[i];
11758
11759     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11760
11761     // Convert the integer vector to pointer vector if the element is pointer.
11762     if (EltTy->isPointerTy())
11763       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11764
11765     SV->replaceAllUsesWith(SubVec);
11766   }
11767
11768   return true;
11769 }
11770
11771 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11772 ///
11773 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11774 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11775                                    unsigned NumElts) {
11776   SmallVector<Constant *, 16> Mask;
11777   for (unsigned i = 0; i < NumElts; i++)
11778     Mask.push_back(Builder.getInt32(Start + i));
11779
11780   return ConstantVector::get(Mask);
11781 }
11782
11783 /// \brief Lower an interleaved store into a vstN intrinsic.
11784 ///
11785 /// E.g. Lower an interleaved store (Factor = 3):
11786 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11787 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11788 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11789 ///
11790 ///      Into:
11791 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11792 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11793 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11794 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11795 ///
11796 /// Note that the new shufflevectors will be removed and we'll only generate one
11797 /// vst3 instruction in CodeGen.
11798 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11799                                               ShuffleVectorInst *SVI,
11800                                               unsigned Factor) const {
11801   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11802          "Invalid interleave factor");
11803
11804   VectorType *VecTy = SVI->getType();
11805   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11806          "Invalid interleaved store");
11807
11808   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11809   Type *EltTy = VecTy->getVectorElementType();
11810   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11811
11812   const DataLayout &DL = SI->getModule()->getDataLayout();
11813   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11814   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11815
11816   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11817   // doesn't support i64/f64 element).
11818   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11819     return false;
11820
11821   Value *Op0 = SVI->getOperand(0);
11822   Value *Op1 = SVI->getOperand(1);
11823   IRBuilder<> Builder(SI);
11824
11825   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11826   // vectors to integer vectors.
11827   if (EltTy->isPointerTy()) {
11828     Type *IntTy = DL.getIntPtrType(EltTy);
11829
11830     // Convert to the corresponding integer vector.
11831     Type *IntVecTy =
11832         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11833     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11834     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11835
11836     SubVecTy = VectorType::get(IntTy, NumSubElts);
11837   }
11838
11839   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11840                                        Intrinsic::arm_neon_vst3,
11841                                        Intrinsic::arm_neon_vst4};
11842   Function *VstNFunc = Intrinsic::getDeclaration(
11843       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11844
11845   SmallVector<Value *, 6> Ops;
11846
11847   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11848   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11849
11850   // Split the shufflevector operands into sub vectors for the new vstN call.
11851   for (unsigned i = 0; i < Factor; i++)
11852     Ops.push_back(Builder.CreateShuffleVector(
11853         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11854
11855   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11856   Builder.CreateCall(VstNFunc, Ops);
11857   return true;
11858 }
11859
11860 enum HABaseType {
11861   HA_UNKNOWN = 0,
11862   HA_FLOAT,
11863   HA_DOUBLE,
11864   HA_VECT64,
11865   HA_VECT128
11866 };
11867
11868 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11869                                    uint64_t &Members) {
11870   if (auto *ST = dyn_cast<StructType>(Ty)) {
11871     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11872       uint64_t SubMembers = 0;
11873       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11874         return false;
11875       Members += SubMembers;
11876     }
11877   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11878     uint64_t SubMembers = 0;
11879     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11880       return false;
11881     Members += SubMembers * AT->getNumElements();
11882   } else if (Ty->isFloatTy()) {
11883     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11884       return false;
11885     Members = 1;
11886     Base = HA_FLOAT;
11887   } else if (Ty->isDoubleTy()) {
11888     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11889       return false;
11890     Members = 1;
11891     Base = HA_DOUBLE;
11892   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11893     Members = 1;
11894     switch (Base) {
11895     case HA_FLOAT:
11896     case HA_DOUBLE:
11897       return false;
11898     case HA_VECT64:
11899       return VT->getBitWidth() == 64;
11900     case HA_VECT128:
11901       return VT->getBitWidth() == 128;
11902     case HA_UNKNOWN:
11903       switch (VT->getBitWidth()) {
11904       case 64:
11905         Base = HA_VECT64;
11906         return true;
11907       case 128:
11908         Base = HA_VECT128;
11909         return true;
11910       default:
11911         return false;
11912       }
11913     }
11914   }
11915
11916   return (Members > 0 && Members <= 4);
11917 }
11918
11919 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11920 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11921 /// passing according to AAPCS rules.
11922 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11923     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11924   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11925       CallingConv::ARM_AAPCS_VFP)
11926     return false;
11927
11928   HABaseType Base = HA_UNKNOWN;
11929   uint64_t Members = 0;
11930   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11931   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11932
11933   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11934   return IsHA || IsIntArray;
11935 }