[ARM] Replace ARMISD::FMIN/FMAX with the shiny new ISD::FMINNAN/FMAXNAN.
[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     if (!Subtarget->isFPOnlySP()) {
936       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
937       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
938       setOperationAction(ISD::FROUND, MVT::f64, Legal);
939       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
940       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
941       setOperationAction(ISD::FRINT, MVT::f64, Legal);
942     }
943   }
944
945   if (Subtarget->hasVFP3()) {
946     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
947     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
948     setOperationAction(ISD::FMINNAN, MVT::f64, Legal);
949     setOperationAction(ISD::FMAXNAN, MVT::f64, Legal);
950   }
951
952   // We have target-specific dag combine patterns for the following nodes:
953   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
954   setTargetDAGCombine(ISD::ADD);
955   setTargetDAGCombine(ISD::SUB);
956   setTargetDAGCombine(ISD::MUL);
957   setTargetDAGCombine(ISD::AND);
958   setTargetDAGCombine(ISD::OR);
959   setTargetDAGCombine(ISD::XOR);
960
961   if (Subtarget->hasV6Ops())
962     setTargetDAGCombine(ISD::SRL);
963
964   setStackPointerRegisterToSaveRestore(ARM::SP);
965
966   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
967       !Subtarget->hasVFP2())
968     setSchedulingPreference(Sched::RegPressure);
969   else
970     setSchedulingPreference(Sched::Hybrid);
971
972   //// temporary - rewrite interface to use type
973   MaxStoresPerMemset = 8;
974   MaxStoresPerMemsetOptSize = 4;
975   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
976   MaxStoresPerMemcpyOptSize = 2;
977   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
978   MaxStoresPerMemmoveOptSize = 2;
979
980   // On ARM arguments smaller than 4 bytes are extended, so all arguments
981   // are at least 4 bytes aligned.
982   setMinStackArgumentAlignment(4);
983
984   // Prefer likely predicted branches to selects on out-of-order cores.
985   PredictableSelectIsExpensive = Subtarget->isLikeA9();
986
987   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
988 }
989
990 bool ARMTargetLowering::useSoftFloat() const {
991   return Subtarget->useSoftFloat();
992 }
993
994 // FIXME: It might make sense to define the representative register class as the
995 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
996 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
997 // SPR's representative would be DPR_VFP2. This should work well if register
998 // pressure tracking were modified such that a register use would increment the
999 // pressure of the register class's representative and all of it's super
1000 // classes' representatives transitively. We have not implemented this because
1001 // of the difficulty prior to coalescing of modeling operand register classes
1002 // due to the common occurrence of cross class copies and subregister insertions
1003 // and extractions.
1004 std::pair<const TargetRegisterClass *, uint8_t>
1005 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1006                                            MVT VT) const {
1007   const TargetRegisterClass *RRC = nullptr;
1008   uint8_t Cost = 1;
1009   switch (VT.SimpleTy) {
1010   default:
1011     return TargetLowering::findRepresentativeClass(TRI, VT);
1012   // Use DPR as representative register class for all floating point
1013   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1014   // the cost is 1 for both f32 and f64.
1015   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1016   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1017     RRC = &ARM::DPRRegClass;
1018     // When NEON is used for SP, only half of the register file is available
1019     // because operations that define both SP and DP results will be constrained
1020     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1021     // coalescing by double-counting the SP regs. See the FIXME above.
1022     if (Subtarget->useNEONForSinglePrecisionFP())
1023       Cost = 2;
1024     break;
1025   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1026   case MVT::v4f32: case MVT::v2f64:
1027     RRC = &ARM::DPRRegClass;
1028     Cost = 2;
1029     break;
1030   case MVT::v4i64:
1031     RRC = &ARM::DPRRegClass;
1032     Cost = 4;
1033     break;
1034   case MVT::v8i64:
1035     RRC = &ARM::DPRRegClass;
1036     Cost = 8;
1037     break;
1038   }
1039   return std::make_pair(RRC, Cost);
1040 }
1041
1042 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1043   switch ((ARMISD::NodeType)Opcode) {
1044   case ARMISD::FIRST_NUMBER:  break;
1045   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1046   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1047   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1048   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1049   case ARMISD::CALL:          return "ARMISD::CALL";
1050   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1051   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1052   case ARMISD::tCALL:         return "ARMISD::tCALL";
1053   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1054   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1055   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1056   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1057   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1058   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1059   case ARMISD::CMP:           return "ARMISD::CMP";
1060   case ARMISD::CMN:           return "ARMISD::CMN";
1061   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1062   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1063   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1064   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1065   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1066
1067   case ARMISD::CMOV:          return "ARMISD::CMOV";
1068
1069   case ARMISD::RBIT:          return "ARMISD::RBIT";
1070
1071   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1072   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1073   case ARMISD::RRX:           return "ARMISD::RRX";
1074
1075   case ARMISD::ADDC:          return "ARMISD::ADDC";
1076   case ARMISD::ADDE:          return "ARMISD::ADDE";
1077   case ARMISD::SUBC:          return "ARMISD::SUBC";
1078   case ARMISD::SUBE:          return "ARMISD::SUBE";
1079
1080   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1081   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1082
1083   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1084   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1085   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1086
1087   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1088
1089   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1090
1091   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1092
1093   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1094
1095   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1096
1097   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1098
1099   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1100   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1101   case ARMISD::VCGE:          return "ARMISD::VCGE";
1102   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1103   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1104   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1105   case ARMISD::VCGT:          return "ARMISD::VCGT";
1106   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1107   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1108   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1109   case ARMISD::VTST:          return "ARMISD::VTST";
1110
1111   case ARMISD::VSHL:          return "ARMISD::VSHL";
1112   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1113   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1114   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1115   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1116   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1117   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1118   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1119   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1120   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1121   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1122   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1123   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1124   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1125   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1126   case ARMISD::VSLI:          return "ARMISD::VSLI";
1127   case ARMISD::VSRI:          return "ARMISD::VSRI";
1128   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1129   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1130   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1131   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1132   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1133   case ARMISD::VDUP:          return "ARMISD::VDUP";
1134   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1135   case ARMISD::VEXT:          return "ARMISD::VEXT";
1136   case ARMISD::VREV64:        return "ARMISD::VREV64";
1137   case ARMISD::VREV32:        return "ARMISD::VREV32";
1138   case ARMISD::VREV16:        return "ARMISD::VREV16";
1139   case ARMISD::VZIP:          return "ARMISD::VZIP";
1140   case ARMISD::VUZP:          return "ARMISD::VUZP";
1141   case ARMISD::VTRN:          return "ARMISD::VTRN";
1142   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1143   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1144   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1145   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1146   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1147   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1148   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1149   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1150   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1151   case ARMISD::BFI:           return "ARMISD::BFI";
1152   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1153   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1154   case ARMISD::VBSL:          return "ARMISD::VBSL";
1155   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1156   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1157   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1158   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1159   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1160   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1161   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1162   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1163   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1164   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1165   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1166   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1167   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1168   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1169   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1170   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1171   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1172   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1173   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1174   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1175   }
1176   return nullptr;
1177 }
1178
1179 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1180                                           EVT VT) const {
1181   if (!VT.isVector())
1182     return getPointerTy(DL);
1183   return VT.changeVectorElementTypeToInteger();
1184 }
1185
1186 /// getRegClassFor - Return the register class that should be used for the
1187 /// specified value type.
1188 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1189   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1190   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1191   // load / store 4 to 8 consecutive D registers.
1192   if (Subtarget->hasNEON()) {
1193     if (VT == MVT::v4i64)
1194       return &ARM::QQPRRegClass;
1195     if (VT == MVT::v8i64)
1196       return &ARM::QQQQPRRegClass;
1197   }
1198   return TargetLowering::getRegClassFor(VT);
1199 }
1200
1201 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1202 // source/dest is aligned and the copy size is large enough. We therefore want
1203 // to align such objects passed to memory intrinsics.
1204 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1205                                                unsigned &PrefAlign) const {
1206   if (!isa<MemIntrinsic>(CI))
1207     return false;
1208   MinSize = 8;
1209   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1210   // cycle faster than 4-byte aligned LDM.
1211   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1212   return true;
1213 }
1214
1215 // Create a fast isel object.
1216 FastISel *
1217 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1218                                   const TargetLibraryInfo *libInfo) const {
1219   return ARM::createFastISel(funcInfo, libInfo);
1220 }
1221
1222 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1223   unsigned NumVals = N->getNumValues();
1224   if (!NumVals)
1225     return Sched::RegPressure;
1226
1227   for (unsigned i = 0; i != NumVals; ++i) {
1228     EVT VT = N->getValueType(i);
1229     if (VT == MVT::Glue || VT == MVT::Other)
1230       continue;
1231     if (VT.isFloatingPoint() || VT.isVector())
1232       return Sched::ILP;
1233   }
1234
1235   if (!N->isMachineOpcode())
1236     return Sched::RegPressure;
1237
1238   // Load are scheduled for latency even if there instruction itinerary
1239   // is not available.
1240   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1241   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1242
1243   if (MCID.getNumDefs() == 0)
1244     return Sched::RegPressure;
1245   if (!Itins->isEmpty() &&
1246       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1247     return Sched::ILP;
1248
1249   return Sched::RegPressure;
1250 }
1251
1252 //===----------------------------------------------------------------------===//
1253 // Lowering Code
1254 //===----------------------------------------------------------------------===//
1255
1256 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1257 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1258   switch (CC) {
1259   default: llvm_unreachable("Unknown condition code!");
1260   case ISD::SETNE:  return ARMCC::NE;
1261   case ISD::SETEQ:  return ARMCC::EQ;
1262   case ISD::SETGT:  return ARMCC::GT;
1263   case ISD::SETGE:  return ARMCC::GE;
1264   case ISD::SETLT:  return ARMCC::LT;
1265   case ISD::SETLE:  return ARMCC::LE;
1266   case ISD::SETUGT: return ARMCC::HI;
1267   case ISD::SETUGE: return ARMCC::HS;
1268   case ISD::SETULT: return ARMCC::LO;
1269   case ISD::SETULE: return ARMCC::LS;
1270   }
1271 }
1272
1273 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1274 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1275                         ARMCC::CondCodes &CondCode2) {
1276   CondCode2 = ARMCC::AL;
1277   switch (CC) {
1278   default: llvm_unreachable("Unknown FP condition!");
1279   case ISD::SETEQ:
1280   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1281   case ISD::SETGT:
1282   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1283   case ISD::SETGE:
1284   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1285   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1286   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1287   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1288   case ISD::SETO:   CondCode = ARMCC::VC; break;
1289   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1290   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1291   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1292   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1293   case ISD::SETLT:
1294   case ISD::SETULT: CondCode = ARMCC::LT; break;
1295   case ISD::SETLE:
1296   case ISD::SETULE: CondCode = ARMCC::LE; break;
1297   case ISD::SETNE:
1298   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1299   }
1300 }
1301
1302 //===----------------------------------------------------------------------===//
1303 //                      Calling Convention Implementation
1304 //===----------------------------------------------------------------------===//
1305
1306 #include "ARMGenCallingConv.inc"
1307
1308 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1309 /// account presence of floating point hardware and calling convention
1310 /// limitations, such as support for variadic functions.
1311 CallingConv::ID
1312 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1313                                            bool isVarArg) const {
1314   switch (CC) {
1315   default:
1316     llvm_unreachable("Unsupported calling convention");
1317   case CallingConv::ARM_AAPCS:
1318   case CallingConv::ARM_APCS:
1319   case CallingConv::GHC:
1320     return CC;
1321   case CallingConv::ARM_AAPCS_VFP:
1322     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1323   case CallingConv::C:
1324     if (!Subtarget->isAAPCS_ABI())
1325       return CallingConv::ARM_APCS;
1326     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1327              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1328              !isVarArg)
1329       return CallingConv::ARM_AAPCS_VFP;
1330     else
1331       return CallingConv::ARM_AAPCS;
1332   case CallingConv::Fast:
1333     if (!Subtarget->isAAPCS_ABI()) {
1334       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1335         return CallingConv::Fast;
1336       return CallingConv::ARM_APCS;
1337     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1338       return CallingConv::ARM_AAPCS_VFP;
1339     else
1340       return CallingConv::ARM_AAPCS;
1341   }
1342 }
1343
1344 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1345 /// CallingConvention.
1346 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1347                                                  bool Return,
1348                                                  bool isVarArg) const {
1349   switch (getEffectiveCallingConv(CC, isVarArg)) {
1350   default:
1351     llvm_unreachable("Unsupported calling convention");
1352   case CallingConv::ARM_APCS:
1353     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1354   case CallingConv::ARM_AAPCS:
1355     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1356   case CallingConv::ARM_AAPCS_VFP:
1357     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1358   case CallingConv::Fast:
1359     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1360   case CallingConv::GHC:
1361     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1362   }
1363 }
1364
1365 /// LowerCallResult - Lower the result values of a call into the
1366 /// appropriate copies out of appropriate physical registers.
1367 SDValue
1368 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1369                                    CallingConv::ID CallConv, bool isVarArg,
1370                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1371                                    SDLoc dl, SelectionDAG &DAG,
1372                                    SmallVectorImpl<SDValue> &InVals,
1373                                    bool isThisReturn, SDValue ThisVal) const {
1374
1375   // Assign locations to each value returned by this call.
1376   SmallVector<CCValAssign, 16> RVLocs;
1377   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1378                     *DAG.getContext(), Call);
1379   CCInfo.AnalyzeCallResult(Ins,
1380                            CCAssignFnForNode(CallConv, /* Return*/ true,
1381                                              isVarArg));
1382
1383   // Copy all of the result registers out of their specified physreg.
1384   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1385     CCValAssign VA = RVLocs[i];
1386
1387     // Pass 'this' value directly from the argument to return value, to avoid
1388     // reg unit interference
1389     if (i == 0 && isThisReturn) {
1390       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1391              "unexpected return calling convention register assignment");
1392       InVals.push_back(ThisVal);
1393       continue;
1394     }
1395
1396     SDValue Val;
1397     if (VA.needsCustom()) {
1398       // Handle f64 or half of a v2f64.
1399       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1400                                       InFlag);
1401       Chain = Lo.getValue(1);
1402       InFlag = Lo.getValue(2);
1403       VA = RVLocs[++i]; // skip ahead to next loc
1404       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1405                                       InFlag);
1406       Chain = Hi.getValue(1);
1407       InFlag = Hi.getValue(2);
1408       if (!Subtarget->isLittle())
1409         std::swap (Lo, Hi);
1410       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1411
1412       if (VA.getLocVT() == MVT::v2f64) {
1413         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1414         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1415                           DAG.getConstant(0, dl, MVT::i32));
1416
1417         VA = RVLocs[++i]; // skip ahead to next loc
1418         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1419         Chain = Lo.getValue(1);
1420         InFlag = Lo.getValue(2);
1421         VA = RVLocs[++i]; // skip ahead to next loc
1422         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1423         Chain = Hi.getValue(1);
1424         InFlag = Hi.getValue(2);
1425         if (!Subtarget->isLittle())
1426           std::swap (Lo, Hi);
1427         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1428         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1429                           DAG.getConstant(1, dl, MVT::i32));
1430       }
1431     } else {
1432       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1433                                InFlag);
1434       Chain = Val.getValue(1);
1435       InFlag = Val.getValue(2);
1436     }
1437
1438     switch (VA.getLocInfo()) {
1439     default: llvm_unreachable("Unknown loc info!");
1440     case CCValAssign::Full: break;
1441     case CCValAssign::BCvt:
1442       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1443       break;
1444     }
1445
1446     InVals.push_back(Val);
1447   }
1448
1449   return Chain;
1450 }
1451
1452 /// LowerMemOpCallTo - Store the argument to the stack.
1453 SDValue
1454 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1455                                     SDValue StackPtr, SDValue Arg,
1456                                     SDLoc dl, SelectionDAG &DAG,
1457                                     const CCValAssign &VA,
1458                                     ISD::ArgFlagsTy Flags) const {
1459   unsigned LocMemOffset = VA.getLocMemOffset();
1460   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1461   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1462                        StackPtr, PtrOff);
1463   return DAG.getStore(Chain, dl, Arg, PtrOff,
1464                       MachinePointerInfo::getStack(LocMemOffset),
1465                       false, false, 0);
1466 }
1467
1468 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1469                                          SDValue Chain, SDValue &Arg,
1470                                          RegsToPassVector &RegsToPass,
1471                                          CCValAssign &VA, CCValAssign &NextVA,
1472                                          SDValue &StackPtr,
1473                                          SmallVectorImpl<SDValue> &MemOpChains,
1474                                          ISD::ArgFlagsTy Flags) const {
1475
1476   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1477                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1478   unsigned id = Subtarget->isLittle() ? 0 : 1;
1479   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1480
1481   if (NextVA.isRegLoc())
1482     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1483   else {
1484     assert(NextVA.isMemLoc());
1485     if (!StackPtr.getNode())
1486       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1487                                     getPointerTy(DAG.getDataLayout()));
1488
1489     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1490                                            dl, DAG, NextVA,
1491                                            Flags));
1492   }
1493 }
1494
1495 /// LowerCall - Lowering a call into a callseq_start <-
1496 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1497 /// nodes.
1498 SDValue
1499 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1500                              SmallVectorImpl<SDValue> &InVals) const {
1501   SelectionDAG &DAG                     = CLI.DAG;
1502   SDLoc &dl                             = CLI.DL;
1503   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1504   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1505   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1506   SDValue Chain                         = CLI.Chain;
1507   SDValue Callee                        = CLI.Callee;
1508   bool &isTailCall                      = CLI.IsTailCall;
1509   CallingConv::ID CallConv              = CLI.CallConv;
1510   bool doesNotRet                       = CLI.DoesNotReturn;
1511   bool isVarArg                         = CLI.IsVarArg;
1512
1513   MachineFunction &MF = DAG.getMachineFunction();
1514   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1515   bool isThisReturn   = false;
1516   bool isSibCall      = false;
1517   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1518
1519   // Disable tail calls if they're not supported.
1520   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1521     isTailCall = false;
1522
1523   if (isTailCall) {
1524     // Check if it's really possible to do a tail call.
1525     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1526                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1527                                                    Outs, OutVals, Ins, DAG);
1528     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1529       report_fatal_error("failed to perform tail call elimination on a call "
1530                          "site marked musttail");
1531     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1532     // detected sibcalls.
1533     if (isTailCall) {
1534       ++NumTailCalls;
1535       isSibCall = true;
1536     }
1537   }
1538
1539   // Analyze operands of the call, assigning locations to each operand.
1540   SmallVector<CCValAssign, 16> ArgLocs;
1541   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1542                     *DAG.getContext(), Call);
1543   CCInfo.AnalyzeCallOperands(Outs,
1544                              CCAssignFnForNode(CallConv, /* Return*/ false,
1545                                                isVarArg));
1546
1547   // Get a count of how many bytes are to be pushed on the stack.
1548   unsigned NumBytes = CCInfo.getNextStackOffset();
1549
1550   // For tail calls, memory operands are available in our caller's stack.
1551   if (isSibCall)
1552     NumBytes = 0;
1553
1554   // Adjust the stack pointer for the new arguments...
1555   // These operations are automatically eliminated by the prolog/epilog pass
1556   if (!isSibCall)
1557     Chain = DAG.getCALLSEQ_START(Chain,
1558                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1559
1560   SDValue StackPtr =
1561       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1562
1563   RegsToPassVector RegsToPass;
1564   SmallVector<SDValue, 8> MemOpChains;
1565
1566   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1567   // of tail call optimization, arguments are handled later.
1568   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1569        i != e;
1570        ++i, ++realArgIdx) {
1571     CCValAssign &VA = ArgLocs[i];
1572     SDValue Arg = OutVals[realArgIdx];
1573     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1574     bool isByVal = Flags.isByVal();
1575
1576     // Promote the value if needed.
1577     switch (VA.getLocInfo()) {
1578     default: llvm_unreachable("Unknown loc info!");
1579     case CCValAssign::Full: break;
1580     case CCValAssign::SExt:
1581       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1582       break;
1583     case CCValAssign::ZExt:
1584       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1585       break;
1586     case CCValAssign::AExt:
1587       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1588       break;
1589     case CCValAssign::BCvt:
1590       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1591       break;
1592     }
1593
1594     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1595     if (VA.needsCustom()) {
1596       if (VA.getLocVT() == MVT::v2f64) {
1597         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1598                                   DAG.getConstant(0, dl, MVT::i32));
1599         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1600                                   DAG.getConstant(1, dl, MVT::i32));
1601
1602         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1603                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1604
1605         VA = ArgLocs[++i]; // skip ahead to next loc
1606         if (VA.isRegLoc()) {
1607           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1608                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1609         } else {
1610           assert(VA.isMemLoc());
1611
1612           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1613                                                  dl, DAG, VA, Flags));
1614         }
1615       } else {
1616         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1617                          StackPtr, MemOpChains, Flags);
1618       }
1619     } else if (VA.isRegLoc()) {
1620       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1621         assert(VA.getLocVT() == MVT::i32 &&
1622                "unexpected calling convention register assignment");
1623         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1624                "unexpected use of 'returned'");
1625         isThisReturn = true;
1626       }
1627       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1628     } else if (isByVal) {
1629       assert(VA.isMemLoc());
1630       unsigned offset = 0;
1631
1632       // True if this byval aggregate will be split between registers
1633       // and memory.
1634       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1635       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1636
1637       if (CurByValIdx < ByValArgsCount) {
1638
1639         unsigned RegBegin, RegEnd;
1640         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1641
1642         EVT PtrVT =
1643             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1644         unsigned int i, j;
1645         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1646           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1647           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1648           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1649                                      MachinePointerInfo(),
1650                                      false, false, false,
1651                                      DAG.InferPtrAlignment(AddArg));
1652           MemOpChains.push_back(Load.getValue(1));
1653           RegsToPass.push_back(std::make_pair(j, Load));
1654         }
1655
1656         // If parameter size outsides register area, "offset" value
1657         // helps us to calculate stack slot for remained part properly.
1658         offset = RegEnd - RegBegin;
1659
1660         CCInfo.nextInRegsParam();
1661       }
1662
1663       if (Flags.getByValSize() > 4*offset) {
1664         auto PtrVT = getPointerTy(DAG.getDataLayout());
1665         unsigned LocMemOffset = VA.getLocMemOffset();
1666         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1667         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1668         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1669         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1670         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1671                                            MVT::i32);
1672         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1673                                             MVT::i32);
1674
1675         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1676         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1677         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1678                                           Ops));
1679       }
1680     } else if (!isSibCall) {
1681       assert(VA.isMemLoc());
1682
1683       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1684                                              dl, DAG, VA, Flags));
1685     }
1686   }
1687
1688   if (!MemOpChains.empty())
1689     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1690
1691   // Build a sequence of copy-to-reg nodes chained together with token chain
1692   // and flag operands which copy the outgoing args into the appropriate regs.
1693   SDValue InFlag;
1694   // Tail call byval lowering might overwrite argument registers so in case of
1695   // tail call optimization the copies to registers are lowered later.
1696   if (!isTailCall)
1697     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1698       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1699                                RegsToPass[i].second, InFlag);
1700       InFlag = Chain.getValue(1);
1701     }
1702
1703   // For tail calls lower the arguments to the 'real' stack slot.
1704   if (isTailCall) {
1705     // Force all the incoming stack arguments to be loaded from the stack
1706     // before any new outgoing arguments are stored to the stack, because the
1707     // outgoing stack slots may alias the incoming argument stack slots, and
1708     // the alias isn't otherwise explicit. This is slightly more conservative
1709     // than necessary, because it means that each store effectively depends
1710     // on every argument instead of just those arguments it would clobber.
1711
1712     // Do not flag preceding copytoreg stuff together with the following stuff.
1713     InFlag = SDValue();
1714     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1715       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1716                                RegsToPass[i].second, InFlag);
1717       InFlag = Chain.getValue(1);
1718     }
1719     InFlag = SDValue();
1720   }
1721
1722   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1723   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1724   // node so that legalize doesn't hack it.
1725   bool isDirect = false;
1726   bool isARMFunc = false;
1727   bool isLocalARMFunc = false;
1728   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1729   auto PtrVt = getPointerTy(DAG.getDataLayout());
1730
1731   if (Subtarget->genLongCalls()) {
1732     assert((Subtarget->isTargetWindows() ||
1733             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1734            "long-calls with non-static relocation model!");
1735     // Handle a global address or an external symbol. If it's not one of
1736     // those, the target's already in a register, so we don't need to do
1737     // anything extra.
1738     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1739       const GlobalValue *GV = G->getGlobal();
1740       // Create a constant pool entry for the callee address
1741       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1742       ARMConstantPoolValue *CPV =
1743         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1744
1745       // Get the address of the callee into a register
1746       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1747       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1748       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1749                            MachinePointerInfo::getConstantPool(), false, false,
1750                            false, 0);
1751     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1752       const char *Sym = S->getSymbol();
1753
1754       // Create a constant pool entry for the callee address
1755       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1756       ARMConstantPoolValue *CPV =
1757         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1758                                       ARMPCLabelIndex, 0);
1759       // Get the address of the callee into a register
1760       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1761       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1762       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1763                            MachinePointerInfo::getConstantPool(), false, false,
1764                            false, 0);
1765     }
1766   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1767     const GlobalValue *GV = G->getGlobal();
1768     isDirect = true;
1769     bool isDef = GV->isStrongDefinitionForLinker();
1770     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1771                    getTargetMachine().getRelocationModel() != Reloc::Static;
1772     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1773     // ARM call to a local ARM function is predicable.
1774     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1775     // tBX takes a register source operand.
1776     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1777       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1778       Callee = DAG.getNode(
1779           ARMISD::WrapperPIC, dl, PtrVt,
1780           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1781       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1782                            MachinePointerInfo::getGOT(), false, false, true, 0);
1783     } else if (Subtarget->isTargetCOFF()) {
1784       assert(Subtarget->isTargetWindows() &&
1785              "Windows is the only supported COFF target");
1786       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1787                                  ? ARMII::MO_DLLIMPORT
1788                                  : ARMII::MO_NO_FLAG;
1789       Callee =
1790           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1791       if (GV->hasDLLImportStorageClass())
1792         Callee =
1793             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1794                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1795                         MachinePointerInfo::getGOT(), false, false, false, 0);
1796     } else {
1797       // On ELF targets for PIC code, direct calls should go through the PLT
1798       unsigned OpFlags = 0;
1799       if (Subtarget->isTargetELF() &&
1800           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1801         OpFlags = ARMII::MO_PLT;
1802       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1803     }
1804   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1805     isDirect = true;
1806     bool isStub = Subtarget->isTargetMachO() &&
1807                   getTargetMachine().getRelocationModel() != Reloc::Static;
1808     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1809     // tBX takes a register source operand.
1810     const char *Sym = S->getSymbol();
1811     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1812       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1813       ARMConstantPoolValue *CPV =
1814         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1815                                       ARMPCLabelIndex, 4);
1816       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1817       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1818       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1819                            MachinePointerInfo::getConstantPool(), false, false,
1820                            false, 0);
1821       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1822       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1823     } else {
1824       unsigned OpFlags = 0;
1825       // On ELF targets for PIC code, direct calls should go through the PLT
1826       if (Subtarget->isTargetELF() &&
1827                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1828         OpFlags = ARMII::MO_PLT;
1829       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1830     }
1831   }
1832
1833   // FIXME: handle tail calls differently.
1834   unsigned CallOpc;
1835   if (Subtarget->isThumb()) {
1836     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1837       CallOpc = ARMISD::CALL_NOLINK;
1838     else
1839       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1840   } else {
1841     if (!isDirect && !Subtarget->hasV5TOps())
1842       CallOpc = ARMISD::CALL_NOLINK;
1843     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1844              // Emit regular call when code size is the priority
1845              !MF.getFunction()->optForMinSize())
1846       // "mov lr, pc; b _foo" to avoid confusing the RSP
1847       CallOpc = ARMISD::CALL_NOLINK;
1848     else
1849       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1850   }
1851
1852   std::vector<SDValue> Ops;
1853   Ops.push_back(Chain);
1854   Ops.push_back(Callee);
1855
1856   // Add argument registers to the end of the list so that they are known live
1857   // into the call.
1858   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1859     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1860                                   RegsToPass[i].second.getValueType()));
1861
1862   // Add a register mask operand representing the call-preserved registers.
1863   if (!isTailCall) {
1864     const uint32_t *Mask;
1865     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1866     if (isThisReturn) {
1867       // For 'this' returns, use the R0-preserving mask if applicable
1868       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1869       if (!Mask) {
1870         // Set isThisReturn to false if the calling convention is not one that
1871         // allows 'returned' to be modeled in this way, so LowerCallResult does
1872         // not try to pass 'this' straight through
1873         isThisReturn = false;
1874         Mask = ARI->getCallPreservedMask(MF, CallConv);
1875       }
1876     } else
1877       Mask = ARI->getCallPreservedMask(MF, CallConv);
1878
1879     assert(Mask && "Missing call preserved mask for calling convention");
1880     Ops.push_back(DAG.getRegisterMask(Mask));
1881   }
1882
1883   if (InFlag.getNode())
1884     Ops.push_back(InFlag);
1885
1886   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1887   if (isTailCall) {
1888     MF.getFrameInfo()->setHasTailCall();
1889     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1890   }
1891
1892   // Returns a chain and a flag for retval copy to use.
1893   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1894   InFlag = Chain.getValue(1);
1895
1896   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1897                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1898   if (!Ins.empty())
1899     InFlag = Chain.getValue(1);
1900
1901   // Handle result values, copying them out of physregs into vregs that we
1902   // return.
1903   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1904                          InVals, isThisReturn,
1905                          isThisReturn ? OutVals[0] : SDValue());
1906 }
1907
1908 /// HandleByVal - Every parameter *after* a byval parameter is passed
1909 /// on the stack.  Remember the next parameter register to allocate,
1910 /// and then confiscate the rest of the parameter registers to insure
1911 /// this.
1912 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1913                                     unsigned Align) const {
1914   assert((State->getCallOrPrologue() == Prologue ||
1915           State->getCallOrPrologue() == Call) &&
1916          "unhandled ParmContext");
1917
1918   // Byval (as with any stack) slots are always at least 4 byte aligned.
1919   Align = std::max(Align, 4U);
1920
1921   unsigned Reg = State->AllocateReg(GPRArgRegs);
1922   if (!Reg)
1923     return;
1924
1925   unsigned AlignInRegs = Align / 4;
1926   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1927   for (unsigned i = 0; i < Waste; ++i)
1928     Reg = State->AllocateReg(GPRArgRegs);
1929
1930   if (!Reg)
1931     return;
1932
1933   unsigned Excess = 4 * (ARM::R4 - Reg);
1934
1935   // Special case when NSAA != SP and parameter size greater than size of
1936   // all remained GPR regs. In that case we can't split parameter, we must
1937   // send it to stack. We also must set NCRN to R4, so waste all
1938   // remained registers.
1939   const unsigned NSAAOffset = State->getNextStackOffset();
1940   if (NSAAOffset != 0 && Size > Excess) {
1941     while (State->AllocateReg(GPRArgRegs))
1942       ;
1943     return;
1944   }
1945
1946   // First register for byval parameter is the first register that wasn't
1947   // allocated before this method call, so it would be "reg".
1948   // If parameter is small enough to be saved in range [reg, r4), then
1949   // the end (first after last) register would be reg + param-size-in-regs,
1950   // else parameter would be splitted between registers and stack,
1951   // end register would be r4 in this case.
1952   unsigned ByValRegBegin = Reg;
1953   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1954   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1955   // Note, first register is allocated in the beginning of function already,
1956   // allocate remained amount of registers we need.
1957   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1958     State->AllocateReg(GPRArgRegs);
1959   // A byval parameter that is split between registers and memory needs its
1960   // size truncated here.
1961   // In the case where the entire structure fits in registers, we set the
1962   // size in memory to zero.
1963   Size = std::max<int>(Size - Excess, 0);
1964 }
1965
1966 /// MatchingStackOffset - Return true if the given stack call argument is
1967 /// already available in the same position (relatively) of the caller's
1968 /// incoming argument stack.
1969 static
1970 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1971                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1972                          const TargetInstrInfo *TII) {
1973   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1974   int FI = INT_MAX;
1975   if (Arg.getOpcode() == ISD::CopyFromReg) {
1976     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1977     if (!TargetRegisterInfo::isVirtualRegister(VR))
1978       return false;
1979     MachineInstr *Def = MRI->getVRegDef(VR);
1980     if (!Def)
1981       return false;
1982     if (!Flags.isByVal()) {
1983       if (!TII->isLoadFromStackSlot(Def, FI))
1984         return false;
1985     } else {
1986       return false;
1987     }
1988   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1989     if (Flags.isByVal())
1990       // ByVal argument is passed in as a pointer but it's now being
1991       // dereferenced. e.g.
1992       // define @foo(%struct.X* %A) {
1993       //   tail call @bar(%struct.X* byval %A)
1994       // }
1995       return false;
1996     SDValue Ptr = Ld->getBasePtr();
1997     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1998     if (!FINode)
1999       return false;
2000     FI = FINode->getIndex();
2001   } else
2002     return false;
2003
2004   assert(FI != INT_MAX);
2005   if (!MFI->isFixedObjectIndex(FI))
2006     return false;
2007   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2008 }
2009
2010 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2011 /// for tail call optimization. Targets which want to do tail call
2012 /// optimization should implement this function.
2013 bool
2014 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2015                                                      CallingConv::ID CalleeCC,
2016                                                      bool isVarArg,
2017                                                      bool isCalleeStructRet,
2018                                                      bool isCallerStructRet,
2019                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2020                                     const SmallVectorImpl<SDValue> &OutVals,
2021                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2022                                                      SelectionDAG& DAG) const {
2023   const Function *CallerF = DAG.getMachineFunction().getFunction();
2024   CallingConv::ID CallerCC = CallerF->getCallingConv();
2025   bool CCMatch = CallerCC == CalleeCC;
2026
2027   // Look for obvious safe cases to perform tail call optimization that do not
2028   // require ABI changes. This is what gcc calls sibcall.
2029
2030   // Do not sibcall optimize vararg calls unless the call site is not passing
2031   // any arguments.
2032   if (isVarArg && !Outs.empty())
2033     return false;
2034
2035   // Exception-handling functions need a special set of instructions to indicate
2036   // a return to the hardware. Tail-calling another function would probably
2037   // break this.
2038   if (CallerF->hasFnAttribute("interrupt"))
2039     return false;
2040
2041   // Also avoid sibcall optimization if either caller or callee uses struct
2042   // return semantics.
2043   if (isCalleeStructRet || isCallerStructRet)
2044     return false;
2045
2046   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2047   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2048   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2049   // support in the assembler and linker to be used. This would need to be
2050   // fixed to fully support tail calls in Thumb1.
2051   //
2052   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2053   // LR.  This means if we need to reload LR, it takes an extra instructions,
2054   // which outweighs the value of the tail call; but here we don't know yet
2055   // whether LR is going to be used.  Probably the right approach is to
2056   // generate the tail call here and turn it back into CALL/RET in
2057   // emitEpilogue if LR is used.
2058
2059   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2060   // but we need to make sure there are enough registers; the only valid
2061   // registers are the 4 used for parameters.  We don't currently do this
2062   // case.
2063   if (Subtarget->isThumb1Only())
2064     return false;
2065
2066   // Externally-defined functions with weak linkage should not be
2067   // tail-called on ARM when the OS does not support dynamic
2068   // pre-emption of symbols, as the AAELF spec requires normal calls
2069   // to undefined weak functions to be replaced with a NOP or jump to the
2070   // next instruction. The behaviour of branch instructions in this
2071   // situation (as used for tail calls) is implementation-defined, so we
2072   // cannot rely on the linker replacing the tail call with a return.
2073   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2074     const GlobalValue *GV = G->getGlobal();
2075     const Triple &TT = getTargetMachine().getTargetTriple();
2076     if (GV->hasExternalWeakLinkage() &&
2077         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2078       return false;
2079   }
2080
2081   // If the calling conventions do not match, then we'd better make sure the
2082   // results are returned in the same way as what the caller expects.
2083   if (!CCMatch) {
2084     SmallVector<CCValAssign, 16> RVLocs1;
2085     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2086                        *DAG.getContext(), Call);
2087     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2088
2089     SmallVector<CCValAssign, 16> RVLocs2;
2090     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2091                        *DAG.getContext(), Call);
2092     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2093
2094     if (RVLocs1.size() != RVLocs2.size())
2095       return false;
2096     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2097       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2098         return false;
2099       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2100         return false;
2101       if (RVLocs1[i].isRegLoc()) {
2102         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2103           return false;
2104       } else {
2105         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2106           return false;
2107       }
2108     }
2109   }
2110
2111   // If Caller's vararg or byval argument has been split between registers and
2112   // stack, do not perform tail call, since part of the argument is in caller's
2113   // local frame.
2114   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2115                                       getInfo<ARMFunctionInfo>();
2116   if (AFI_Caller->getArgRegsSaveSize())
2117     return false;
2118
2119   // If the callee takes no arguments then go on to check the results of the
2120   // call.
2121   if (!Outs.empty()) {
2122     // Check if stack adjustment is needed. For now, do not do this if any
2123     // argument is passed on the stack.
2124     SmallVector<CCValAssign, 16> ArgLocs;
2125     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2126                       *DAG.getContext(), Call);
2127     CCInfo.AnalyzeCallOperands(Outs,
2128                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2129     if (CCInfo.getNextStackOffset()) {
2130       MachineFunction &MF = DAG.getMachineFunction();
2131
2132       // Check if the arguments are already laid out in the right way as
2133       // the caller's fixed stack objects.
2134       MachineFrameInfo *MFI = MF.getFrameInfo();
2135       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2136       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2137       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2138            i != e;
2139            ++i, ++realArgIdx) {
2140         CCValAssign &VA = ArgLocs[i];
2141         EVT RegVT = VA.getLocVT();
2142         SDValue Arg = OutVals[realArgIdx];
2143         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2144         if (VA.getLocInfo() == CCValAssign::Indirect)
2145           return false;
2146         if (VA.needsCustom()) {
2147           // f64 and vector types are split into multiple registers or
2148           // register/stack-slot combinations.  The types will not match
2149           // the registers; give up on memory f64 refs until we figure
2150           // out what to do about this.
2151           if (!VA.isRegLoc())
2152             return false;
2153           if (!ArgLocs[++i].isRegLoc())
2154             return false;
2155           if (RegVT == MVT::v2f64) {
2156             if (!ArgLocs[++i].isRegLoc())
2157               return false;
2158             if (!ArgLocs[++i].isRegLoc())
2159               return false;
2160           }
2161         } else if (!VA.isRegLoc()) {
2162           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2163                                    MFI, MRI, TII))
2164             return false;
2165         }
2166       }
2167     }
2168   }
2169
2170   return true;
2171 }
2172
2173 bool
2174 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2175                                   MachineFunction &MF, bool isVarArg,
2176                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2177                                   LLVMContext &Context) const {
2178   SmallVector<CCValAssign, 16> RVLocs;
2179   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2180   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2181                                                     isVarArg));
2182 }
2183
2184 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2185                                     SDLoc DL, SelectionDAG &DAG) {
2186   const MachineFunction &MF = DAG.getMachineFunction();
2187   const Function *F = MF.getFunction();
2188
2189   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2190
2191   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2192   // version of the "preferred return address". These offsets affect the return
2193   // instruction if this is a return from PL1 without hypervisor extensions.
2194   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2195   //    SWI:     0      "subs pc, lr, #0"
2196   //    ABORT:   +4     "subs pc, lr, #4"
2197   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2198   // UNDEF varies depending on where the exception came from ARM or Thumb
2199   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2200
2201   int64_t LROffset;
2202   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2203       IntKind == "ABORT")
2204     LROffset = 4;
2205   else if (IntKind == "SWI" || IntKind == "UNDEF")
2206     LROffset = 0;
2207   else
2208     report_fatal_error("Unsupported interrupt attribute. If present, value "
2209                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2210
2211   RetOps.insert(RetOps.begin() + 1,
2212                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2213
2214   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2215 }
2216
2217 SDValue
2218 ARMTargetLowering::LowerReturn(SDValue Chain,
2219                                CallingConv::ID CallConv, bool isVarArg,
2220                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2221                                const SmallVectorImpl<SDValue> &OutVals,
2222                                SDLoc dl, SelectionDAG &DAG) const {
2223
2224   // CCValAssign - represent the assignment of the return value to a location.
2225   SmallVector<CCValAssign, 16> RVLocs;
2226
2227   // CCState - Info about the registers and stack slots.
2228   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2229                     *DAG.getContext(), Call);
2230
2231   // Analyze outgoing return values.
2232   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2233                                                isVarArg));
2234
2235   SDValue Flag;
2236   SmallVector<SDValue, 4> RetOps;
2237   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2238   bool isLittleEndian = Subtarget->isLittle();
2239
2240   MachineFunction &MF = DAG.getMachineFunction();
2241   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2242   AFI->setReturnRegsCount(RVLocs.size());
2243
2244   // Copy the result values into the output registers.
2245   for (unsigned i = 0, realRVLocIdx = 0;
2246        i != RVLocs.size();
2247        ++i, ++realRVLocIdx) {
2248     CCValAssign &VA = RVLocs[i];
2249     assert(VA.isRegLoc() && "Can only return in registers!");
2250
2251     SDValue Arg = OutVals[realRVLocIdx];
2252
2253     switch (VA.getLocInfo()) {
2254     default: llvm_unreachable("Unknown loc info!");
2255     case CCValAssign::Full: break;
2256     case CCValAssign::BCvt:
2257       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2258       break;
2259     }
2260
2261     if (VA.needsCustom()) {
2262       if (VA.getLocVT() == MVT::v2f64) {
2263         // Extract the first half and return it in two registers.
2264         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2265                                    DAG.getConstant(0, dl, MVT::i32));
2266         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2267                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2268
2269         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2270                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2271                                  Flag);
2272         Flag = Chain.getValue(1);
2273         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2274         VA = RVLocs[++i]; // skip ahead to next loc
2275         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2276                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2277                                  Flag);
2278         Flag = Chain.getValue(1);
2279         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2280         VA = RVLocs[++i]; // skip ahead to next loc
2281
2282         // Extract the 2nd half and fall through to handle it as an f64 value.
2283         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2284                           DAG.getConstant(1, dl, MVT::i32));
2285       }
2286       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2287       // available.
2288       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2289                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2290       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2292                                Flag);
2293       Flag = Chain.getValue(1);
2294       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2295       VA = RVLocs[++i]; // skip ahead to next loc
2296       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2297                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2298                                Flag);
2299     } else
2300       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2301
2302     // Guarantee that all emitted copies are
2303     // stuck together, avoiding something bad.
2304     Flag = Chain.getValue(1);
2305     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2306   }
2307
2308   // Update chain and glue.
2309   RetOps[0] = Chain;
2310   if (Flag.getNode())
2311     RetOps.push_back(Flag);
2312
2313   // CPUs which aren't M-class use a special sequence to return from
2314   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2315   // though we use "subs pc, lr, #N").
2316   //
2317   // M-class CPUs actually use a normal return sequence with a special
2318   // (hardware-provided) value in LR, so the normal code path works.
2319   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2320       !Subtarget->isMClass()) {
2321     if (Subtarget->isThumb1Only())
2322       report_fatal_error("interrupt attribute is not supported in Thumb1");
2323     return LowerInterruptReturn(RetOps, dl, DAG);
2324   }
2325
2326   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2327 }
2328
2329 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2330   if (N->getNumValues() != 1)
2331     return false;
2332   if (!N->hasNUsesOfValue(1, 0))
2333     return false;
2334
2335   SDValue TCChain = Chain;
2336   SDNode *Copy = *N->use_begin();
2337   if (Copy->getOpcode() == ISD::CopyToReg) {
2338     // If the copy has a glue operand, we conservatively assume it isn't safe to
2339     // perform a tail call.
2340     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2341       return false;
2342     TCChain = Copy->getOperand(0);
2343   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2344     SDNode *VMov = Copy;
2345     // f64 returned in a pair of GPRs.
2346     SmallPtrSet<SDNode*, 2> Copies;
2347     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2348          UI != UE; ++UI) {
2349       if (UI->getOpcode() != ISD::CopyToReg)
2350         return false;
2351       Copies.insert(*UI);
2352     }
2353     if (Copies.size() > 2)
2354       return false;
2355
2356     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2357          UI != UE; ++UI) {
2358       SDValue UseChain = UI->getOperand(0);
2359       if (Copies.count(UseChain.getNode()))
2360         // Second CopyToReg
2361         Copy = *UI;
2362       else {
2363         // We are at the top of this chain.
2364         // If the copy has a glue operand, we conservatively assume it
2365         // isn't safe to perform a tail call.
2366         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2367           return false;
2368         // First CopyToReg
2369         TCChain = UseChain;
2370       }
2371     }
2372   } else if (Copy->getOpcode() == ISD::BITCAST) {
2373     // f32 returned in a single GPR.
2374     if (!Copy->hasOneUse())
2375       return false;
2376     Copy = *Copy->use_begin();
2377     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2378       return false;
2379     // If the copy has a glue operand, we conservatively assume it isn't safe to
2380     // perform a tail call.
2381     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2382       return false;
2383     TCChain = Copy->getOperand(0);
2384   } else {
2385     return false;
2386   }
2387
2388   bool HasRet = false;
2389   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2390        UI != UE; ++UI) {
2391     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2392         UI->getOpcode() != ARMISD::INTRET_FLAG)
2393       return false;
2394     HasRet = true;
2395   }
2396
2397   if (!HasRet)
2398     return false;
2399
2400   Chain = TCChain;
2401   return true;
2402 }
2403
2404 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2405   if (!Subtarget->supportsTailCall())
2406     return false;
2407
2408   auto Attr =
2409       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2410   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2411     return false;
2412
2413   return !Subtarget->isThumb1Only();
2414 }
2415
2416 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2417 // and pass the lower and high parts through.
2418 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2419   SDLoc DL(Op);
2420   SDValue WriteValue = Op->getOperand(2);
2421
2422   // This function is only supposed to be called for i64 type argument.
2423   assert(WriteValue.getValueType() == MVT::i64
2424           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2425
2426   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2427                            DAG.getConstant(0, DL, MVT::i32));
2428   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2429                            DAG.getConstant(1, DL, MVT::i32));
2430   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2431   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2432 }
2433
2434 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2435 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2436 // one of the above mentioned nodes. It has to be wrapped because otherwise
2437 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2438 // be used to form addressing mode. These wrapped nodes will be selected
2439 // into MOVi.
2440 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2441   EVT PtrVT = Op.getValueType();
2442   // FIXME there is no actual debug info here
2443   SDLoc dl(Op);
2444   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2445   SDValue Res;
2446   if (CP->isMachineConstantPoolEntry())
2447     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2448                                     CP->getAlignment());
2449   else
2450     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2451                                     CP->getAlignment());
2452   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2453 }
2454
2455 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2456   return MachineJumpTableInfo::EK_Inline;
2457 }
2458
2459 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2460                                              SelectionDAG &DAG) const {
2461   MachineFunction &MF = DAG.getMachineFunction();
2462   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2463   unsigned ARMPCLabelIndex = 0;
2464   SDLoc DL(Op);
2465   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2466   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2467   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2468   SDValue CPAddr;
2469   if (RelocM == Reloc::Static) {
2470     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2471   } else {
2472     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2473     ARMPCLabelIndex = AFI->createPICLabelUId();
2474     ARMConstantPoolValue *CPV =
2475       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2476                                       ARMCP::CPBlockAddress, PCAdj);
2477     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2478   }
2479   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2480   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2481                                MachinePointerInfo::getConstantPool(),
2482                                false, false, false, 0);
2483   if (RelocM == Reloc::Static)
2484     return Result;
2485   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2486   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2487 }
2488
2489 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2490 SDValue
2491 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2492                                                  SelectionDAG &DAG) const {
2493   SDLoc dl(GA);
2494   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2495   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2496   MachineFunction &MF = DAG.getMachineFunction();
2497   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2498   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2499   ARMConstantPoolValue *CPV =
2500     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2501                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2502   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2503   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2504   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2505                          MachinePointerInfo::getConstantPool(),
2506                          false, false, false, 0);
2507   SDValue Chain = Argument.getValue(1);
2508
2509   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2510   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2511
2512   // call __tls_get_addr.
2513   ArgListTy Args;
2514   ArgListEntry Entry;
2515   Entry.Node = Argument;
2516   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2517   Args.push_back(Entry);
2518
2519   // FIXME: is there useful debug info available here?
2520   TargetLowering::CallLoweringInfo CLI(DAG);
2521   CLI.setDebugLoc(dl).setChain(Chain)
2522     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2523                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2524                0);
2525
2526   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2527   return CallResult.first;
2528 }
2529
2530 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2531 // "local exec" model.
2532 SDValue
2533 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2534                                         SelectionDAG &DAG,
2535                                         TLSModel::Model model) const {
2536   const GlobalValue *GV = GA->getGlobal();
2537   SDLoc dl(GA);
2538   SDValue Offset;
2539   SDValue Chain = DAG.getEntryNode();
2540   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2541   // Get the Thread Pointer
2542   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2543
2544   if (model == TLSModel::InitialExec) {
2545     MachineFunction &MF = DAG.getMachineFunction();
2546     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2547     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2548     // Initial exec model.
2549     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2550     ARMConstantPoolValue *CPV =
2551       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2552                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2553                                       true);
2554     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2555     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2556     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2557                          MachinePointerInfo::getConstantPool(),
2558                          false, false, false, 0);
2559     Chain = Offset.getValue(1);
2560
2561     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2562     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2563
2564     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2565                          MachinePointerInfo::getConstantPool(),
2566                          false, false, false, 0);
2567   } else {
2568     // local exec model
2569     assert(model == TLSModel::LocalExec);
2570     ARMConstantPoolValue *CPV =
2571       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2572     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2573     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2574     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2575                          MachinePointerInfo::getConstantPool(),
2576                          false, false, false, 0);
2577   }
2578
2579   // The address of the thread local variable is the add of the thread
2580   // pointer with the offset of the variable.
2581   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2582 }
2583
2584 SDValue
2585 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2586   // TODO: implement the "local dynamic" model
2587   assert(Subtarget->isTargetELF() &&
2588          "TLS not implemented for non-ELF targets");
2589   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2590   if (DAG.getTarget().Options.EmulatedTLS)
2591     return LowerToTLSEmulatedModel(GA, DAG);
2592
2593   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2594
2595   switch (model) {
2596     case TLSModel::GeneralDynamic:
2597     case TLSModel::LocalDynamic:
2598       return LowerToTLSGeneralDynamicModel(GA, DAG);
2599     case TLSModel::InitialExec:
2600     case TLSModel::LocalExec:
2601       return LowerToTLSExecModels(GA, DAG, model);
2602   }
2603   llvm_unreachable("bogus TLS model");
2604 }
2605
2606 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2607                                                  SelectionDAG &DAG) const {
2608   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2609   SDLoc dl(Op);
2610   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2611   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2612     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2613     ARMConstantPoolValue *CPV =
2614       ARMConstantPoolConstant::Create(GV,
2615                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2616     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2617     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2618     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2619                                  CPAddr,
2620                                  MachinePointerInfo::getConstantPool(),
2621                                  false, false, false, 0);
2622     SDValue Chain = Result.getValue(1);
2623     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2624     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2625     if (!UseGOTOFF)
2626       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2627                            MachinePointerInfo::getGOT(),
2628                            false, false, false, 0);
2629     return Result;
2630   }
2631
2632   // If we have T2 ops, we can materialize the address directly via movt/movw
2633   // pair. This is always cheaper.
2634   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2635     ++NumMovwMovt;
2636     // FIXME: Once remat is capable of dealing with instructions with register
2637     // operands, expand this into two nodes.
2638     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2639                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2640   } else {
2641     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2642     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2643     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2644                        MachinePointerInfo::getConstantPool(),
2645                        false, false, false, 0);
2646   }
2647 }
2648
2649 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2650                                                     SelectionDAG &DAG) const {
2651   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2652   SDLoc dl(Op);
2653   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2654   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2655
2656   if (Subtarget->useMovt(DAG.getMachineFunction()))
2657     ++NumMovwMovt;
2658
2659   // FIXME: Once remat is capable of dealing with instructions with register
2660   // operands, expand this into multiple nodes
2661   unsigned Wrapper =
2662       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2663
2664   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2665   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2666
2667   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2668     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2669                          MachinePointerInfo::getGOT(), false, false, false, 0);
2670   return Result;
2671 }
2672
2673 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2674                                                      SelectionDAG &DAG) const {
2675   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2676   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2677          "Windows on ARM expects to use movw/movt");
2678
2679   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2680   const ARMII::TOF TargetFlags =
2681     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2682   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2683   SDValue Result;
2684   SDLoc DL(Op);
2685
2686   ++NumMovwMovt;
2687
2688   // FIXME: Once remat is capable of dealing with instructions with register
2689   // operands, expand this into two nodes.
2690   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2691                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2692                                                   TargetFlags));
2693   if (GV->hasDLLImportStorageClass())
2694     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2695                          MachinePointerInfo::getGOT(), false, false, false, 0);
2696   return Result;
2697 }
2698
2699 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2700                                                     SelectionDAG &DAG) const {
2701   assert(Subtarget->isTargetELF() &&
2702          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2703   MachineFunction &MF = DAG.getMachineFunction();
2704   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2705   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2706   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2707   SDLoc dl(Op);
2708   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2709   ARMConstantPoolValue *CPV =
2710     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2711                                   ARMPCLabelIndex, PCAdj);
2712   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2713   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2714   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2715                                MachinePointerInfo::getConstantPool(),
2716                                false, false, false, 0);
2717   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2718   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2719 }
2720
2721 SDValue
2722 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2723   SDLoc dl(Op);
2724   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2725   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2726                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2727                      Op.getOperand(1), Val);
2728 }
2729
2730 SDValue
2731 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2732   SDLoc dl(Op);
2733   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2734                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2735 }
2736
2737 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2738                                                       SelectionDAG &DAG) const {
2739   SDLoc dl(Op);
2740   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2741                      Op.getOperand(0));
2742 }
2743
2744 SDValue
2745 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2746                                           const ARMSubtarget *Subtarget) const {
2747   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2748   SDLoc dl(Op);
2749   switch (IntNo) {
2750   default: return SDValue();    // Don't custom lower most intrinsics.
2751   case Intrinsic::arm_rbit: {
2752     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2753            "RBIT intrinsic must have i32 type!");
2754     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2755   }
2756   case Intrinsic::arm_thread_pointer: {
2757     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2758     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2759   }
2760   case Intrinsic::eh_sjlj_lsda: {
2761     MachineFunction &MF = DAG.getMachineFunction();
2762     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2763     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2764     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2765     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2766     SDValue CPAddr;
2767     unsigned PCAdj = (RelocM != Reloc::PIC_)
2768       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2769     ARMConstantPoolValue *CPV =
2770       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2771                                       ARMCP::CPLSDA, PCAdj);
2772     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2773     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2774     SDValue Result =
2775       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2776                   MachinePointerInfo::getConstantPool(),
2777                   false, false, false, 0);
2778
2779     if (RelocM == Reloc::PIC_) {
2780       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2781       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2782     }
2783     return Result;
2784   }
2785   case Intrinsic::arm_neon_vmulls:
2786   case Intrinsic::arm_neon_vmullu: {
2787     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2788       ? ARMISD::VMULLs : ARMISD::VMULLu;
2789     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2790                        Op.getOperand(1), Op.getOperand(2));
2791   }
2792   }
2793 }
2794
2795 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2796                                  const ARMSubtarget *Subtarget) {
2797   // FIXME: handle "fence singlethread" more efficiently.
2798   SDLoc dl(Op);
2799   if (!Subtarget->hasDataBarrier()) {
2800     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2801     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2802     // here.
2803     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2804            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2805     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2806                        DAG.getConstant(0, dl, MVT::i32));
2807   }
2808
2809   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2810   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2811   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2812   if (Subtarget->isMClass()) {
2813     // Only a full system barrier exists in the M-class architectures.
2814     Domain = ARM_MB::SY;
2815   } else if (Subtarget->isSwift() && Ord == Release) {
2816     // Swift happens to implement ISHST barriers in a way that's compatible with
2817     // Release semantics but weaker than ISH so we'd be fools not to use
2818     // it. Beware: other processors probably don't!
2819     Domain = ARM_MB::ISHST;
2820   }
2821
2822   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2823                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2824                      DAG.getConstant(Domain, dl, MVT::i32));
2825 }
2826
2827 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2828                              const ARMSubtarget *Subtarget) {
2829   // ARM pre v5TE and Thumb1 does not have preload instructions.
2830   if (!(Subtarget->isThumb2() ||
2831         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2832     // Just preserve the chain.
2833     return Op.getOperand(0);
2834
2835   SDLoc dl(Op);
2836   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2837   if (!isRead &&
2838       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2839     // ARMv7 with MP extension has PLDW.
2840     return Op.getOperand(0);
2841
2842   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2843   if (Subtarget->isThumb()) {
2844     // Invert the bits.
2845     isRead = ~isRead & 1;
2846     isData = ~isData & 1;
2847   }
2848
2849   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2850                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2851                      DAG.getConstant(isData, dl, MVT::i32));
2852 }
2853
2854 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2855   MachineFunction &MF = DAG.getMachineFunction();
2856   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2857
2858   // vastart just stores the address of the VarArgsFrameIndex slot into the
2859   // memory location argument.
2860   SDLoc dl(Op);
2861   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2862   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2863   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2864   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2865                       MachinePointerInfo(SV), false, false, 0);
2866 }
2867
2868 SDValue
2869 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2870                                         SDValue &Root, SelectionDAG &DAG,
2871                                         SDLoc dl) const {
2872   MachineFunction &MF = DAG.getMachineFunction();
2873   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2874
2875   const TargetRegisterClass *RC;
2876   if (AFI->isThumb1OnlyFunction())
2877     RC = &ARM::tGPRRegClass;
2878   else
2879     RC = &ARM::GPRRegClass;
2880
2881   // Transform the arguments stored in physical registers into virtual ones.
2882   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2883   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2884
2885   SDValue ArgValue2;
2886   if (NextVA.isMemLoc()) {
2887     MachineFrameInfo *MFI = MF.getFrameInfo();
2888     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2889
2890     // Create load node to retrieve arguments from the stack.
2891     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2892     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2893                             MachinePointerInfo::getFixedStack(FI),
2894                             false, false, false, 0);
2895   } else {
2896     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2897     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2898   }
2899   if (!Subtarget->isLittle())
2900     std::swap (ArgValue, ArgValue2);
2901   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2902 }
2903
2904 // The remaining GPRs hold either the beginning of variable-argument
2905 // data, or the beginning of an aggregate passed by value (usually
2906 // byval).  Either way, we allocate stack slots adjacent to the data
2907 // provided by our caller, and store the unallocated registers there.
2908 // If this is a variadic function, the va_list pointer will begin with
2909 // these values; otherwise, this reassembles a (byval) structure that
2910 // was split between registers and memory.
2911 // Return: The frame index registers were stored into.
2912 int
2913 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2914                                   SDLoc dl, SDValue &Chain,
2915                                   const Value *OrigArg,
2916                                   unsigned InRegsParamRecordIdx,
2917                                   int ArgOffset,
2918                                   unsigned ArgSize) const {
2919   // Currently, two use-cases possible:
2920   // Case #1. Non-var-args function, and we meet first byval parameter.
2921   //          Setup first unallocated register as first byval register;
2922   //          eat all remained registers
2923   //          (these two actions are performed by HandleByVal method).
2924   //          Then, here, we initialize stack frame with
2925   //          "store-reg" instructions.
2926   // Case #2. Var-args function, that doesn't contain byval parameters.
2927   //          The same: eat all remained unallocated registers,
2928   //          initialize stack frame.
2929
2930   MachineFunction &MF = DAG.getMachineFunction();
2931   MachineFrameInfo *MFI = MF.getFrameInfo();
2932   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2933   unsigned RBegin, REnd;
2934   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2935     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2936   } else {
2937     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2938     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2939     REnd = ARM::R4;
2940   }
2941
2942   if (REnd != RBegin)
2943     ArgOffset = -4 * (ARM::R4 - RBegin);
2944
2945   auto PtrVT = getPointerTy(DAG.getDataLayout());
2946   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2947   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2948
2949   SmallVector<SDValue, 4> MemOps;
2950   const TargetRegisterClass *RC =
2951       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2952
2953   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2954     unsigned VReg = MF.addLiveIn(Reg, RC);
2955     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2956     SDValue Store =
2957         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2958                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2959     MemOps.push_back(Store);
2960     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2961   }
2962
2963   if (!MemOps.empty())
2964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2965   return FrameIndex;
2966 }
2967
2968 // Setup stack frame, the va_list pointer will start from.
2969 void
2970 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2971                                         SDLoc dl, SDValue &Chain,
2972                                         unsigned ArgOffset,
2973                                         unsigned TotalArgRegsSaveSize,
2974                                         bool ForceMutable) const {
2975   MachineFunction &MF = DAG.getMachineFunction();
2976   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2977
2978   // Try to store any remaining integer argument regs
2979   // to their spots on the stack so that they may be loaded by deferencing
2980   // the result of va_next.
2981   // If there is no regs to be stored, just point address after last
2982   // argument passed via stack.
2983   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2984                                   CCInfo.getInRegsParamsCount(),
2985                                   CCInfo.getNextStackOffset(), 4);
2986   AFI->setVarArgsFrameIndex(FrameIndex);
2987 }
2988
2989 SDValue
2990 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2991                                         CallingConv::ID CallConv, bool isVarArg,
2992                                         const SmallVectorImpl<ISD::InputArg>
2993                                           &Ins,
2994                                         SDLoc dl, SelectionDAG &DAG,
2995                                         SmallVectorImpl<SDValue> &InVals)
2996                                           const {
2997   MachineFunction &MF = DAG.getMachineFunction();
2998   MachineFrameInfo *MFI = MF.getFrameInfo();
2999
3000   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3001
3002   // Assign locations to all of the incoming arguments.
3003   SmallVector<CCValAssign, 16> ArgLocs;
3004   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3005                     *DAG.getContext(), Prologue);
3006   CCInfo.AnalyzeFormalArguments(Ins,
3007                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3008                                                   isVarArg));
3009
3010   SmallVector<SDValue, 16> ArgValues;
3011   SDValue ArgValue;
3012   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3013   unsigned CurArgIdx = 0;
3014
3015   // Initially ArgRegsSaveSize is zero.
3016   // Then we increase this value each time we meet byval parameter.
3017   // We also increase this value in case of varargs function.
3018   AFI->setArgRegsSaveSize(0);
3019
3020   // Calculate the amount of stack space that we need to allocate to store
3021   // byval and variadic arguments that are passed in registers.
3022   // We need to know this before we allocate the first byval or variadic
3023   // argument, as they will be allocated a stack slot below the CFA (Canonical
3024   // Frame Address, the stack pointer at entry to the function).
3025   unsigned ArgRegBegin = ARM::R4;
3026   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3027     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3028       break;
3029
3030     CCValAssign &VA = ArgLocs[i];
3031     unsigned Index = VA.getValNo();
3032     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3033     if (!Flags.isByVal())
3034       continue;
3035
3036     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3037     unsigned RBegin, REnd;
3038     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3039     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3040
3041     CCInfo.nextInRegsParam();
3042   }
3043   CCInfo.rewindByValRegsInfo();
3044
3045   int lastInsIndex = -1;
3046   if (isVarArg && MFI->hasVAStart()) {
3047     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3048     if (RegIdx != array_lengthof(GPRArgRegs))
3049       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3050   }
3051
3052   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3053   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3054   auto PtrVT = getPointerTy(DAG.getDataLayout());
3055
3056   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3057     CCValAssign &VA = ArgLocs[i];
3058     if (Ins[VA.getValNo()].isOrigArg()) {
3059       std::advance(CurOrigArg,
3060                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3061       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3062     }
3063     // Arguments stored in registers.
3064     if (VA.isRegLoc()) {
3065       EVT RegVT = VA.getLocVT();
3066
3067       if (VA.needsCustom()) {
3068         // f64 and vector types are split up into multiple registers or
3069         // combinations of registers and stack slots.
3070         if (VA.getLocVT() == MVT::v2f64) {
3071           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3072                                                    Chain, DAG, dl);
3073           VA = ArgLocs[++i]; // skip ahead to next loc
3074           SDValue ArgValue2;
3075           if (VA.isMemLoc()) {
3076             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3077             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3078             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3079                                     MachinePointerInfo::getFixedStack(FI),
3080                                     false, false, false, 0);
3081           } else {
3082             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3083                                              Chain, DAG, dl);
3084           }
3085           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3086           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3087                                  ArgValue, ArgValue1,
3088                                  DAG.getIntPtrConstant(0, dl));
3089           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3090                                  ArgValue, ArgValue2,
3091                                  DAG.getIntPtrConstant(1, dl));
3092         } else
3093           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3094
3095       } else {
3096         const TargetRegisterClass *RC;
3097
3098         if (RegVT == MVT::f32)
3099           RC = &ARM::SPRRegClass;
3100         else if (RegVT == MVT::f64)
3101           RC = &ARM::DPRRegClass;
3102         else if (RegVT == MVT::v2f64)
3103           RC = &ARM::QPRRegClass;
3104         else if (RegVT == MVT::i32)
3105           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3106                                            : &ARM::GPRRegClass;
3107         else
3108           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3109
3110         // Transform the arguments in physical registers into virtual ones.
3111         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3112         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3113       }
3114
3115       // If this is an 8 or 16-bit value, it is really passed promoted
3116       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3117       // truncate to the right size.
3118       switch (VA.getLocInfo()) {
3119       default: llvm_unreachable("Unknown loc info!");
3120       case CCValAssign::Full: break;
3121       case CCValAssign::BCvt:
3122         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3123         break;
3124       case CCValAssign::SExt:
3125         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3126                                DAG.getValueType(VA.getValVT()));
3127         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3128         break;
3129       case CCValAssign::ZExt:
3130         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3131                                DAG.getValueType(VA.getValVT()));
3132         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3133         break;
3134       }
3135
3136       InVals.push_back(ArgValue);
3137
3138     } else { // VA.isRegLoc()
3139
3140       // sanity check
3141       assert(VA.isMemLoc());
3142       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3143
3144       int index = VA.getValNo();
3145
3146       // Some Ins[] entries become multiple ArgLoc[] entries.
3147       // Process them only once.
3148       if (index != lastInsIndex)
3149         {
3150           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3151           // FIXME: For now, all byval parameter objects are marked mutable.
3152           // This can be changed with more analysis.
3153           // In case of tail call optimization mark all arguments mutable.
3154           // Since they could be overwritten by lowering of arguments in case of
3155           // a tail call.
3156           if (Flags.isByVal()) {
3157             assert(Ins[index].isOrigArg() &&
3158                    "Byval arguments cannot be implicit");
3159             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3160
3161             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3162                                             CurByValIndex, VA.getLocMemOffset(),
3163                                             Flags.getByValSize());
3164             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3165             CCInfo.nextInRegsParam();
3166           } else {
3167             unsigned FIOffset = VA.getLocMemOffset();
3168             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3169                                             FIOffset, true);
3170
3171             // Create load nodes to retrieve arguments from the stack.
3172             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3173             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3174                                          MachinePointerInfo::getFixedStack(FI),
3175                                          false, false, false, 0));
3176           }
3177           lastInsIndex = index;
3178         }
3179     }
3180   }
3181
3182   // varargs
3183   if (isVarArg && MFI->hasVAStart())
3184     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3185                          CCInfo.getNextStackOffset(),
3186                          TotalArgRegsSaveSize);
3187
3188   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3189
3190   return Chain;
3191 }
3192
3193 /// isFloatingPointZero - Return true if this is +0.0.
3194 static bool isFloatingPointZero(SDValue Op) {
3195   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3196     return CFP->getValueAPF().isPosZero();
3197   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3198     // Maybe this has already been legalized into the constant pool?
3199     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3200       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3201       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3202         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3203           return CFP->getValueAPF().isPosZero();
3204     }
3205   } else if (Op->getOpcode() == ISD::BITCAST &&
3206              Op->getValueType(0) == MVT::f64) {
3207     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3208     // created by LowerConstantFP().
3209     SDValue BitcastOp = Op->getOperand(0);
3210     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3211       SDValue MoveOp = BitcastOp->getOperand(0);
3212       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3213           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3214         return true;
3215       }
3216     }
3217   }
3218   return false;
3219 }
3220
3221 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3222 /// the given operands.
3223 SDValue
3224 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3225                              SDValue &ARMcc, SelectionDAG &DAG,
3226                              SDLoc dl) const {
3227   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3228     unsigned C = RHSC->getZExtValue();
3229     if (!isLegalICmpImmediate(C)) {
3230       // Constant does not fit, try adjusting it by one?
3231       switch (CC) {
3232       default: break;
3233       case ISD::SETLT:
3234       case ISD::SETGE:
3235         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3236           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3237           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3238         }
3239         break;
3240       case ISD::SETULT:
3241       case ISD::SETUGE:
3242         if (C != 0 && isLegalICmpImmediate(C-1)) {
3243           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3244           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3245         }
3246         break;
3247       case ISD::SETLE:
3248       case ISD::SETGT:
3249         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3250           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3251           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3252         }
3253         break;
3254       case ISD::SETULE:
3255       case ISD::SETUGT:
3256         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3257           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3258           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3259         }
3260         break;
3261       }
3262     }
3263   }
3264
3265   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3266   ARMISD::NodeType CompareType;
3267   switch (CondCode) {
3268   default:
3269     CompareType = ARMISD::CMP;
3270     break;
3271   case ARMCC::EQ:
3272   case ARMCC::NE:
3273     // Uses only Z Flag
3274     CompareType = ARMISD::CMPZ;
3275     break;
3276   }
3277   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3278   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3279 }
3280
3281 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3282 SDValue
3283 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3284                              SDLoc dl) const {
3285   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3286   SDValue Cmp;
3287   if (!isFloatingPointZero(RHS))
3288     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3289   else
3290     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3291   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3292 }
3293
3294 /// duplicateCmp - Glue values can have only one use, so this function
3295 /// duplicates a comparison node.
3296 SDValue
3297 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3298   unsigned Opc = Cmp.getOpcode();
3299   SDLoc DL(Cmp);
3300   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3301     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3302
3303   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3304   Cmp = Cmp.getOperand(0);
3305   Opc = Cmp.getOpcode();
3306   if (Opc == ARMISD::CMPFP)
3307     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3308   else {
3309     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3310     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3311   }
3312   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3313 }
3314
3315 std::pair<SDValue, SDValue>
3316 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3317                                  SDValue &ARMcc) const {
3318   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3319
3320   SDValue Value, OverflowCmp;
3321   SDValue LHS = Op.getOperand(0);
3322   SDValue RHS = Op.getOperand(1);
3323   SDLoc dl(Op);
3324
3325   // FIXME: We are currently always generating CMPs because we don't support
3326   // generating CMN through the backend. This is not as good as the natural
3327   // CMP case because it causes a register dependency and cannot be folded
3328   // later.
3329
3330   switch (Op.getOpcode()) {
3331   default:
3332     llvm_unreachable("Unknown overflow instruction!");
3333   case ISD::SADDO:
3334     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3335     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3336     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3337     break;
3338   case ISD::UADDO:
3339     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3340     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3341     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3342     break;
3343   case ISD::SSUBO:
3344     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3345     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3346     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3347     break;
3348   case ISD::USUBO:
3349     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3350     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3351     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3352     break;
3353   } // switch (...)
3354
3355   return std::make_pair(Value, OverflowCmp);
3356 }
3357
3358
3359 SDValue
3360 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3361   // Let legalize expand this if it isn't a legal type yet.
3362   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3363     return SDValue();
3364
3365   SDValue Value, OverflowCmp;
3366   SDValue ARMcc;
3367   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3368   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3369   SDLoc dl(Op);
3370   // We use 0 and 1 as false and true values.
3371   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3372   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3373   EVT VT = Op.getValueType();
3374
3375   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3376                                  ARMcc, CCR, OverflowCmp);
3377
3378   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3379   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3380 }
3381
3382
3383 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3384   SDValue Cond = Op.getOperand(0);
3385   SDValue SelectTrue = Op.getOperand(1);
3386   SDValue SelectFalse = Op.getOperand(2);
3387   SDLoc dl(Op);
3388   unsigned Opc = Cond.getOpcode();
3389
3390   if (Cond.getResNo() == 1 &&
3391       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3392        Opc == ISD::USUBO)) {
3393     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3394       return SDValue();
3395
3396     SDValue Value, OverflowCmp;
3397     SDValue ARMcc;
3398     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3399     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3400     EVT VT = Op.getValueType();
3401
3402     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3403                    OverflowCmp, DAG);
3404   }
3405
3406   // Convert:
3407   //
3408   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3409   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3410   //
3411   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3412     const ConstantSDNode *CMOVTrue =
3413       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3414     const ConstantSDNode *CMOVFalse =
3415       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3416
3417     if (CMOVTrue && CMOVFalse) {
3418       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3419       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3420
3421       SDValue True;
3422       SDValue False;
3423       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3424         True = SelectTrue;
3425         False = SelectFalse;
3426       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3427         True = SelectFalse;
3428         False = SelectTrue;
3429       }
3430
3431       if (True.getNode() && False.getNode()) {
3432         EVT VT = Op.getValueType();
3433         SDValue ARMcc = Cond.getOperand(2);
3434         SDValue CCR = Cond.getOperand(3);
3435         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3436         assert(True.getValueType() == VT);
3437         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3438       }
3439     }
3440   }
3441
3442   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3443   // undefined bits before doing a full-word comparison with zero.
3444   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3445                      DAG.getConstant(1, dl, Cond.getValueType()));
3446
3447   return DAG.getSelectCC(dl, Cond,
3448                          DAG.getConstant(0, dl, Cond.getValueType()),
3449                          SelectTrue, SelectFalse, ISD::SETNE);
3450 }
3451
3452 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3453                                  bool &swpCmpOps, bool &swpVselOps) {
3454   // Start by selecting the GE condition code for opcodes that return true for
3455   // 'equality'
3456   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3457       CC == ISD::SETULE)
3458     CondCode = ARMCC::GE;
3459
3460   // and GT for opcodes that return false for 'equality'.
3461   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3462            CC == ISD::SETULT)
3463     CondCode = ARMCC::GT;
3464
3465   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3466   // to swap the compare operands.
3467   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3468       CC == ISD::SETULT)
3469     swpCmpOps = true;
3470
3471   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3472   // If we have an unordered opcode, we need to swap the operands to the VSEL
3473   // instruction (effectively negating the condition).
3474   //
3475   // This also has the effect of swapping which one of 'less' or 'greater'
3476   // returns true, so we also swap the compare operands. It also switches
3477   // whether we return true for 'equality', so we compensate by picking the
3478   // opposite condition code to our original choice.
3479   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3480       CC == ISD::SETUGT) {
3481     swpCmpOps = !swpCmpOps;
3482     swpVselOps = !swpVselOps;
3483     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3484   }
3485
3486   // 'ordered' is 'anything but unordered', so use the VS condition code and
3487   // swap the VSEL operands.
3488   if (CC == ISD::SETO) {
3489     CondCode = ARMCC::VS;
3490     swpVselOps = true;
3491   }
3492
3493   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3494   // code and swap the VSEL operands.
3495   if (CC == ISD::SETUNE) {
3496     CondCode = ARMCC::EQ;
3497     swpVselOps = true;
3498   }
3499 }
3500
3501 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3502                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3503                                    SDValue Cmp, SelectionDAG &DAG) const {
3504   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3505     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3506                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3507     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3508                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3509
3510     SDValue TrueLow = TrueVal.getValue(0);
3511     SDValue TrueHigh = TrueVal.getValue(1);
3512     SDValue FalseLow = FalseVal.getValue(0);
3513     SDValue FalseHigh = FalseVal.getValue(1);
3514
3515     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3516                               ARMcc, CCR, Cmp);
3517     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3518                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3519
3520     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3521   } else {
3522     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3523                        Cmp);
3524   }
3525 }
3526
3527 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3528   EVT VT = Op.getValueType();
3529   SDValue LHS = Op.getOperand(0);
3530   SDValue RHS = Op.getOperand(1);
3531   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3532   SDValue TrueVal = Op.getOperand(2);
3533   SDValue FalseVal = Op.getOperand(3);
3534   SDLoc dl(Op);
3535
3536   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3537     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3538                                                     dl);
3539
3540     // If softenSetCCOperands only returned one value, we should compare it to
3541     // zero.
3542     if (!RHS.getNode()) {
3543       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3544       CC = ISD::SETNE;
3545     }
3546   }
3547
3548   if (LHS.getValueType() == MVT::i32) {
3549     // Try to generate VSEL on ARMv8.
3550     // The VSEL instruction can't use all the usual ARM condition
3551     // codes: it only has two bits to select the condition code, so it's
3552     // constrained to use only GE, GT, VS and EQ.
3553     //
3554     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3555     // swap the operands of the previous compare instruction (effectively
3556     // inverting the compare condition, swapping 'less' and 'greater') and
3557     // sometimes need to swap the operands to the VSEL (which inverts the
3558     // condition in the sense of firing whenever the previous condition didn't)
3559     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3560                                     TrueVal.getValueType() == MVT::f64)) {
3561       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3562       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3563           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3564         CC = ISD::getSetCCInverse(CC, true);
3565         std::swap(TrueVal, FalseVal);
3566       }
3567     }
3568
3569     SDValue ARMcc;
3570     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3571     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3572     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3573   }
3574
3575   ARMCC::CondCodes CondCode, CondCode2;
3576   FPCCToARMCC(CC, CondCode, CondCode2);
3577
3578   // Try to generate VMAXNM/VMINNM on ARMv8.
3579   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3580                                   TrueVal.getValueType() == MVT::f64)) {
3581     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3582     // same operands, as follows:
3583     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3584     //   select c, a, b
3585     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3586     bool swapSides = false;
3587     if (!getTargetMachine().Options.NoNaNsFPMath) {
3588       // transformability may depend on which way around we compare
3589       switch (CC) {
3590       default:
3591         break;
3592       case ISD::SETOGT:
3593       case ISD::SETOGE:
3594       case ISD::SETOLT:
3595       case ISD::SETOLE:
3596         // the non-NaN should be RHS
3597         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3598         break;
3599       case ISD::SETUGT:
3600       case ISD::SETUGE:
3601       case ISD::SETULT:
3602       case ISD::SETULE:
3603         // the non-NaN should be LHS
3604         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3605         break;
3606       }
3607     }
3608     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3609     if (swapSides) {
3610       CC = ISD::getSetCCSwappedOperands(CC);
3611       std::swap(LHS, RHS);
3612     }
3613     if (LHS == TrueVal && RHS == FalseVal) {
3614       bool canTransform = true;
3615       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3616       if (!getTargetMachine().Options.UnsafeFPMath &&
3617           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3618         const ConstantFPSDNode *Zero;
3619         switch (CC) {
3620         default:
3621           break;
3622         case ISD::SETOGT:
3623         case ISD::SETUGT:
3624         case ISD::SETGT:
3625           // RHS must not be -0
3626           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3627                          !Zero->isNegative();
3628           break;
3629         case ISD::SETOGE:
3630         case ISD::SETUGE:
3631         case ISD::SETGE:
3632           // LHS must not be -0
3633           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3634                          !Zero->isNegative();
3635           break;
3636         case ISD::SETOLT:
3637         case ISD::SETULT:
3638         case ISD::SETLT:
3639           // RHS must not be +0
3640           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3641                           Zero->isNegative();
3642           break;
3643         case ISD::SETOLE:
3644         case ISD::SETULE:
3645         case ISD::SETLE:
3646           // LHS must not be +0
3647           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3648                           Zero->isNegative();
3649           break;
3650         }
3651       }
3652       if (canTransform) {
3653         // Note: If one of the elements in a pair is a number and the other
3654         // element is NaN, the corresponding result element is the number.
3655         // This is consistent with the IEEE 754-2008 standard.
3656         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3657         switch (CC) {
3658         default:
3659           break;
3660         case ISD::SETOGT:
3661         case ISD::SETOGE:
3662           if (!DAG.isKnownNeverNaN(RHS))
3663             break;
3664           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3665         case ISD::SETUGT:
3666         case ISD::SETUGE:
3667           if (!DAG.isKnownNeverNaN(LHS))
3668             break;
3669         case ISD::SETGT:
3670         case ISD::SETGE:
3671           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3672         case ISD::SETOLT:
3673         case ISD::SETOLE:
3674           if (!DAG.isKnownNeverNaN(RHS))
3675             break;
3676           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3677         case ISD::SETULT:
3678         case ISD::SETULE:
3679           if (!DAG.isKnownNeverNaN(LHS))
3680             break;
3681         case ISD::SETLT:
3682         case ISD::SETLE:
3683           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3684         }
3685       }
3686     }
3687
3688     bool swpCmpOps = false;
3689     bool swpVselOps = false;
3690     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3691
3692     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3693         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3694       if (swpCmpOps)
3695         std::swap(LHS, RHS);
3696       if (swpVselOps)
3697         std::swap(TrueVal, FalseVal);
3698     }
3699   }
3700
3701   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3702   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3703   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3704   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3705   if (CondCode2 != ARMCC::AL) {
3706     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3707     // FIXME: Needs another CMP because flag can have but one use.
3708     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3709     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3710   }
3711   return Result;
3712 }
3713
3714 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3715 /// to morph to an integer compare sequence.
3716 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3717                            const ARMSubtarget *Subtarget) {
3718   SDNode *N = Op.getNode();
3719   if (!N->hasOneUse())
3720     // Otherwise it requires moving the value from fp to integer registers.
3721     return false;
3722   if (!N->getNumValues())
3723     return false;
3724   EVT VT = Op.getValueType();
3725   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3726     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3727     // vmrs are very slow, e.g. cortex-a8.
3728     return false;
3729
3730   if (isFloatingPointZero(Op)) {
3731     SeenZero = true;
3732     return true;
3733   }
3734   return ISD::isNormalLoad(N);
3735 }
3736
3737 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3738   if (isFloatingPointZero(Op))
3739     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3740
3741   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3742     return DAG.getLoad(MVT::i32, SDLoc(Op),
3743                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3744                        Ld->isVolatile(), Ld->isNonTemporal(),
3745                        Ld->isInvariant(), Ld->getAlignment());
3746
3747   llvm_unreachable("Unknown VFP cmp argument!");
3748 }
3749
3750 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3751                            SDValue &RetVal1, SDValue &RetVal2) {
3752   SDLoc dl(Op);
3753
3754   if (isFloatingPointZero(Op)) {
3755     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3756     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3757     return;
3758   }
3759
3760   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3761     SDValue Ptr = Ld->getBasePtr();
3762     RetVal1 = DAG.getLoad(MVT::i32, dl,
3763                           Ld->getChain(), Ptr,
3764                           Ld->getPointerInfo(),
3765                           Ld->isVolatile(), Ld->isNonTemporal(),
3766                           Ld->isInvariant(), Ld->getAlignment());
3767
3768     EVT PtrType = Ptr.getValueType();
3769     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3770     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3771                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3772     RetVal2 = DAG.getLoad(MVT::i32, dl,
3773                           Ld->getChain(), NewPtr,
3774                           Ld->getPointerInfo().getWithOffset(4),
3775                           Ld->isVolatile(), Ld->isNonTemporal(),
3776                           Ld->isInvariant(), NewAlign);
3777     return;
3778   }
3779
3780   llvm_unreachable("Unknown VFP cmp argument!");
3781 }
3782
3783 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3784 /// f32 and even f64 comparisons to integer ones.
3785 SDValue
3786 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3787   SDValue Chain = Op.getOperand(0);
3788   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3789   SDValue LHS = Op.getOperand(2);
3790   SDValue RHS = Op.getOperand(3);
3791   SDValue Dest = Op.getOperand(4);
3792   SDLoc dl(Op);
3793
3794   bool LHSSeenZero = false;
3795   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3796   bool RHSSeenZero = false;
3797   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3798   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3799     // If unsafe fp math optimization is enabled and there are no other uses of
3800     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3801     // to an integer comparison.
3802     if (CC == ISD::SETOEQ)
3803       CC = ISD::SETEQ;
3804     else if (CC == ISD::SETUNE)
3805       CC = ISD::SETNE;
3806
3807     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3808     SDValue ARMcc;
3809     if (LHS.getValueType() == MVT::f32) {
3810       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3811                         bitcastf32Toi32(LHS, DAG), Mask);
3812       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3813                         bitcastf32Toi32(RHS, DAG), Mask);
3814       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3815       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3816       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3817                          Chain, Dest, ARMcc, CCR, Cmp);
3818     }
3819
3820     SDValue LHS1, LHS2;
3821     SDValue RHS1, RHS2;
3822     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3823     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3824     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3825     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3826     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3827     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3828     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3829     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3830     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3831   }
3832
3833   return SDValue();
3834 }
3835
3836 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3837   SDValue Chain = Op.getOperand(0);
3838   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3839   SDValue LHS = Op.getOperand(2);
3840   SDValue RHS = Op.getOperand(3);
3841   SDValue Dest = Op.getOperand(4);
3842   SDLoc dl(Op);
3843
3844   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3845     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3846                                                     dl);
3847
3848     // If softenSetCCOperands only returned one value, we should compare it to
3849     // zero.
3850     if (!RHS.getNode()) {
3851       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3852       CC = ISD::SETNE;
3853     }
3854   }
3855
3856   if (LHS.getValueType() == MVT::i32) {
3857     SDValue ARMcc;
3858     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3859     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3860     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3861                        Chain, Dest, ARMcc, CCR, Cmp);
3862   }
3863
3864   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3865
3866   if (getTargetMachine().Options.UnsafeFPMath &&
3867       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3868        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3869     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3870     if (Result.getNode())
3871       return Result;
3872   }
3873
3874   ARMCC::CondCodes CondCode, CondCode2;
3875   FPCCToARMCC(CC, CondCode, CondCode2);
3876
3877   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3878   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3879   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3880   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3881   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3882   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3883   if (CondCode2 != ARMCC::AL) {
3884     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3885     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3886     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3887   }
3888   return Res;
3889 }
3890
3891 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3892   SDValue Chain = Op.getOperand(0);
3893   SDValue Table = Op.getOperand(1);
3894   SDValue Index = Op.getOperand(2);
3895   SDLoc dl(Op);
3896
3897   EVT PTy = getPointerTy(DAG.getDataLayout());
3898   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3899   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3900   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3901   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3902   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3903   if (Subtarget->isThumb2()) {
3904     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3905     // which does another jump to the destination. This also makes it easier
3906     // to translate it to TBB / TBH later.
3907     // FIXME: This might not work if the function is extremely large.
3908     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3909                        Addr, Op.getOperand(2), JTI);
3910   }
3911   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3912     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3913                        MachinePointerInfo::getJumpTable(),
3914                        false, false, false, 0);
3915     Chain = Addr.getValue(1);
3916     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3917     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3918   } else {
3919     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3920                        MachinePointerInfo::getJumpTable(),
3921                        false, false, false, 0);
3922     Chain = Addr.getValue(1);
3923     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3924   }
3925 }
3926
3927 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3928   EVT VT = Op.getValueType();
3929   SDLoc dl(Op);
3930
3931   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3932     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3933       return Op;
3934     return DAG.UnrollVectorOp(Op.getNode());
3935   }
3936
3937   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3938          "Invalid type for custom lowering!");
3939   if (VT != MVT::v4i16)
3940     return DAG.UnrollVectorOp(Op.getNode());
3941
3942   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3943   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3944 }
3945
3946 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3947   EVT VT = Op.getValueType();
3948   if (VT.isVector())
3949     return LowerVectorFP_TO_INT(Op, DAG);
3950   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3951     RTLIB::Libcall LC;
3952     if (Op.getOpcode() == ISD::FP_TO_SINT)
3953       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3954                               Op.getValueType());
3955     else
3956       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3957                               Op.getValueType());
3958     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3959                        /*isSigned*/ false, SDLoc(Op)).first;
3960   }
3961
3962   return Op;
3963 }
3964
3965 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3966   EVT VT = Op.getValueType();
3967   SDLoc dl(Op);
3968
3969   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3970     if (VT.getVectorElementType() == MVT::f32)
3971       return Op;
3972     return DAG.UnrollVectorOp(Op.getNode());
3973   }
3974
3975   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3976          "Invalid type for custom lowering!");
3977   if (VT != MVT::v4f32)
3978     return DAG.UnrollVectorOp(Op.getNode());
3979
3980   unsigned CastOpc;
3981   unsigned Opc;
3982   switch (Op.getOpcode()) {
3983   default: llvm_unreachable("Invalid opcode!");
3984   case ISD::SINT_TO_FP:
3985     CastOpc = ISD::SIGN_EXTEND;
3986     Opc = ISD::SINT_TO_FP;
3987     break;
3988   case ISD::UINT_TO_FP:
3989     CastOpc = ISD::ZERO_EXTEND;
3990     Opc = ISD::UINT_TO_FP;
3991     break;
3992   }
3993
3994   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3995   return DAG.getNode(Opc, dl, VT, Op);
3996 }
3997
3998 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3999   EVT VT = Op.getValueType();
4000   if (VT.isVector())
4001     return LowerVectorINT_TO_FP(Op, DAG);
4002   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4003     RTLIB::Libcall LC;
4004     if (Op.getOpcode() == ISD::SINT_TO_FP)
4005       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4006                               Op.getValueType());
4007     else
4008       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4009                               Op.getValueType());
4010     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4011                        /*isSigned*/ false, SDLoc(Op)).first;
4012   }
4013
4014   return Op;
4015 }
4016
4017 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4018   // Implement fcopysign with a fabs and a conditional fneg.
4019   SDValue Tmp0 = Op.getOperand(0);
4020   SDValue Tmp1 = Op.getOperand(1);
4021   SDLoc dl(Op);
4022   EVT VT = Op.getValueType();
4023   EVT SrcVT = Tmp1.getValueType();
4024   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4025     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4026   bool UseNEON = !InGPR && Subtarget->hasNEON();
4027
4028   if (UseNEON) {
4029     // Use VBSL to copy the sign bit.
4030     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4031     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4032                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4033     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4034     if (VT == MVT::f64)
4035       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4036                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4037                          DAG.getConstant(32, dl, MVT::i32));
4038     else /*if (VT == MVT::f32)*/
4039       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4040     if (SrcVT == MVT::f32) {
4041       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4042       if (VT == MVT::f64)
4043         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4044                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4045                            DAG.getConstant(32, dl, MVT::i32));
4046     } else if (VT == MVT::f32)
4047       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4048                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4049                          DAG.getConstant(32, dl, MVT::i32));
4050     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4051     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4052
4053     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4054                                             dl, MVT::i32);
4055     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4056     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4057                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4058
4059     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4060                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4061                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4062     if (VT == MVT::f32) {
4063       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4064       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4065                         DAG.getConstant(0, dl, MVT::i32));
4066     } else {
4067       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4068     }
4069
4070     return Res;
4071   }
4072
4073   // Bitcast operand 1 to i32.
4074   if (SrcVT == MVT::f64)
4075     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4076                        Tmp1).getValue(1);
4077   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4078
4079   // Or in the signbit with integer operations.
4080   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4081   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4082   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4083   if (VT == MVT::f32) {
4084     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4085                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4086     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4087                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4088   }
4089
4090   // f64: Or the high part with signbit and then combine two parts.
4091   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4092                      Tmp0);
4093   SDValue Lo = Tmp0.getValue(0);
4094   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4095   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4096   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4097 }
4098
4099 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4100   MachineFunction &MF = DAG.getMachineFunction();
4101   MachineFrameInfo *MFI = MF.getFrameInfo();
4102   MFI->setReturnAddressIsTaken(true);
4103
4104   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4105     return SDValue();
4106
4107   EVT VT = Op.getValueType();
4108   SDLoc dl(Op);
4109   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4110   if (Depth) {
4111     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4112     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4113     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4114                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4115                        MachinePointerInfo(), false, false, false, 0);
4116   }
4117
4118   // Return LR, which contains the return address. Mark it an implicit live-in.
4119   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4120   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4121 }
4122
4123 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4124   const ARMBaseRegisterInfo &ARI =
4125     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4126   MachineFunction &MF = DAG.getMachineFunction();
4127   MachineFrameInfo *MFI = MF.getFrameInfo();
4128   MFI->setFrameAddressIsTaken(true);
4129
4130   EVT VT = Op.getValueType();
4131   SDLoc dl(Op);  // FIXME probably not meaningful
4132   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4133   unsigned FrameReg = ARI.getFrameRegister(MF);
4134   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4135   while (Depth--)
4136     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4137                             MachinePointerInfo(),
4138                             false, false, false, 0);
4139   return FrameAddr;
4140 }
4141
4142 // FIXME? Maybe this could be a TableGen attribute on some registers and
4143 // this table could be generated automatically from RegInfo.
4144 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4145                                               SelectionDAG &DAG) const {
4146   unsigned Reg = StringSwitch<unsigned>(RegName)
4147                        .Case("sp", ARM::SP)
4148                        .Default(0);
4149   if (Reg)
4150     return Reg;
4151   report_fatal_error(Twine("Invalid register name \""
4152                               + StringRef(RegName)  + "\"."));
4153 }
4154
4155 // Result is 64 bit value so split into two 32 bit values and return as a
4156 // pair of values.
4157 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4158                                 SelectionDAG &DAG) {
4159   SDLoc DL(N);
4160
4161   // This function is only supposed to be called for i64 type destination.
4162   assert(N->getValueType(0) == MVT::i64
4163           && "ExpandREAD_REGISTER called for non-i64 type result.");
4164
4165   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4166                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4167                              N->getOperand(0),
4168                              N->getOperand(1));
4169
4170   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4171                     Read.getValue(1)));
4172   Results.push_back(Read.getOperand(0));
4173 }
4174
4175 /// ExpandBITCAST - If the target supports VFP, this function is called to
4176 /// expand a bit convert where either the source or destination type is i64 to
4177 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4178 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4179 /// vectors), since the legalizer won't know what to do with that.
4180 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4182   SDLoc dl(N);
4183   SDValue Op = N->getOperand(0);
4184
4185   // This function is only supposed to be called for i64 types, either as the
4186   // source or destination of the bit convert.
4187   EVT SrcVT = Op.getValueType();
4188   EVT DstVT = N->getValueType(0);
4189   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4190          "ExpandBITCAST called for non-i64 type");
4191
4192   // Turn i64->f64 into VMOVDRR.
4193   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4194     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4195                              DAG.getConstant(0, dl, MVT::i32));
4196     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4197                              DAG.getConstant(1, dl, MVT::i32));
4198     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4199                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4200   }
4201
4202   // Turn f64->i64 into VMOVRRD.
4203   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4204     SDValue Cvt;
4205     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4206         SrcVT.getVectorNumElements() > 1)
4207       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4208                         DAG.getVTList(MVT::i32, MVT::i32),
4209                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4210     else
4211       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4212                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4213     // Merge the pieces into a single i64 value.
4214     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4215   }
4216
4217   return SDValue();
4218 }
4219
4220 /// getZeroVector - Returns a vector of specified type with all zero elements.
4221 /// Zero vectors are used to represent vector negation and in those cases
4222 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4223 /// not support i64 elements, so sometimes the zero vectors will need to be
4224 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4225 /// zero vector.
4226 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4227   assert(VT.isVector() && "Expected a vector type");
4228   // The canonical modified immediate encoding of a zero vector is....0!
4229   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4230   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4231   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4232   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4233 }
4234
4235 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4236 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4237 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4238                                                 SelectionDAG &DAG) const {
4239   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4240   EVT VT = Op.getValueType();
4241   unsigned VTBits = VT.getSizeInBits();
4242   SDLoc dl(Op);
4243   SDValue ShOpLo = Op.getOperand(0);
4244   SDValue ShOpHi = Op.getOperand(1);
4245   SDValue ShAmt  = Op.getOperand(2);
4246   SDValue ARMcc;
4247   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4248
4249   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4250
4251   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4252                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4253   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4254   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4255                                    DAG.getConstant(VTBits, dl, MVT::i32));
4256   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4257   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4258   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4259
4260   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4261   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4262                           ISD::SETGE, ARMcc, DAG, dl);
4263   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4264   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4265                            CCR, Cmp);
4266
4267   SDValue Ops[2] = { Lo, Hi };
4268   return DAG.getMergeValues(Ops, dl);
4269 }
4270
4271 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4272 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4273 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4274                                                SelectionDAG &DAG) const {
4275   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4276   EVT VT = Op.getValueType();
4277   unsigned VTBits = VT.getSizeInBits();
4278   SDLoc dl(Op);
4279   SDValue ShOpLo = Op.getOperand(0);
4280   SDValue ShOpHi = Op.getOperand(1);
4281   SDValue ShAmt  = Op.getOperand(2);
4282   SDValue ARMcc;
4283
4284   assert(Op.getOpcode() == ISD::SHL_PARTS);
4285   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4286                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4287   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4288   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4289                                    DAG.getConstant(VTBits, dl, MVT::i32));
4290   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4291   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4292
4293   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4294   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4295   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4296                           ISD::SETGE, ARMcc, DAG, dl);
4297   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4298   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4299                            CCR, Cmp);
4300
4301   SDValue Ops[2] = { Lo, Hi };
4302   return DAG.getMergeValues(Ops, dl);
4303 }
4304
4305 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4306                                             SelectionDAG &DAG) const {
4307   // The rounding mode is in bits 23:22 of the FPSCR.
4308   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4309   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4310   // so that the shift + and get folded into a bitfield extract.
4311   SDLoc dl(Op);
4312   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4313                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4314                                               MVT::i32));
4315   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4316                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4317   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4318                               DAG.getConstant(22, dl, MVT::i32));
4319   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4320                      DAG.getConstant(3, dl, MVT::i32));
4321 }
4322
4323 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4324                          const ARMSubtarget *ST) {
4325   SDLoc dl(N);
4326   EVT VT = N->getValueType(0);
4327   if (VT.isVector()) {
4328     assert(ST->hasNEON());
4329
4330     // Compute the least significant set bit: LSB = X & -X
4331     SDValue X = N->getOperand(0);
4332     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4333     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4334
4335     EVT ElemTy = VT.getVectorElementType();
4336
4337     if (ElemTy == MVT::i8) {
4338       // Compute with: cttz(x) = ctpop(lsb - 1)
4339       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4340                                 DAG.getTargetConstant(1, dl, ElemTy));
4341       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4342       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4343     }
4344
4345     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4346         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4347       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4348       unsigned NumBits = ElemTy.getSizeInBits();
4349       SDValue WidthMinus1 =
4350           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4351                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4352       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4353       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4354     }
4355
4356     // Compute with: cttz(x) = ctpop(lsb - 1)
4357
4358     // Since we can only compute the number of bits in a byte with vcnt.8, we
4359     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4360     // and i64.
4361
4362     // Compute LSB - 1.
4363     SDValue Bits;
4364     if (ElemTy == MVT::i64) {
4365       // Load constant 0xffff'ffff'ffff'ffff to register.
4366       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4367                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4368       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4369     } else {
4370       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4371                                 DAG.getTargetConstant(1, dl, ElemTy));
4372       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4373     }
4374
4375     // Count #bits with vcnt.8.
4376     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4377     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4378     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4379
4380     // Gather the #bits with vpaddl (pairwise add.)
4381     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4382     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4383         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4384         Cnt8);
4385     if (ElemTy == MVT::i16)
4386       return Cnt16;
4387
4388     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4389     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4390         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4391         Cnt16);
4392     if (ElemTy == MVT::i32)
4393       return Cnt32;
4394
4395     assert(ElemTy == MVT::i64);
4396     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4397         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4398         Cnt32);
4399     return Cnt64;
4400   }
4401
4402   if (!ST->hasV6T2Ops())
4403     return SDValue();
4404
4405   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4406   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4407 }
4408
4409 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4410 /// for each 16-bit element from operand, repeated.  The basic idea is to
4411 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4412 ///
4413 /// Trace for v4i16:
4414 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4415 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4416 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4417 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4418 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4419 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4420 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4421 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4422 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4423   EVT VT = N->getValueType(0);
4424   SDLoc DL(N);
4425
4426   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4427   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4428   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4429   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4430   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4431   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4432 }
4433
4434 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4435 /// bit-count for each 16-bit element from the operand.  We need slightly
4436 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4437 /// 64/128-bit registers.
4438 ///
4439 /// Trace for v4i16:
4440 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4441 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4442 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4443 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4444 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4445   EVT VT = N->getValueType(0);
4446   SDLoc DL(N);
4447
4448   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4449   if (VT.is64BitVector()) {
4450     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4451     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4452                        DAG.getIntPtrConstant(0, DL));
4453   } else {
4454     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4455                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4456     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4457   }
4458 }
4459
4460 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4461 /// bit-count for each 32-bit element from the operand.  The idea here is
4462 /// to split the vector into 16-bit elements, leverage the 16-bit count
4463 /// routine, and then combine the results.
4464 ///
4465 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4466 /// input    = [v0    v1    ] (vi: 32-bit elements)
4467 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4468 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4469 /// vrev: N0 = [k1 k0 k3 k2 ]
4470 ///            [k0 k1 k2 k3 ]
4471 ///       N1 =+[k1 k0 k3 k2 ]
4472 ///            [k0 k2 k1 k3 ]
4473 ///       N2 =+[k1 k3 k0 k2 ]
4474 ///            [k0    k2    k1    k3    ]
4475 /// Extended =+[k1    k3    k0    k2    ]
4476 ///            [k0    k2    ]
4477 /// Extracted=+[k1    k3    ]
4478 ///
4479 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4480   EVT VT = N->getValueType(0);
4481   SDLoc DL(N);
4482
4483   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4484
4485   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4486   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4487   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4488   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4489   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4490
4491   if (VT.is64BitVector()) {
4492     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4493     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4494                        DAG.getIntPtrConstant(0, DL));
4495   } else {
4496     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4497                                     DAG.getIntPtrConstant(0, DL));
4498     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4499   }
4500 }
4501
4502 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4503                           const ARMSubtarget *ST) {
4504   EVT VT = N->getValueType(0);
4505
4506   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4507   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4508           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4509          "Unexpected type for custom ctpop lowering");
4510
4511   if (VT.getVectorElementType() == MVT::i32)
4512     return lowerCTPOP32BitElements(N, DAG);
4513   else
4514     return lowerCTPOP16BitElements(N, DAG);
4515 }
4516
4517 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4518                           const ARMSubtarget *ST) {
4519   EVT VT = N->getValueType(0);
4520   SDLoc dl(N);
4521
4522   if (!VT.isVector())
4523     return SDValue();
4524
4525   // Lower vector shifts on NEON to use VSHL.
4526   assert(ST->hasNEON() && "unexpected vector shift");
4527
4528   // Left shifts translate directly to the vshiftu intrinsic.
4529   if (N->getOpcode() == ISD::SHL)
4530     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4531                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4532                                        MVT::i32),
4533                        N->getOperand(0), N->getOperand(1));
4534
4535   assert((N->getOpcode() == ISD::SRA ||
4536           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4537
4538   // NEON uses the same intrinsics for both left and right shifts.  For
4539   // right shifts, the shift amounts are negative, so negate the vector of
4540   // shift amounts.
4541   EVT ShiftVT = N->getOperand(1).getValueType();
4542   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4543                                      getZeroVector(ShiftVT, DAG, dl),
4544                                      N->getOperand(1));
4545   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4546                              Intrinsic::arm_neon_vshifts :
4547                              Intrinsic::arm_neon_vshiftu);
4548   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4549                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4550                      N->getOperand(0), NegatedCount);
4551 }
4552
4553 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4554                                 const ARMSubtarget *ST) {
4555   EVT VT = N->getValueType(0);
4556   SDLoc dl(N);
4557
4558   // We can get here for a node like i32 = ISD::SHL i32, i64
4559   if (VT != MVT::i64)
4560     return SDValue();
4561
4562   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4563          "Unknown shift to lower!");
4564
4565   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4566   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4567       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4568     return SDValue();
4569
4570   // If we are in thumb mode, we don't have RRX.
4571   if (ST->isThumb1Only()) return SDValue();
4572
4573   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4574   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4575                            DAG.getConstant(0, dl, MVT::i32));
4576   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4577                            DAG.getConstant(1, dl, MVT::i32));
4578
4579   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4580   // captures the result into a carry flag.
4581   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4582   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4583
4584   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4585   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4586
4587   // Merge the pieces into a single i64 value.
4588  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4589 }
4590
4591 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4592   SDValue TmpOp0, TmpOp1;
4593   bool Invert = false;
4594   bool Swap = false;
4595   unsigned Opc = 0;
4596
4597   SDValue Op0 = Op.getOperand(0);
4598   SDValue Op1 = Op.getOperand(1);
4599   SDValue CC = Op.getOperand(2);
4600   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4601   EVT VT = Op.getValueType();
4602   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4603   SDLoc dl(Op);
4604
4605   if (Op1.getValueType().isFloatingPoint()) {
4606     switch (SetCCOpcode) {
4607     default: llvm_unreachable("Illegal FP comparison");
4608     case ISD::SETUNE:
4609     case ISD::SETNE:  Invert = true; // Fallthrough
4610     case ISD::SETOEQ:
4611     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4612     case ISD::SETOLT:
4613     case ISD::SETLT: Swap = true; // Fallthrough
4614     case ISD::SETOGT:
4615     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4616     case ISD::SETOLE:
4617     case ISD::SETLE:  Swap = true; // Fallthrough
4618     case ISD::SETOGE:
4619     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4620     case ISD::SETUGE: Swap = true; // Fallthrough
4621     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4622     case ISD::SETUGT: Swap = true; // Fallthrough
4623     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4624     case ISD::SETUEQ: Invert = true; // Fallthrough
4625     case ISD::SETONE:
4626       // Expand this to (OLT | OGT).
4627       TmpOp0 = Op0;
4628       TmpOp1 = Op1;
4629       Opc = ISD::OR;
4630       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4631       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4632       break;
4633     case ISD::SETUO: Invert = true; // Fallthrough
4634     case ISD::SETO:
4635       // Expand this to (OLT | OGE).
4636       TmpOp0 = Op0;
4637       TmpOp1 = Op1;
4638       Opc = ISD::OR;
4639       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4640       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4641       break;
4642     }
4643   } else {
4644     // Integer comparisons.
4645     switch (SetCCOpcode) {
4646     default: llvm_unreachable("Illegal integer comparison");
4647     case ISD::SETNE:  Invert = true;
4648     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4649     case ISD::SETLT:  Swap = true;
4650     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4651     case ISD::SETLE:  Swap = true;
4652     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4653     case ISD::SETULT: Swap = true;
4654     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4655     case ISD::SETULE: Swap = true;
4656     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4657     }
4658
4659     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4660     if (Opc == ARMISD::VCEQ) {
4661
4662       SDValue AndOp;
4663       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4664         AndOp = Op0;
4665       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4666         AndOp = Op1;
4667
4668       // Ignore bitconvert.
4669       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4670         AndOp = AndOp.getOperand(0);
4671
4672       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4673         Opc = ARMISD::VTST;
4674         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4675         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4676         Invert = !Invert;
4677       }
4678     }
4679   }
4680
4681   if (Swap)
4682     std::swap(Op0, Op1);
4683
4684   // If one of the operands is a constant vector zero, attempt to fold the
4685   // comparison to a specialized compare-against-zero form.
4686   SDValue SingleOp;
4687   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4688     SingleOp = Op0;
4689   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4690     if (Opc == ARMISD::VCGE)
4691       Opc = ARMISD::VCLEZ;
4692     else if (Opc == ARMISD::VCGT)
4693       Opc = ARMISD::VCLTZ;
4694     SingleOp = Op1;
4695   }
4696
4697   SDValue Result;
4698   if (SingleOp.getNode()) {
4699     switch (Opc) {
4700     case ARMISD::VCEQ:
4701       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4702     case ARMISD::VCGE:
4703       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4704     case ARMISD::VCLEZ:
4705       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4706     case ARMISD::VCGT:
4707       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4708     case ARMISD::VCLTZ:
4709       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4710     default:
4711       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4712     }
4713   } else {
4714      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4715   }
4716
4717   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4718
4719   if (Invert)
4720     Result = DAG.getNOT(dl, Result, VT);
4721
4722   return Result;
4723 }
4724
4725 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4726 /// valid vector constant for a NEON instruction with a "modified immediate"
4727 /// operand (e.g., VMOV).  If so, return the encoded value.
4728 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4729                                  unsigned SplatBitSize, SelectionDAG &DAG,
4730                                  SDLoc dl, EVT &VT, bool is128Bits,
4731                                  NEONModImmType type) {
4732   unsigned OpCmode, Imm;
4733
4734   // SplatBitSize is set to the smallest size that splats the vector, so a
4735   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4736   // immediate instructions others than VMOV do not support the 8-bit encoding
4737   // of a zero vector, and the default encoding of zero is supposed to be the
4738   // 32-bit version.
4739   if (SplatBits == 0)
4740     SplatBitSize = 32;
4741
4742   switch (SplatBitSize) {
4743   case 8:
4744     if (type != VMOVModImm)
4745       return SDValue();
4746     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4747     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4748     OpCmode = 0xe;
4749     Imm = SplatBits;
4750     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4751     break;
4752
4753   case 16:
4754     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4755     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4756     if ((SplatBits & ~0xff) == 0) {
4757       // Value = 0x00nn: Op=x, Cmode=100x.
4758       OpCmode = 0x8;
4759       Imm = SplatBits;
4760       break;
4761     }
4762     if ((SplatBits & ~0xff00) == 0) {
4763       // Value = 0xnn00: Op=x, Cmode=101x.
4764       OpCmode = 0xa;
4765       Imm = SplatBits >> 8;
4766       break;
4767     }
4768     return SDValue();
4769
4770   case 32:
4771     // NEON's 32-bit VMOV supports splat values where:
4772     // * only one byte is nonzero, or
4773     // * the least significant byte is 0xff and the second byte is nonzero, or
4774     // * the least significant 2 bytes are 0xff and the third is nonzero.
4775     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4776     if ((SplatBits & ~0xff) == 0) {
4777       // Value = 0x000000nn: Op=x, Cmode=000x.
4778       OpCmode = 0;
4779       Imm = SplatBits;
4780       break;
4781     }
4782     if ((SplatBits & ~0xff00) == 0) {
4783       // Value = 0x0000nn00: Op=x, Cmode=001x.
4784       OpCmode = 0x2;
4785       Imm = SplatBits >> 8;
4786       break;
4787     }
4788     if ((SplatBits & ~0xff0000) == 0) {
4789       // Value = 0x00nn0000: Op=x, Cmode=010x.
4790       OpCmode = 0x4;
4791       Imm = SplatBits >> 16;
4792       break;
4793     }
4794     if ((SplatBits & ~0xff000000) == 0) {
4795       // Value = 0xnn000000: Op=x, Cmode=011x.
4796       OpCmode = 0x6;
4797       Imm = SplatBits >> 24;
4798       break;
4799     }
4800
4801     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4802     if (type == OtherModImm) return SDValue();
4803
4804     if ((SplatBits & ~0xffff) == 0 &&
4805         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4806       // Value = 0x0000nnff: Op=x, Cmode=1100.
4807       OpCmode = 0xc;
4808       Imm = SplatBits >> 8;
4809       break;
4810     }
4811
4812     if ((SplatBits & ~0xffffff) == 0 &&
4813         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4814       // Value = 0x00nnffff: Op=x, Cmode=1101.
4815       OpCmode = 0xd;
4816       Imm = SplatBits >> 16;
4817       break;
4818     }
4819
4820     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4821     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4822     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4823     // and fall through here to test for a valid 64-bit splat.  But, then the
4824     // caller would also need to check and handle the change in size.
4825     return SDValue();
4826
4827   case 64: {
4828     if (type != VMOVModImm)
4829       return SDValue();
4830     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4831     uint64_t BitMask = 0xff;
4832     uint64_t Val = 0;
4833     unsigned ImmMask = 1;
4834     Imm = 0;
4835     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4836       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4837         Val |= BitMask;
4838         Imm |= ImmMask;
4839       } else if ((SplatBits & BitMask) != 0) {
4840         return SDValue();
4841       }
4842       BitMask <<= 8;
4843       ImmMask <<= 1;
4844     }
4845
4846     if (DAG.getDataLayout().isBigEndian())
4847       // swap higher and lower 32 bit word
4848       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4849
4850     // Op=1, Cmode=1110.
4851     OpCmode = 0x1e;
4852     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4853     break;
4854   }
4855
4856   default:
4857     llvm_unreachable("unexpected size for isNEONModifiedImm");
4858   }
4859
4860   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4861   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4862 }
4863
4864 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4865                                            const ARMSubtarget *ST) const {
4866   if (!ST->hasVFP3())
4867     return SDValue();
4868
4869   bool IsDouble = Op.getValueType() == MVT::f64;
4870   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4871
4872   // Use the default (constant pool) lowering for double constants when we have
4873   // an SP-only FPU
4874   if (IsDouble && Subtarget->isFPOnlySP())
4875     return SDValue();
4876
4877   // Try splatting with a VMOV.f32...
4878   APFloat FPVal = CFP->getValueAPF();
4879   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4880
4881   if (ImmVal != -1) {
4882     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4883       // We have code in place to select a valid ConstantFP already, no need to
4884       // do any mangling.
4885       return Op;
4886     }
4887
4888     // It's a float and we are trying to use NEON operations where
4889     // possible. Lower it to a splat followed by an extract.
4890     SDLoc DL(Op);
4891     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4892     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4893                                       NewVal);
4894     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4895                        DAG.getConstant(0, DL, MVT::i32));
4896   }
4897
4898   // The rest of our options are NEON only, make sure that's allowed before
4899   // proceeding..
4900   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4901     return SDValue();
4902
4903   EVT VMovVT;
4904   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4905
4906   // It wouldn't really be worth bothering for doubles except for one very
4907   // important value, which does happen to match: 0.0. So make sure we don't do
4908   // anything stupid.
4909   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4910     return SDValue();
4911
4912   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4913   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4914                                      VMovVT, false, VMOVModImm);
4915   if (NewVal != SDValue()) {
4916     SDLoc DL(Op);
4917     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4918                                       NewVal);
4919     if (IsDouble)
4920       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4921
4922     // It's a float: cast and extract a vector element.
4923     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4924                                        VecConstant);
4925     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4926                        DAG.getConstant(0, DL, MVT::i32));
4927   }
4928
4929   // Finally, try a VMVN.i32
4930   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4931                              false, VMVNModImm);
4932   if (NewVal != SDValue()) {
4933     SDLoc DL(Op);
4934     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4935
4936     if (IsDouble)
4937       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4938
4939     // It's a float: cast and extract a vector element.
4940     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4941                                        VecConstant);
4942     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4943                        DAG.getConstant(0, DL, MVT::i32));
4944   }
4945
4946   return SDValue();
4947 }
4948
4949 // check if an VEXT instruction can handle the shuffle mask when the
4950 // vector sources of the shuffle are the same.
4951 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4952   unsigned NumElts = VT.getVectorNumElements();
4953
4954   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4955   if (M[0] < 0)
4956     return false;
4957
4958   Imm = M[0];
4959
4960   // If this is a VEXT shuffle, the immediate value is the index of the first
4961   // element.  The other shuffle indices must be the successive elements after
4962   // the first one.
4963   unsigned ExpectedElt = Imm;
4964   for (unsigned i = 1; i < NumElts; ++i) {
4965     // Increment the expected index.  If it wraps around, just follow it
4966     // back to index zero and keep going.
4967     ++ExpectedElt;
4968     if (ExpectedElt == NumElts)
4969       ExpectedElt = 0;
4970
4971     if (M[i] < 0) continue; // ignore UNDEF indices
4972     if (ExpectedElt != static_cast<unsigned>(M[i]))
4973       return false;
4974   }
4975
4976   return true;
4977 }
4978
4979
4980 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4981                        bool &ReverseVEXT, unsigned &Imm) {
4982   unsigned NumElts = VT.getVectorNumElements();
4983   ReverseVEXT = false;
4984
4985   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4986   if (M[0] < 0)
4987     return false;
4988
4989   Imm = M[0];
4990
4991   // If this is a VEXT shuffle, the immediate value is the index of the first
4992   // element.  The other shuffle indices must be the successive elements after
4993   // the first one.
4994   unsigned ExpectedElt = Imm;
4995   for (unsigned i = 1; i < NumElts; ++i) {
4996     // Increment the expected index.  If it wraps around, it may still be
4997     // a VEXT but the source vectors must be swapped.
4998     ExpectedElt += 1;
4999     if (ExpectedElt == NumElts * 2) {
5000       ExpectedElt = 0;
5001       ReverseVEXT = true;
5002     }
5003
5004     if (M[i] < 0) continue; // ignore UNDEF indices
5005     if (ExpectedElt != static_cast<unsigned>(M[i]))
5006       return false;
5007   }
5008
5009   // Adjust the index value if the source operands will be swapped.
5010   if (ReverseVEXT)
5011     Imm -= NumElts;
5012
5013   return true;
5014 }
5015
5016 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5017 /// instruction with the specified blocksize.  (The order of the elements
5018 /// within each block of the vector is reversed.)
5019 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5020   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5021          "Only possible block sizes for VREV are: 16, 32, 64");
5022
5023   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5024   if (EltSz == 64)
5025     return false;
5026
5027   unsigned NumElts = VT.getVectorNumElements();
5028   unsigned BlockElts = M[0] + 1;
5029   // If the first shuffle index is UNDEF, be optimistic.
5030   if (M[0] < 0)
5031     BlockElts = BlockSize / EltSz;
5032
5033   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5034     return false;
5035
5036   for (unsigned i = 0; i < NumElts; ++i) {
5037     if (M[i] < 0) continue; // ignore UNDEF indices
5038     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5039       return false;
5040   }
5041
5042   return true;
5043 }
5044
5045 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5046   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5047   // range, then 0 is placed into the resulting vector. So pretty much any mask
5048   // of 8 elements can work here.
5049   return VT == MVT::v8i8 && M.size() == 8;
5050 }
5051
5052 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5053 // checking that pairs of elements in the shuffle mask represent the same index
5054 // in each vector, incrementing the expected index by 2 at each step.
5055 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5056 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5057 //  v2={e,f,g,h}
5058 // WhichResult gives the offset for each element in the mask based on which
5059 // of the two results it belongs to.
5060 //
5061 // The transpose can be represented either as:
5062 // result1 = shufflevector v1, v2, result1_shuffle_mask
5063 // result2 = shufflevector v1, v2, result2_shuffle_mask
5064 // where v1/v2 and the shuffle masks have the same number of elements
5065 // (here WhichResult (see below) indicates which result is being checked)
5066 //
5067 // or as:
5068 // results = shufflevector v1, v2, shuffle_mask
5069 // where both results are returned in one vector and the shuffle mask has twice
5070 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5071 // want to check the low half and high half of the shuffle mask as if it were
5072 // the other case
5073 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5074   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5075   if (EltSz == 64)
5076     return false;
5077
5078   unsigned NumElts = VT.getVectorNumElements();
5079   if (M.size() != NumElts && M.size() != NumElts*2)
5080     return false;
5081
5082   // If the mask is twice as long as the result then we need to check the upper
5083   // and lower parts of the mask
5084   for (unsigned i = 0; i < M.size(); i += NumElts) {
5085     WhichResult = M[i] == 0 ? 0 : 1;
5086     for (unsigned j = 0; j < NumElts; j += 2) {
5087       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5088           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5089         return false;
5090     }
5091   }
5092
5093   if (M.size() == NumElts*2)
5094     WhichResult = 0;
5095
5096   return true;
5097 }
5098
5099 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5100 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5101 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5102 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5103   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5104   if (EltSz == 64)
5105     return false;
5106
5107   unsigned NumElts = VT.getVectorNumElements();
5108   if (M.size() != NumElts && M.size() != NumElts*2)
5109     return false;
5110
5111   for (unsigned i = 0; i < M.size(); i += NumElts) {
5112     WhichResult = M[i] == 0 ? 0 : 1;
5113     for (unsigned j = 0; j < NumElts; j += 2) {
5114       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5115           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5116         return false;
5117     }
5118   }
5119
5120   if (M.size() == NumElts*2)
5121     WhichResult = 0;
5122
5123   return true;
5124 }
5125
5126 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5127 // that the mask elements are either all even and in steps of size 2 or all odd
5128 // and in steps of size 2.
5129 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5130 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5131 //  v2={e,f,g,h}
5132 // Requires similar checks to that of isVTRNMask with
5133 // respect the how results are returned.
5134 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5135   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5136   if (EltSz == 64)
5137     return false;
5138
5139   unsigned NumElts = VT.getVectorNumElements();
5140   if (M.size() != NumElts && M.size() != NumElts*2)
5141     return false;
5142
5143   for (unsigned i = 0; i < M.size(); i += NumElts) {
5144     WhichResult = M[i] == 0 ? 0 : 1;
5145     for (unsigned j = 0; j < NumElts; ++j) {
5146       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5147         return false;
5148     }
5149   }
5150
5151   if (M.size() == NumElts*2)
5152     WhichResult = 0;
5153
5154   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5155   if (VT.is64BitVector() && EltSz == 32)
5156     return false;
5157
5158   return true;
5159 }
5160
5161 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5162 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5163 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5164 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5165   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5166   if (EltSz == 64)
5167     return false;
5168
5169   unsigned NumElts = VT.getVectorNumElements();
5170   if (M.size() != NumElts && M.size() != NumElts*2)
5171     return false;
5172
5173   unsigned Half = NumElts / 2;
5174   for (unsigned i = 0; i < M.size(); i += NumElts) {
5175     WhichResult = M[i] == 0 ? 0 : 1;
5176     for (unsigned j = 0; j < NumElts; j += Half) {
5177       unsigned Idx = WhichResult;
5178       for (unsigned k = 0; k < Half; ++k) {
5179         int MIdx = M[i + j + k];
5180         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5181           return false;
5182         Idx += 2;
5183       }
5184     }
5185   }
5186
5187   if (M.size() == NumElts*2)
5188     WhichResult = 0;
5189
5190   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5191   if (VT.is64BitVector() && EltSz == 32)
5192     return false;
5193
5194   return true;
5195 }
5196
5197 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5198 // that pairs of elements of the shufflemask represent the same index in each
5199 // vector incrementing sequentially through the vectors.
5200 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5201 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5202 //  v2={e,f,g,h}
5203 // Requires similar checks to that of isVTRNMask with respect the how results
5204 // are returned.
5205 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5206   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5207   if (EltSz == 64)
5208     return false;
5209
5210   unsigned NumElts = VT.getVectorNumElements();
5211   if (M.size() != NumElts && M.size() != NumElts*2)
5212     return false;
5213
5214   for (unsigned i = 0; i < M.size(); i += NumElts) {
5215     WhichResult = M[i] == 0 ? 0 : 1;
5216     unsigned Idx = WhichResult * NumElts / 2;
5217     for (unsigned j = 0; j < NumElts; j += 2) {
5218       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5219           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5220         return false;
5221       Idx += 1;
5222     }
5223   }
5224
5225   if (M.size() == NumElts*2)
5226     WhichResult = 0;
5227
5228   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5229   if (VT.is64BitVector() && EltSz == 32)
5230     return false;
5231
5232   return true;
5233 }
5234
5235 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5236 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5237 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5238 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5239   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5240   if (EltSz == 64)
5241     return false;
5242
5243   unsigned NumElts = VT.getVectorNumElements();
5244   if (M.size() != NumElts && M.size() != NumElts*2)
5245     return false;
5246
5247   for (unsigned i = 0; i < M.size(); i += NumElts) {
5248     WhichResult = M[i] == 0 ? 0 : 1;
5249     unsigned Idx = WhichResult * NumElts / 2;
5250     for (unsigned j = 0; j < NumElts; j += 2) {
5251       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5252           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5253         return false;
5254       Idx += 1;
5255     }
5256   }
5257
5258   if (M.size() == NumElts*2)
5259     WhichResult = 0;
5260
5261   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5262   if (VT.is64BitVector() && EltSz == 32)
5263     return false;
5264
5265   return true;
5266 }
5267
5268 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5269 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5270 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5271                                            unsigned &WhichResult,
5272                                            bool &isV_UNDEF) {
5273   isV_UNDEF = false;
5274   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5275     return ARMISD::VTRN;
5276   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5277     return ARMISD::VUZP;
5278   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5279     return ARMISD::VZIP;
5280
5281   isV_UNDEF = true;
5282   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5283     return ARMISD::VTRN;
5284   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5285     return ARMISD::VUZP;
5286   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5287     return ARMISD::VZIP;
5288
5289   return 0;
5290 }
5291
5292 /// \return true if this is a reverse operation on an vector.
5293 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5294   unsigned NumElts = VT.getVectorNumElements();
5295   // Make sure the mask has the right size.
5296   if (NumElts != M.size())
5297       return false;
5298
5299   // Look for <15, ..., 3, -1, 1, 0>.
5300   for (unsigned i = 0; i != NumElts; ++i)
5301     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5302       return false;
5303
5304   return true;
5305 }
5306
5307 // If N is an integer constant that can be moved into a register in one
5308 // instruction, return an SDValue of such a constant (will become a MOV
5309 // instruction).  Otherwise return null.
5310 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5311                                      const ARMSubtarget *ST, SDLoc dl) {
5312   uint64_t Val;
5313   if (!isa<ConstantSDNode>(N))
5314     return SDValue();
5315   Val = cast<ConstantSDNode>(N)->getZExtValue();
5316
5317   if (ST->isThumb1Only()) {
5318     if (Val <= 255 || ~Val <= 255)
5319       return DAG.getConstant(Val, dl, MVT::i32);
5320   } else {
5321     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5322       return DAG.getConstant(Val, dl, MVT::i32);
5323   }
5324   return SDValue();
5325 }
5326
5327 // If this is a case we can't handle, return null and let the default
5328 // expansion code take care of it.
5329 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5330                                              const ARMSubtarget *ST) const {
5331   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5332   SDLoc dl(Op);
5333   EVT VT = Op.getValueType();
5334
5335   APInt SplatBits, SplatUndef;
5336   unsigned SplatBitSize;
5337   bool HasAnyUndefs;
5338   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5339     if (SplatBitSize <= 64) {
5340       // Check if an immediate VMOV works.
5341       EVT VmovVT;
5342       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5343                                       SplatUndef.getZExtValue(), SplatBitSize,
5344                                       DAG, dl, VmovVT, VT.is128BitVector(),
5345                                       VMOVModImm);
5346       if (Val.getNode()) {
5347         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5348         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5349       }
5350
5351       // Try an immediate VMVN.
5352       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5353       Val = isNEONModifiedImm(NegatedImm,
5354                                       SplatUndef.getZExtValue(), SplatBitSize,
5355                                       DAG, dl, VmovVT, VT.is128BitVector(),
5356                                       VMVNModImm);
5357       if (Val.getNode()) {
5358         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5359         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5360       }
5361
5362       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5363       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5364         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5365         if (ImmVal != -1) {
5366           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5367           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5368         }
5369       }
5370     }
5371   }
5372
5373   // Scan through the operands to see if only one value is used.
5374   //
5375   // As an optimisation, even if more than one value is used it may be more
5376   // profitable to splat with one value then change some lanes.
5377   //
5378   // Heuristically we decide to do this if the vector has a "dominant" value,
5379   // defined as splatted to more than half of the lanes.
5380   unsigned NumElts = VT.getVectorNumElements();
5381   bool isOnlyLowElement = true;
5382   bool usesOnlyOneValue = true;
5383   bool hasDominantValue = false;
5384   bool isConstant = true;
5385
5386   // Map of the number of times a particular SDValue appears in the
5387   // element list.
5388   DenseMap<SDValue, unsigned> ValueCounts;
5389   SDValue Value;
5390   for (unsigned i = 0; i < NumElts; ++i) {
5391     SDValue V = Op.getOperand(i);
5392     if (V.getOpcode() == ISD::UNDEF)
5393       continue;
5394     if (i > 0)
5395       isOnlyLowElement = false;
5396     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5397       isConstant = false;
5398
5399     ValueCounts.insert(std::make_pair(V, 0));
5400     unsigned &Count = ValueCounts[V];
5401
5402     // Is this value dominant? (takes up more than half of the lanes)
5403     if (++Count > (NumElts / 2)) {
5404       hasDominantValue = true;
5405       Value = V;
5406     }
5407   }
5408   if (ValueCounts.size() != 1)
5409     usesOnlyOneValue = false;
5410   if (!Value.getNode() && ValueCounts.size() > 0)
5411     Value = ValueCounts.begin()->first;
5412
5413   if (ValueCounts.size() == 0)
5414     return DAG.getUNDEF(VT);
5415
5416   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5417   // Keep going if we are hitting this case.
5418   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5419     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5420
5421   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5422
5423   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5424   // i32 and try again.
5425   if (hasDominantValue && EltSize <= 32) {
5426     if (!isConstant) {
5427       SDValue N;
5428
5429       // If we are VDUPing a value that comes directly from a vector, that will
5430       // cause an unnecessary move to and from a GPR, where instead we could
5431       // just use VDUPLANE. We can only do this if the lane being extracted
5432       // is at a constant index, as the VDUP from lane instructions only have
5433       // constant-index forms.
5434       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5435           isa<ConstantSDNode>(Value->getOperand(1))) {
5436         // We need to create a new undef vector to use for the VDUPLANE if the
5437         // size of the vector from which we get the value is different than the
5438         // size of the vector that we need to create. We will insert the element
5439         // such that the register coalescer will remove unnecessary copies.
5440         if (VT != Value->getOperand(0).getValueType()) {
5441           ConstantSDNode *constIndex;
5442           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5443           assert(constIndex && "The index is not a constant!");
5444           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5445                              VT.getVectorNumElements();
5446           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5447                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5448                         Value, DAG.getConstant(index, dl, MVT::i32)),
5449                            DAG.getConstant(index, dl, MVT::i32));
5450         } else
5451           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5452                         Value->getOperand(0), Value->getOperand(1));
5453       } else
5454         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5455
5456       if (!usesOnlyOneValue) {
5457         // The dominant value was splatted as 'N', but we now have to insert
5458         // all differing elements.
5459         for (unsigned I = 0; I < NumElts; ++I) {
5460           if (Op.getOperand(I) == Value)
5461             continue;
5462           SmallVector<SDValue, 3> Ops;
5463           Ops.push_back(N);
5464           Ops.push_back(Op.getOperand(I));
5465           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5466           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5467         }
5468       }
5469       return N;
5470     }
5471     if (VT.getVectorElementType().isFloatingPoint()) {
5472       SmallVector<SDValue, 8> Ops;
5473       for (unsigned i = 0; i < NumElts; ++i)
5474         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5475                                   Op.getOperand(i)));
5476       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5477       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5478       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5479       if (Val.getNode())
5480         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5481     }
5482     if (usesOnlyOneValue) {
5483       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5484       if (isConstant && Val.getNode())
5485         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5486     }
5487   }
5488
5489   // If all elements are constants and the case above didn't get hit, fall back
5490   // to the default expansion, which will generate a load from the constant
5491   // pool.
5492   if (isConstant)
5493     return SDValue();
5494
5495   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5496   if (NumElts >= 4) {
5497     SDValue shuffle = ReconstructShuffle(Op, DAG);
5498     if (shuffle != SDValue())
5499       return shuffle;
5500   }
5501
5502   // Vectors with 32- or 64-bit elements can be built by directly assigning
5503   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5504   // will be legalized.
5505   if (EltSize >= 32) {
5506     // Do the expansion with floating-point types, since that is what the VFP
5507     // registers are defined to use, and since i64 is not legal.
5508     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5509     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5510     SmallVector<SDValue, 8> Ops;
5511     for (unsigned i = 0; i < NumElts; ++i)
5512       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5513     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5514     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5515   }
5516
5517   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5518   // know the default expansion would otherwise fall back on something even
5519   // worse. For a vector with one or two non-undef values, that's
5520   // scalar_to_vector for the elements followed by a shuffle (provided the
5521   // shuffle is valid for the target) and materialization element by element
5522   // on the stack followed by a load for everything else.
5523   if (!isConstant && !usesOnlyOneValue) {
5524     SDValue Vec = DAG.getUNDEF(VT);
5525     for (unsigned i = 0 ; i < NumElts; ++i) {
5526       SDValue V = Op.getOperand(i);
5527       if (V.getOpcode() == ISD::UNDEF)
5528         continue;
5529       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5530       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5531     }
5532     return Vec;
5533   }
5534
5535   return SDValue();
5536 }
5537
5538 /// getExtFactor - Determine the adjustment factor for the position when
5539 /// generating an "extract from vector registers" instruction.
5540 static unsigned getExtFactor(SDValue &V) {
5541   EVT EltType = V.getValueType().getVectorElementType();
5542   return EltType.getSizeInBits() / 8;
5543 }
5544
5545 // Gather data to see if the operation can be modelled as a
5546 // shuffle in combination with VEXTs.
5547 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5548                                               SelectionDAG &DAG) const {
5549   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5550   SDLoc dl(Op);
5551   EVT VT = Op.getValueType();
5552   unsigned NumElts = VT.getVectorNumElements();
5553
5554   struct ShuffleSourceInfo {
5555     SDValue Vec;
5556     unsigned MinElt;
5557     unsigned MaxElt;
5558
5559     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5560     // be compatible with the shuffle we intend to construct. As a result
5561     // ShuffleVec will be some sliding window into the original Vec.
5562     SDValue ShuffleVec;
5563
5564     // Code should guarantee that element i in Vec starts at element "WindowBase
5565     // + i * WindowScale in ShuffleVec".
5566     int WindowBase;
5567     int WindowScale;
5568
5569     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5570     ShuffleSourceInfo(SDValue Vec)
5571         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5572           WindowScale(1) {}
5573   };
5574
5575   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5576   // node.
5577   SmallVector<ShuffleSourceInfo, 2> Sources;
5578   for (unsigned i = 0; i < NumElts; ++i) {
5579     SDValue V = Op.getOperand(i);
5580     if (V.getOpcode() == ISD::UNDEF)
5581       continue;
5582     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5583       // A shuffle can only come from building a vector from various
5584       // elements of other vectors.
5585       return SDValue();
5586     }
5587
5588     // Add this element source to the list if it's not already there.
5589     SDValue SourceVec = V.getOperand(0);
5590     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5591     if (Source == Sources.end())
5592       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5593
5594     // Update the minimum and maximum lane number seen.
5595     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5596     Source->MinElt = std::min(Source->MinElt, EltNo);
5597     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5598   }
5599
5600   // Currently only do something sane when at most two source vectors
5601   // are involved.
5602   if (Sources.size() > 2)
5603     return SDValue();
5604
5605   // Find out the smallest element size among result and two sources, and use
5606   // it as element size to build the shuffle_vector.
5607   EVT SmallestEltTy = VT.getVectorElementType();
5608   for (auto &Source : Sources) {
5609     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5610     if (SrcEltTy.bitsLT(SmallestEltTy))
5611       SmallestEltTy = SrcEltTy;
5612   }
5613   unsigned ResMultiplier =
5614       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5615   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5616   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5617
5618   // If the source vector is too wide or too narrow, we may nevertheless be able
5619   // to construct a compatible shuffle either by concatenating it with UNDEF or
5620   // extracting a suitable range of elements.
5621   for (auto &Src : Sources) {
5622     EVT SrcVT = Src.ShuffleVec.getValueType();
5623
5624     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5625       continue;
5626
5627     // This stage of the search produces a source with the same element type as
5628     // the original, but with a total width matching the BUILD_VECTOR output.
5629     EVT EltVT = SrcVT.getVectorElementType();
5630     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5631     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5632
5633     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5634       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5635         return SDValue();
5636       // We can pad out the smaller vector for free, so if it's part of a
5637       // shuffle...
5638       Src.ShuffleVec =
5639           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5640                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5641       continue;
5642     }
5643
5644     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5645       return SDValue();
5646
5647     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5648       // Span too large for a VEXT to cope
5649       return SDValue();
5650     }
5651
5652     if (Src.MinElt >= NumSrcElts) {
5653       // The extraction can just take the second half
5654       Src.ShuffleVec =
5655           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5656                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5657       Src.WindowBase = -NumSrcElts;
5658     } else if (Src.MaxElt < NumSrcElts) {
5659       // The extraction can just take the first half
5660       Src.ShuffleVec =
5661           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5662                       DAG.getConstant(0, dl, MVT::i32));
5663     } else {
5664       // An actual VEXT is needed
5665       SDValue VEXTSrc1 =
5666           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5667                       DAG.getConstant(0, dl, MVT::i32));
5668       SDValue VEXTSrc2 =
5669           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5670                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5671       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5672
5673       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5674                                    VEXTSrc2,
5675                                    DAG.getConstant(Imm, dl, MVT::i32));
5676       Src.WindowBase = -Src.MinElt;
5677     }
5678   }
5679
5680   // Another possible incompatibility occurs from the vector element types. We
5681   // can fix this by bitcasting the source vectors to the same type we intend
5682   // for the shuffle.
5683   for (auto &Src : Sources) {
5684     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5685     if (SrcEltTy == SmallestEltTy)
5686       continue;
5687     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5688     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5689     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5690     Src.WindowBase *= Src.WindowScale;
5691   }
5692
5693   // Final sanity check before we try to actually produce a shuffle.
5694   DEBUG(
5695     for (auto Src : Sources)
5696       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5697   );
5698
5699   // The stars all align, our next step is to produce the mask for the shuffle.
5700   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5701   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5702   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5703     SDValue Entry = Op.getOperand(i);
5704     if (Entry.getOpcode() == ISD::UNDEF)
5705       continue;
5706
5707     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5708     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5709
5710     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5711     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5712     // segment.
5713     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5714     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5715                                VT.getVectorElementType().getSizeInBits());
5716     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5717
5718     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5719     // starting at the appropriate offset.
5720     int *LaneMask = &Mask[i * ResMultiplier];
5721
5722     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5723     ExtractBase += NumElts * (Src - Sources.begin());
5724     for (int j = 0; j < LanesDefined; ++j)
5725       LaneMask[j] = ExtractBase + j;
5726   }
5727
5728   // Final check before we try to produce nonsense...
5729   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5730     return SDValue();
5731
5732   // We can't handle more than two sources. This should have already
5733   // been checked before this point.
5734   assert(Sources.size() <= 2 && "Too many sources!");
5735
5736   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5737   for (unsigned i = 0; i < Sources.size(); ++i)
5738     ShuffleOps[i] = Sources[i].ShuffleVec;
5739
5740   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5741                                          ShuffleOps[1], &Mask[0]);
5742   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5743 }
5744
5745 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5746 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5747 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5748 /// are assumed to be legal.
5749 bool
5750 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5751                                       EVT VT) const {
5752   if (VT.getVectorNumElements() == 4 &&
5753       (VT.is128BitVector() || VT.is64BitVector())) {
5754     unsigned PFIndexes[4];
5755     for (unsigned i = 0; i != 4; ++i) {
5756       if (M[i] < 0)
5757         PFIndexes[i] = 8;
5758       else
5759         PFIndexes[i] = M[i];
5760     }
5761
5762     // Compute the index in the perfect shuffle table.
5763     unsigned PFTableIndex =
5764       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5765     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5766     unsigned Cost = (PFEntry >> 30);
5767
5768     if (Cost <= 4)
5769       return true;
5770   }
5771
5772   bool ReverseVEXT, isV_UNDEF;
5773   unsigned Imm, WhichResult;
5774
5775   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5776   return (EltSize >= 32 ||
5777           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5778           isVREVMask(M, VT, 64) ||
5779           isVREVMask(M, VT, 32) ||
5780           isVREVMask(M, VT, 16) ||
5781           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5782           isVTBLMask(M, VT) ||
5783           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5784           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5785 }
5786
5787 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5788 /// the specified operations to build the shuffle.
5789 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5790                                       SDValue RHS, SelectionDAG &DAG,
5791                                       SDLoc dl) {
5792   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5793   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5794   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5795
5796   enum {
5797     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5798     OP_VREV,
5799     OP_VDUP0,
5800     OP_VDUP1,
5801     OP_VDUP2,
5802     OP_VDUP3,
5803     OP_VEXT1,
5804     OP_VEXT2,
5805     OP_VEXT3,
5806     OP_VUZPL, // VUZP, left result
5807     OP_VUZPR, // VUZP, right result
5808     OP_VZIPL, // VZIP, left result
5809     OP_VZIPR, // VZIP, right result
5810     OP_VTRNL, // VTRN, left result
5811     OP_VTRNR  // VTRN, right result
5812   };
5813
5814   if (OpNum == OP_COPY) {
5815     if (LHSID == (1*9+2)*9+3) return LHS;
5816     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5817     return RHS;
5818   }
5819
5820   SDValue OpLHS, OpRHS;
5821   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5822   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5823   EVT VT = OpLHS.getValueType();
5824
5825   switch (OpNum) {
5826   default: llvm_unreachable("Unknown shuffle opcode!");
5827   case OP_VREV:
5828     // VREV divides the vector in half and swaps within the half.
5829     if (VT.getVectorElementType() == MVT::i32 ||
5830         VT.getVectorElementType() == MVT::f32)
5831       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5832     // vrev <4 x i16> -> VREV32
5833     if (VT.getVectorElementType() == MVT::i16)
5834       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5835     // vrev <4 x i8> -> VREV16
5836     assert(VT.getVectorElementType() == MVT::i8);
5837     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5838   case OP_VDUP0:
5839   case OP_VDUP1:
5840   case OP_VDUP2:
5841   case OP_VDUP3:
5842     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5843                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5844   case OP_VEXT1:
5845   case OP_VEXT2:
5846   case OP_VEXT3:
5847     return DAG.getNode(ARMISD::VEXT, dl, VT,
5848                        OpLHS, OpRHS,
5849                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5850   case OP_VUZPL:
5851   case OP_VUZPR:
5852     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5853                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5854   case OP_VZIPL:
5855   case OP_VZIPR:
5856     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5857                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5858   case OP_VTRNL:
5859   case OP_VTRNR:
5860     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5861                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5862   }
5863 }
5864
5865 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5866                                        ArrayRef<int> ShuffleMask,
5867                                        SelectionDAG &DAG) {
5868   // Check to see if we can use the VTBL instruction.
5869   SDValue V1 = Op.getOperand(0);
5870   SDValue V2 = Op.getOperand(1);
5871   SDLoc DL(Op);
5872
5873   SmallVector<SDValue, 8> VTBLMask;
5874   for (ArrayRef<int>::iterator
5875          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5876     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5877
5878   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5879     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5880                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5881
5882   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5883                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5884 }
5885
5886 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5887                                                       SelectionDAG &DAG) {
5888   SDLoc DL(Op);
5889   SDValue OpLHS = Op.getOperand(0);
5890   EVT VT = OpLHS.getValueType();
5891
5892   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5893          "Expect an v8i16/v16i8 type");
5894   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5895   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5896   // extract the first 8 bytes into the top double word and the last 8 bytes
5897   // into the bottom double word. The v8i16 case is similar.
5898   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5899   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5900                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5901 }
5902
5903 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5904   SDValue V1 = Op.getOperand(0);
5905   SDValue V2 = Op.getOperand(1);
5906   SDLoc dl(Op);
5907   EVT VT = Op.getValueType();
5908   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5909
5910   // Convert shuffles that are directly supported on NEON to target-specific
5911   // DAG nodes, instead of keeping them as shuffles and matching them again
5912   // during code selection.  This is more efficient and avoids the possibility
5913   // of inconsistencies between legalization and selection.
5914   // FIXME: floating-point vectors should be canonicalized to integer vectors
5915   // of the same time so that they get CSEd properly.
5916   ArrayRef<int> ShuffleMask = SVN->getMask();
5917
5918   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5919   if (EltSize <= 32) {
5920     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5921       int Lane = SVN->getSplatIndex();
5922       // If this is undef splat, generate it via "just" vdup, if possible.
5923       if (Lane == -1) Lane = 0;
5924
5925       // Test if V1 is a SCALAR_TO_VECTOR.
5926       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5927         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5928       }
5929       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5930       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5931       // reaches it).
5932       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5933           !isa<ConstantSDNode>(V1.getOperand(0))) {
5934         bool IsScalarToVector = true;
5935         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5936           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5937             IsScalarToVector = false;
5938             break;
5939           }
5940         if (IsScalarToVector)
5941           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5942       }
5943       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5944                          DAG.getConstant(Lane, dl, MVT::i32));
5945     }
5946
5947     bool ReverseVEXT;
5948     unsigned Imm;
5949     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5950       if (ReverseVEXT)
5951         std::swap(V1, V2);
5952       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5953                          DAG.getConstant(Imm, dl, MVT::i32));
5954     }
5955
5956     if (isVREVMask(ShuffleMask, VT, 64))
5957       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5958     if (isVREVMask(ShuffleMask, VT, 32))
5959       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5960     if (isVREVMask(ShuffleMask, VT, 16))
5961       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5962
5963     if (V2->getOpcode() == ISD::UNDEF &&
5964         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5965       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5966                          DAG.getConstant(Imm, dl, MVT::i32));
5967     }
5968
5969     // Check for Neon shuffles that modify both input vectors in place.
5970     // If both results are used, i.e., if there are two shuffles with the same
5971     // source operands and with masks corresponding to both results of one of
5972     // these operations, DAG memoization will ensure that a single node is
5973     // used for both shuffles.
5974     unsigned WhichResult;
5975     bool isV_UNDEF;
5976     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5977             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5978       if (isV_UNDEF)
5979         V2 = V1;
5980       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5981           .getValue(WhichResult);
5982     }
5983
5984     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5985     // shuffles that produce a result larger than their operands with:
5986     //   shuffle(concat(v1, undef), concat(v2, undef))
5987     // ->
5988     //   shuffle(concat(v1, v2), undef)
5989     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5990     //
5991     // This is useful in the general case, but there are special cases where
5992     // native shuffles produce larger results: the two-result ops.
5993     //
5994     // Look through the concat when lowering them:
5995     //   shuffle(concat(v1, v2), undef)
5996     // ->
5997     //   concat(VZIP(v1, v2):0, :1)
5998     //
5999     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6000         V2->getOpcode() == ISD::UNDEF) {
6001       SDValue SubV1 = V1->getOperand(0);
6002       SDValue SubV2 = V1->getOperand(1);
6003       EVT SubVT = SubV1.getValueType();
6004
6005       // We expect these to have been canonicalized to -1.
6006       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6007         return i < (int)VT.getVectorNumElements();
6008       }) && "Unexpected shuffle index into UNDEF operand!");
6009
6010       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6011               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6012         if (isV_UNDEF)
6013           SubV2 = SubV1;
6014         assert((WhichResult == 0) &&
6015                "In-place shuffle of concat can only have one result!");
6016         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6017                                   SubV1, SubV2);
6018         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6019                            Res.getValue(1));
6020       }
6021     }
6022   }
6023
6024   // If the shuffle is not directly supported and it has 4 elements, use
6025   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6026   unsigned NumElts = VT.getVectorNumElements();
6027   if (NumElts == 4) {
6028     unsigned PFIndexes[4];
6029     for (unsigned i = 0; i != 4; ++i) {
6030       if (ShuffleMask[i] < 0)
6031         PFIndexes[i] = 8;
6032       else
6033         PFIndexes[i] = ShuffleMask[i];
6034     }
6035
6036     // Compute the index in the perfect shuffle table.
6037     unsigned PFTableIndex =
6038       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6039     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6040     unsigned Cost = (PFEntry >> 30);
6041
6042     if (Cost <= 4)
6043       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6044   }
6045
6046   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6047   if (EltSize >= 32) {
6048     // Do the expansion with floating-point types, since that is what the VFP
6049     // registers are defined to use, and since i64 is not legal.
6050     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6051     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6052     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6053     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6054     SmallVector<SDValue, 8> Ops;
6055     for (unsigned i = 0; i < NumElts; ++i) {
6056       if (ShuffleMask[i] < 0)
6057         Ops.push_back(DAG.getUNDEF(EltVT));
6058       else
6059         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6060                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6061                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6062                                                   dl, MVT::i32)));
6063     }
6064     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6065     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6066   }
6067
6068   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6069     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6070
6071   if (VT == MVT::v8i8) {
6072     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6073     if (NewOp.getNode())
6074       return NewOp;
6075   }
6076
6077   return SDValue();
6078 }
6079
6080 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6081   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6082   SDValue Lane = Op.getOperand(2);
6083   if (!isa<ConstantSDNode>(Lane))
6084     return SDValue();
6085
6086   return Op;
6087 }
6088
6089 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6090   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6091   SDValue Lane = Op.getOperand(1);
6092   if (!isa<ConstantSDNode>(Lane))
6093     return SDValue();
6094
6095   SDValue Vec = Op.getOperand(0);
6096   if (Op.getValueType() == MVT::i32 &&
6097       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6098     SDLoc dl(Op);
6099     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6100   }
6101
6102   return Op;
6103 }
6104
6105 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6106   // The only time a CONCAT_VECTORS operation can have legal types is when
6107   // two 64-bit vectors are concatenated to a 128-bit vector.
6108   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6109          "unexpected CONCAT_VECTORS");
6110   SDLoc dl(Op);
6111   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6112   SDValue Op0 = Op.getOperand(0);
6113   SDValue Op1 = Op.getOperand(1);
6114   if (Op0.getOpcode() != ISD::UNDEF)
6115     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6116                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6117                       DAG.getIntPtrConstant(0, dl));
6118   if (Op1.getOpcode() != ISD::UNDEF)
6119     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6120                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6121                       DAG.getIntPtrConstant(1, dl));
6122   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6123 }
6124
6125 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6126 /// element has been zero/sign-extended, depending on the isSigned parameter,
6127 /// from an integer type half its size.
6128 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6129                                    bool isSigned) {
6130   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6131   EVT VT = N->getValueType(0);
6132   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6133     SDNode *BVN = N->getOperand(0).getNode();
6134     if (BVN->getValueType(0) != MVT::v4i32 ||
6135         BVN->getOpcode() != ISD::BUILD_VECTOR)
6136       return false;
6137     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6138     unsigned HiElt = 1 - LoElt;
6139     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6140     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6141     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6142     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6143     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6144       return false;
6145     if (isSigned) {
6146       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6147           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6148         return true;
6149     } else {
6150       if (Hi0->isNullValue() && Hi1->isNullValue())
6151         return true;
6152     }
6153     return false;
6154   }
6155
6156   if (N->getOpcode() != ISD::BUILD_VECTOR)
6157     return false;
6158
6159   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6160     SDNode *Elt = N->getOperand(i).getNode();
6161     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6162       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6163       unsigned HalfSize = EltSize / 2;
6164       if (isSigned) {
6165         if (!isIntN(HalfSize, C->getSExtValue()))
6166           return false;
6167       } else {
6168         if (!isUIntN(HalfSize, C->getZExtValue()))
6169           return false;
6170       }
6171       continue;
6172     }
6173     return false;
6174   }
6175
6176   return true;
6177 }
6178
6179 /// isSignExtended - Check if a node is a vector value that is sign-extended
6180 /// or a constant BUILD_VECTOR with sign-extended elements.
6181 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6182   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6183     return true;
6184   if (isExtendedBUILD_VECTOR(N, DAG, true))
6185     return true;
6186   return false;
6187 }
6188
6189 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6190 /// or a constant BUILD_VECTOR with zero-extended elements.
6191 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6192   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6193     return true;
6194   if (isExtendedBUILD_VECTOR(N, DAG, false))
6195     return true;
6196   return false;
6197 }
6198
6199 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6200   if (OrigVT.getSizeInBits() >= 64)
6201     return OrigVT;
6202
6203   assert(OrigVT.isSimple() && "Expecting a simple value type");
6204
6205   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6206   switch (OrigSimpleTy) {
6207   default: llvm_unreachable("Unexpected Vector Type");
6208   case MVT::v2i8:
6209   case MVT::v2i16:
6210      return MVT::v2i32;
6211   case MVT::v4i8:
6212     return  MVT::v4i16;
6213   }
6214 }
6215
6216 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6217 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6218 /// We insert the required extension here to get the vector to fill a D register.
6219 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6220                                             const EVT &OrigTy,
6221                                             const EVT &ExtTy,
6222                                             unsigned ExtOpcode) {
6223   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6224   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6225   // 64-bits we need to insert a new extension so that it will be 64-bits.
6226   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6227   if (OrigTy.getSizeInBits() >= 64)
6228     return N;
6229
6230   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6231   EVT NewVT = getExtensionTo64Bits(OrigTy);
6232
6233   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6234 }
6235
6236 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6237 /// does not do any sign/zero extension. If the original vector is less
6238 /// than 64 bits, an appropriate extension will be added after the load to
6239 /// reach a total size of 64 bits. We have to add the extension separately
6240 /// because ARM does not have a sign/zero extending load for vectors.
6241 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6242   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6243
6244   // The load already has the right type.
6245   if (ExtendedTy == LD->getMemoryVT())
6246     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6247                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6248                 LD->isNonTemporal(), LD->isInvariant(),
6249                 LD->getAlignment());
6250
6251   // We need to create a zextload/sextload. We cannot just create a load
6252   // followed by a zext/zext node because LowerMUL is also run during normal
6253   // operation legalization where we can't create illegal types.
6254   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6255                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6256                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6257                         LD->isNonTemporal(), LD->getAlignment());
6258 }
6259
6260 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6261 /// extending load, or BUILD_VECTOR with extended elements, return the
6262 /// unextended value. The unextended vector should be 64 bits so that it can
6263 /// be used as an operand to a VMULL instruction. If the original vector size
6264 /// before extension is less than 64 bits we add a an extension to resize
6265 /// the vector to 64 bits.
6266 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6267   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6268     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6269                                         N->getOperand(0)->getValueType(0),
6270                                         N->getValueType(0),
6271                                         N->getOpcode());
6272
6273   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6274     return SkipLoadExtensionForVMULL(LD, DAG);
6275
6276   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6277   // have been legalized as a BITCAST from v4i32.
6278   if (N->getOpcode() == ISD::BITCAST) {
6279     SDNode *BVN = N->getOperand(0).getNode();
6280     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6281            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6282     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6283     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6284                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6285   }
6286   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6287   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6288   EVT VT = N->getValueType(0);
6289   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6290   unsigned NumElts = VT.getVectorNumElements();
6291   MVT TruncVT = MVT::getIntegerVT(EltSize);
6292   SmallVector<SDValue, 8> Ops;
6293   SDLoc dl(N);
6294   for (unsigned i = 0; i != NumElts; ++i) {
6295     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6296     const APInt &CInt = C->getAPIntValue();
6297     // Element types smaller than 32 bits are not legal, so use i32 elements.
6298     // The values are implicitly truncated so sext vs. zext doesn't matter.
6299     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6300   }
6301   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6302                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6303 }
6304
6305 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6306   unsigned Opcode = N->getOpcode();
6307   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6308     SDNode *N0 = N->getOperand(0).getNode();
6309     SDNode *N1 = N->getOperand(1).getNode();
6310     return N0->hasOneUse() && N1->hasOneUse() &&
6311       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6312   }
6313   return false;
6314 }
6315
6316 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6317   unsigned Opcode = N->getOpcode();
6318   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6319     SDNode *N0 = N->getOperand(0).getNode();
6320     SDNode *N1 = N->getOperand(1).getNode();
6321     return N0->hasOneUse() && N1->hasOneUse() &&
6322       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6323   }
6324   return false;
6325 }
6326
6327 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6328   // Multiplications are only custom-lowered for 128-bit vectors so that
6329   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6330   EVT VT = Op.getValueType();
6331   assert(VT.is128BitVector() && VT.isInteger() &&
6332          "unexpected type for custom-lowering ISD::MUL");
6333   SDNode *N0 = Op.getOperand(0).getNode();
6334   SDNode *N1 = Op.getOperand(1).getNode();
6335   unsigned NewOpc = 0;
6336   bool isMLA = false;
6337   bool isN0SExt = isSignExtended(N0, DAG);
6338   bool isN1SExt = isSignExtended(N1, DAG);
6339   if (isN0SExt && isN1SExt)
6340     NewOpc = ARMISD::VMULLs;
6341   else {
6342     bool isN0ZExt = isZeroExtended(N0, DAG);
6343     bool isN1ZExt = isZeroExtended(N1, DAG);
6344     if (isN0ZExt && isN1ZExt)
6345       NewOpc = ARMISD::VMULLu;
6346     else if (isN1SExt || isN1ZExt) {
6347       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6348       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6349       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6350         NewOpc = ARMISD::VMULLs;
6351         isMLA = true;
6352       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6353         NewOpc = ARMISD::VMULLu;
6354         isMLA = true;
6355       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6356         std::swap(N0, N1);
6357         NewOpc = ARMISD::VMULLu;
6358         isMLA = true;
6359       }
6360     }
6361
6362     if (!NewOpc) {
6363       if (VT == MVT::v2i64)
6364         // Fall through to expand this.  It is not legal.
6365         return SDValue();
6366       else
6367         // Other vector multiplications are legal.
6368         return Op;
6369     }
6370   }
6371
6372   // Legalize to a VMULL instruction.
6373   SDLoc DL(Op);
6374   SDValue Op0;
6375   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6376   if (!isMLA) {
6377     Op0 = SkipExtensionForVMULL(N0, DAG);
6378     assert(Op0.getValueType().is64BitVector() &&
6379            Op1.getValueType().is64BitVector() &&
6380            "unexpected types for extended operands to VMULL");
6381     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6382   }
6383
6384   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6385   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6386   //   vmull q0, d4, d6
6387   //   vmlal q0, d5, d6
6388   // is faster than
6389   //   vaddl q0, d4, d5
6390   //   vmovl q1, d6
6391   //   vmul  q0, q0, q1
6392   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6393   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6394   EVT Op1VT = Op1.getValueType();
6395   return DAG.getNode(N0->getOpcode(), DL, VT,
6396                      DAG.getNode(NewOpc, DL, VT,
6397                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6398                      DAG.getNode(NewOpc, DL, VT,
6399                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6400 }
6401
6402 static SDValue
6403 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6404   // Convert to float
6405   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6406   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6407   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6408   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6409   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6410   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6411   // Get reciprocal estimate.
6412   // float4 recip = vrecpeq_f32(yf);
6413   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6414                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6415                    Y);
6416   // Because char has a smaller range than uchar, we can actually get away
6417   // without any newton steps.  This requires that we use a weird bias
6418   // of 0xb000, however (again, this has been exhaustively tested).
6419   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6420   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6421   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6422   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6423   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6424   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6425   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6426   // Convert back to short.
6427   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6428   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6429   return X;
6430 }
6431
6432 static SDValue
6433 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6434   SDValue N2;
6435   // Convert to float.
6436   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6437   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6438   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6439   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6440   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6441   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6442
6443   // Use reciprocal estimate and one refinement step.
6444   // float4 recip = vrecpeq_f32(yf);
6445   // recip *= vrecpsq_f32(yf, recip);
6446   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6447                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6448                    N1);
6449   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6450                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6451                    N1, N2);
6452   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6453   // Because short has a smaller range than ushort, we can actually get away
6454   // with only a single newton step.  This requires that we use a weird bias
6455   // of 89, however (again, this has been exhaustively tested).
6456   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6457   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6458   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6459   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6460   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6461   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6462   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6463   // Convert back to integer and return.
6464   // return vmovn_s32(vcvt_s32_f32(result));
6465   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6466   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6467   return N0;
6468 }
6469
6470 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6471   EVT VT = Op.getValueType();
6472   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6473          "unexpected type for custom-lowering ISD::SDIV");
6474
6475   SDLoc dl(Op);
6476   SDValue N0 = Op.getOperand(0);
6477   SDValue N1 = Op.getOperand(1);
6478   SDValue N2, N3;
6479
6480   if (VT == MVT::v8i8) {
6481     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6482     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6483
6484     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6485                      DAG.getIntPtrConstant(4, dl));
6486     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6487                      DAG.getIntPtrConstant(4, dl));
6488     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6489                      DAG.getIntPtrConstant(0, dl));
6490     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6491                      DAG.getIntPtrConstant(0, dl));
6492
6493     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6494     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6495
6496     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6497     N0 = LowerCONCAT_VECTORS(N0, DAG);
6498
6499     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6500     return N0;
6501   }
6502   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6503 }
6504
6505 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6506   EVT VT = Op.getValueType();
6507   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6508          "unexpected type for custom-lowering ISD::UDIV");
6509
6510   SDLoc dl(Op);
6511   SDValue N0 = Op.getOperand(0);
6512   SDValue N1 = Op.getOperand(1);
6513   SDValue N2, N3;
6514
6515   if (VT == MVT::v8i8) {
6516     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6517     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6518
6519     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6520                      DAG.getIntPtrConstant(4, dl));
6521     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6522                      DAG.getIntPtrConstant(4, dl));
6523     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6524                      DAG.getIntPtrConstant(0, dl));
6525     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6526                      DAG.getIntPtrConstant(0, dl));
6527
6528     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6529     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6530
6531     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6532     N0 = LowerCONCAT_VECTORS(N0, DAG);
6533
6534     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6535                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6536                                      MVT::i32),
6537                      N0);
6538     return N0;
6539   }
6540
6541   // v4i16 sdiv ... Convert to float.
6542   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6543   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6544   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6545   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6546   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6547   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6548
6549   // Use reciprocal estimate and two refinement steps.
6550   // float4 recip = vrecpeq_f32(yf);
6551   // recip *= vrecpsq_f32(yf, recip);
6552   // recip *= vrecpsq_f32(yf, recip);
6553   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6554                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6555                    BN1);
6556   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6557                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6558                    BN1, N2);
6559   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6560   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6561                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6562                    BN1, N2);
6563   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6564   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6565   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6566   // and that it will never cause us to return an answer too large).
6567   // float4 result = as_float4(as_int4(xf*recip) + 2);
6568   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6569   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6570   N1 = DAG.getConstant(2, dl, MVT::i32);
6571   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6572   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6573   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6574   // Convert back to integer and return.
6575   // return vmovn_u32(vcvt_s32_f32(result));
6576   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6577   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6578   return N0;
6579 }
6580
6581 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6582   EVT VT = Op.getNode()->getValueType(0);
6583   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6584
6585   unsigned Opc;
6586   bool ExtraOp = false;
6587   switch (Op.getOpcode()) {
6588   default: llvm_unreachable("Invalid code");
6589   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6590   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6591   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6592   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6593   }
6594
6595   if (!ExtraOp)
6596     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6597                        Op.getOperand(1));
6598   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6599                      Op.getOperand(1), Op.getOperand(2));
6600 }
6601
6602 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6603   assert(Subtarget->isTargetDarwin());
6604
6605   // For iOS, we want to call an alternative entry point: __sincos_stret,
6606   // return values are passed via sret.
6607   SDLoc dl(Op);
6608   SDValue Arg = Op.getOperand(0);
6609   EVT ArgVT = Arg.getValueType();
6610   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6611   auto PtrVT = getPointerTy(DAG.getDataLayout());
6612
6613   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6614
6615   // Pair of floats / doubles used to pass the result.
6616   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6617
6618   // Create stack object for sret.
6619   auto &DL = DAG.getDataLayout();
6620   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6621   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6622   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6623   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6624
6625   ArgListTy Args;
6626   ArgListEntry Entry;
6627
6628   Entry.Node = SRet;
6629   Entry.Ty = RetTy->getPointerTo();
6630   Entry.isSExt = false;
6631   Entry.isZExt = false;
6632   Entry.isSRet = true;
6633   Args.push_back(Entry);
6634
6635   Entry.Node = Arg;
6636   Entry.Ty = ArgTy;
6637   Entry.isSExt = false;
6638   Entry.isZExt = false;
6639   Args.push_back(Entry);
6640
6641   const char *LibcallName  = (ArgVT == MVT::f64)
6642   ? "__sincos_stret" : "__sincosf_stret";
6643   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6644
6645   TargetLowering::CallLoweringInfo CLI(DAG);
6646   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6647     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6648                std::move(Args), 0)
6649     .setDiscardResult();
6650
6651   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6652
6653   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6654                                 MachinePointerInfo(), false, false, false, 0);
6655
6656   // Address of cos field.
6657   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6658                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6659   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6660                                 MachinePointerInfo(), false, false, false, 0);
6661
6662   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6663   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6664                      LoadSin.getValue(0), LoadCos.getValue(0));
6665 }
6666
6667 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6668   // Monotonic load/store is legal for all targets
6669   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6670     return Op;
6671
6672   // Acquire/Release load/store is not legal for targets without a
6673   // dmb or equivalent available.
6674   return SDValue();
6675 }
6676
6677 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6678                                     SmallVectorImpl<SDValue> &Results,
6679                                     SelectionDAG &DAG,
6680                                     const ARMSubtarget *Subtarget) {
6681   SDLoc DL(N);
6682   SDValue Cycles32, OutChain;
6683
6684   if (Subtarget->hasPerfMon()) {
6685     // Under Power Management extensions, the cycle-count is:
6686     //    mrc p15, #0, <Rt>, c9, c13, #0
6687     SDValue Ops[] = { N->getOperand(0), // Chain
6688                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6689                       DAG.getConstant(15, DL, MVT::i32),
6690                       DAG.getConstant(0, DL, MVT::i32),
6691                       DAG.getConstant(9, DL, MVT::i32),
6692                       DAG.getConstant(13, DL, MVT::i32),
6693                       DAG.getConstant(0, DL, MVT::i32)
6694     };
6695
6696     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6697                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6698     OutChain = Cycles32.getValue(1);
6699   } else {
6700     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6701     // there are older ARM CPUs that have implementation-specific ways of
6702     // obtaining this information (FIXME!).
6703     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6704     OutChain = DAG.getEntryNode();
6705   }
6706
6707
6708   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6709                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6710   Results.push_back(Cycles64);
6711   Results.push_back(OutChain);
6712 }
6713
6714 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6715   switch (Op.getOpcode()) {
6716   default: llvm_unreachable("Don't know how to custom lower this!");
6717   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6718   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6719   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6720   case ISD::GlobalAddress:
6721     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6722     default: llvm_unreachable("unknown object format");
6723     case Triple::COFF:
6724       return LowerGlobalAddressWindows(Op, DAG);
6725     case Triple::ELF:
6726       return LowerGlobalAddressELF(Op, DAG);
6727     case Triple::MachO:
6728       return LowerGlobalAddressDarwin(Op, DAG);
6729     }
6730   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6731   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6732   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6733   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6734   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6735   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6736   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6737   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6738   case ISD::SINT_TO_FP:
6739   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6740   case ISD::FP_TO_SINT:
6741   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6742   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6743   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6744   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6745   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6746   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6747   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6748   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6749   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6750                                                                Subtarget);
6751   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6752   case ISD::SHL:
6753   case ISD::SRL:
6754   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6755   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6756   case ISD::SRL_PARTS:
6757   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6758   case ISD::CTTZ:
6759   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6760   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6761   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6762   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6763   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6764   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6765   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6766   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6767   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6768   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6769   case ISD::MUL:           return LowerMUL(Op, DAG);
6770   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6771   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6772   case ISD::ADDC:
6773   case ISD::ADDE:
6774   case ISD::SUBC:
6775   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6776   case ISD::SADDO:
6777   case ISD::UADDO:
6778   case ISD::SSUBO:
6779   case ISD::USUBO:
6780     return LowerXALUO(Op, DAG);
6781   case ISD::ATOMIC_LOAD:
6782   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6783   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6784   case ISD::SDIVREM:
6785   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6786   case ISD::DYNAMIC_STACKALLOC:
6787     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6788       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6789     llvm_unreachable("Don't know how to custom lower this!");
6790   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6791   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6792   }
6793 }
6794
6795 /// ReplaceNodeResults - Replace the results of node with an illegal result
6796 /// type with new values built out of custom code.
6797 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6798                                            SmallVectorImpl<SDValue>&Results,
6799                                            SelectionDAG &DAG) const {
6800   SDValue Res;
6801   switch (N->getOpcode()) {
6802   default:
6803     llvm_unreachable("Don't know how to custom expand this!");
6804   case ISD::READ_REGISTER:
6805     ExpandREAD_REGISTER(N, Results, DAG);
6806     break;
6807   case ISD::BITCAST:
6808     Res = ExpandBITCAST(N, DAG);
6809     break;
6810   case ISD::SRL:
6811   case ISD::SRA:
6812     Res = Expand64BitShift(N, DAG, Subtarget);
6813     break;
6814   case ISD::READCYCLECOUNTER:
6815     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6816     return;
6817   }
6818   if (Res.getNode())
6819     Results.push_back(Res);
6820 }
6821
6822 //===----------------------------------------------------------------------===//
6823 //                           ARM Scheduler Hooks
6824 //===----------------------------------------------------------------------===//
6825
6826 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6827 /// registers the function context.
6828 void ARMTargetLowering::
6829 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6830                        MachineBasicBlock *DispatchBB, int FI) const {
6831   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6832   DebugLoc dl = MI->getDebugLoc();
6833   MachineFunction *MF = MBB->getParent();
6834   MachineRegisterInfo *MRI = &MF->getRegInfo();
6835   MachineConstantPool *MCP = MF->getConstantPool();
6836   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6837   const Function *F = MF->getFunction();
6838
6839   bool isThumb = Subtarget->isThumb();
6840   bool isThumb2 = Subtarget->isThumb2();
6841
6842   unsigned PCLabelId = AFI->createPICLabelUId();
6843   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6844   ARMConstantPoolValue *CPV =
6845     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6846   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6847
6848   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6849                                            : &ARM::GPRRegClass;
6850
6851   // Grab constant pool and fixed stack memory operands.
6852   MachineMemOperand *CPMMO =
6853     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6854                              MachineMemOperand::MOLoad, 4, 4);
6855
6856   MachineMemOperand *FIMMOSt =
6857     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6858                              MachineMemOperand::MOStore, 4, 4);
6859
6860   // Load the address of the dispatch MBB into the jump buffer.
6861   if (isThumb2) {
6862     // Incoming value: jbuf
6863     //   ldr.n  r5, LCPI1_1
6864     //   orr    r5, r5, #1
6865     //   add    r5, pc
6866     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6867     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6868     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6869                    .addConstantPoolIndex(CPI)
6870                    .addMemOperand(CPMMO));
6871     // Set the low bit because of thumb mode.
6872     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6873     AddDefaultCC(
6874       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6875                      .addReg(NewVReg1, RegState::Kill)
6876                      .addImm(0x01)));
6877     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6878     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6879       .addReg(NewVReg2, RegState::Kill)
6880       .addImm(PCLabelId);
6881     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6882                    .addReg(NewVReg3, RegState::Kill)
6883                    .addFrameIndex(FI)
6884                    .addImm(36)  // &jbuf[1] :: pc
6885                    .addMemOperand(FIMMOSt));
6886   } else if (isThumb) {
6887     // Incoming value: jbuf
6888     //   ldr.n  r1, LCPI1_4
6889     //   add    r1, pc
6890     //   mov    r2, #1
6891     //   orrs   r1, r2
6892     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6893     //   str    r1, [r2]
6894     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6895     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6896                    .addConstantPoolIndex(CPI)
6897                    .addMemOperand(CPMMO));
6898     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6899     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6900       .addReg(NewVReg1, RegState::Kill)
6901       .addImm(PCLabelId);
6902     // Set the low bit because of thumb mode.
6903     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6904     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6905                    .addReg(ARM::CPSR, RegState::Define)
6906                    .addImm(1));
6907     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6908     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6909                    .addReg(ARM::CPSR, RegState::Define)
6910                    .addReg(NewVReg2, RegState::Kill)
6911                    .addReg(NewVReg3, RegState::Kill));
6912     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6913     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6914             .addFrameIndex(FI)
6915             .addImm(36); // &jbuf[1] :: pc
6916     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6917                    .addReg(NewVReg4, RegState::Kill)
6918                    .addReg(NewVReg5, RegState::Kill)
6919                    .addImm(0)
6920                    .addMemOperand(FIMMOSt));
6921   } else {
6922     // Incoming value: jbuf
6923     //   ldr  r1, LCPI1_1
6924     //   add  r1, pc, r1
6925     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6926     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6927     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6928                    .addConstantPoolIndex(CPI)
6929                    .addImm(0)
6930                    .addMemOperand(CPMMO));
6931     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6932     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6933                    .addReg(NewVReg1, RegState::Kill)
6934                    .addImm(PCLabelId));
6935     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6936                    .addReg(NewVReg2, RegState::Kill)
6937                    .addFrameIndex(FI)
6938                    .addImm(36)  // &jbuf[1] :: pc
6939                    .addMemOperand(FIMMOSt));
6940   }
6941 }
6942
6943 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6944                                               MachineBasicBlock *MBB) const {
6945   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6946   DebugLoc dl = MI->getDebugLoc();
6947   MachineFunction *MF = MBB->getParent();
6948   MachineRegisterInfo *MRI = &MF->getRegInfo();
6949   MachineFrameInfo *MFI = MF->getFrameInfo();
6950   int FI = MFI->getFunctionContextIndex();
6951
6952   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6953                                                         : &ARM::GPRnopcRegClass;
6954
6955   // Get a mapping of the call site numbers to all of the landing pads they're
6956   // associated with.
6957   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6958   unsigned MaxCSNum = 0;
6959   MachineModuleInfo &MMI = MF->getMMI();
6960   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6961        ++BB) {
6962     if (!BB->isLandingPad()) continue;
6963
6964     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6965     // pad.
6966     for (MachineBasicBlock::iterator
6967            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6968       if (!II->isEHLabel()) continue;
6969
6970       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6971       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6972
6973       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6974       for (SmallVectorImpl<unsigned>::iterator
6975              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6976            CSI != CSE; ++CSI) {
6977         CallSiteNumToLPad[*CSI].push_back(BB);
6978         MaxCSNum = std::max(MaxCSNum, *CSI);
6979       }
6980       break;
6981     }
6982   }
6983
6984   // Get an ordered list of the machine basic blocks for the jump table.
6985   std::vector<MachineBasicBlock*> LPadList;
6986   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6987   LPadList.reserve(CallSiteNumToLPad.size());
6988   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6989     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6990     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6991            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6992       LPadList.push_back(*II);
6993       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6994     }
6995   }
6996
6997   assert(!LPadList.empty() &&
6998          "No landing pad destinations for the dispatch jump table!");
6999
7000   // Create the jump table and associated information.
7001   MachineJumpTableInfo *JTI =
7002     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7003   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7004   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7005
7006   // Create the MBBs for the dispatch code.
7007
7008   // Shove the dispatch's address into the return slot in the function context.
7009   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7010   DispatchBB->setIsLandingPad();
7011
7012   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7013   unsigned trap_opcode;
7014   if (Subtarget->isThumb())
7015     trap_opcode = ARM::tTRAP;
7016   else
7017     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7018
7019   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7020   DispatchBB->addSuccessor(TrapBB);
7021
7022   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7023   DispatchBB->addSuccessor(DispContBB);
7024
7025   // Insert and MBBs.
7026   MF->insert(MF->end(), DispatchBB);
7027   MF->insert(MF->end(), DispContBB);
7028   MF->insert(MF->end(), TrapBB);
7029
7030   // Insert code into the entry block that creates and registers the function
7031   // context.
7032   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7033
7034   MachineMemOperand *FIMMOLd =
7035     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
7036                              MachineMemOperand::MOLoad |
7037                              MachineMemOperand::MOVolatile, 4, 4);
7038
7039   MachineInstrBuilder MIB;
7040   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7041
7042   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7043   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7044
7045   // Add a register mask with no preserved registers.  This results in all
7046   // registers being marked as clobbered.
7047   MIB.addRegMask(RI.getNoPreservedMask());
7048
7049   unsigned NumLPads = LPadList.size();
7050   if (Subtarget->isThumb2()) {
7051     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7052     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7053                    .addFrameIndex(FI)
7054                    .addImm(4)
7055                    .addMemOperand(FIMMOLd));
7056
7057     if (NumLPads < 256) {
7058       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7059                      .addReg(NewVReg1)
7060                      .addImm(LPadList.size()));
7061     } else {
7062       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7063       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7064                      .addImm(NumLPads & 0xFFFF));
7065
7066       unsigned VReg2 = VReg1;
7067       if ((NumLPads & 0xFFFF0000) != 0) {
7068         VReg2 = MRI->createVirtualRegister(TRC);
7069         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7070                        .addReg(VReg1)
7071                        .addImm(NumLPads >> 16));
7072       }
7073
7074       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7075                      .addReg(NewVReg1)
7076                      .addReg(VReg2));
7077     }
7078
7079     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7080       .addMBB(TrapBB)
7081       .addImm(ARMCC::HI)
7082       .addReg(ARM::CPSR);
7083
7084     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7085     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7086                    .addJumpTableIndex(MJTI));
7087
7088     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7089     AddDefaultCC(
7090       AddDefaultPred(
7091         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7092         .addReg(NewVReg3, RegState::Kill)
7093         .addReg(NewVReg1)
7094         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7095
7096     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7097       .addReg(NewVReg4, RegState::Kill)
7098       .addReg(NewVReg1)
7099       .addJumpTableIndex(MJTI);
7100   } else if (Subtarget->isThumb()) {
7101     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7102     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7103                    .addFrameIndex(FI)
7104                    .addImm(1)
7105                    .addMemOperand(FIMMOLd));
7106
7107     if (NumLPads < 256) {
7108       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7109                      .addReg(NewVReg1)
7110                      .addImm(NumLPads));
7111     } else {
7112       MachineConstantPool *ConstantPool = MF->getConstantPool();
7113       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7114       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7115
7116       // MachineConstantPool wants an explicit alignment.
7117       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7118       if (Align == 0)
7119         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7120       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7121
7122       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7123       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7124                      .addReg(VReg1, RegState::Define)
7125                      .addConstantPoolIndex(Idx));
7126       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7127                      .addReg(NewVReg1)
7128                      .addReg(VReg1));
7129     }
7130
7131     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7132       .addMBB(TrapBB)
7133       .addImm(ARMCC::HI)
7134       .addReg(ARM::CPSR);
7135
7136     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7137     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7138                    .addReg(ARM::CPSR, RegState::Define)
7139                    .addReg(NewVReg1)
7140                    .addImm(2));
7141
7142     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7143     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7144                    .addJumpTableIndex(MJTI));
7145
7146     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7147     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7148                    .addReg(ARM::CPSR, RegState::Define)
7149                    .addReg(NewVReg2, RegState::Kill)
7150                    .addReg(NewVReg3));
7151
7152     MachineMemOperand *JTMMOLd =
7153       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7154                                MachineMemOperand::MOLoad, 4, 4);
7155
7156     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7157     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7158                    .addReg(NewVReg4, RegState::Kill)
7159                    .addImm(0)
7160                    .addMemOperand(JTMMOLd));
7161
7162     unsigned NewVReg6 = NewVReg5;
7163     if (RelocM == Reloc::PIC_) {
7164       NewVReg6 = MRI->createVirtualRegister(TRC);
7165       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7166                      .addReg(ARM::CPSR, RegState::Define)
7167                      .addReg(NewVReg5, RegState::Kill)
7168                      .addReg(NewVReg3));
7169     }
7170
7171     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7172       .addReg(NewVReg6, RegState::Kill)
7173       .addJumpTableIndex(MJTI);
7174   } else {
7175     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7176     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7177                    .addFrameIndex(FI)
7178                    .addImm(4)
7179                    .addMemOperand(FIMMOLd));
7180
7181     if (NumLPads < 256) {
7182       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7183                      .addReg(NewVReg1)
7184                      .addImm(NumLPads));
7185     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7186       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7187       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7188                      .addImm(NumLPads & 0xFFFF));
7189
7190       unsigned VReg2 = VReg1;
7191       if ((NumLPads & 0xFFFF0000) != 0) {
7192         VReg2 = MRI->createVirtualRegister(TRC);
7193         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7194                        .addReg(VReg1)
7195                        .addImm(NumLPads >> 16));
7196       }
7197
7198       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7199                      .addReg(NewVReg1)
7200                      .addReg(VReg2));
7201     } else {
7202       MachineConstantPool *ConstantPool = MF->getConstantPool();
7203       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7204       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7205
7206       // MachineConstantPool wants an explicit alignment.
7207       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7208       if (Align == 0)
7209         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7210       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7211
7212       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7213       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7214                      .addReg(VReg1, RegState::Define)
7215                      .addConstantPoolIndex(Idx)
7216                      .addImm(0));
7217       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7218                      .addReg(NewVReg1)
7219                      .addReg(VReg1, RegState::Kill));
7220     }
7221
7222     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7223       .addMBB(TrapBB)
7224       .addImm(ARMCC::HI)
7225       .addReg(ARM::CPSR);
7226
7227     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7228     AddDefaultCC(
7229       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7230                      .addReg(NewVReg1)
7231                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7232     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7233     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7234                    .addJumpTableIndex(MJTI));
7235
7236     MachineMemOperand *JTMMOLd =
7237       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7238                                MachineMemOperand::MOLoad, 4, 4);
7239     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7240     AddDefaultPred(
7241       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7242       .addReg(NewVReg3, RegState::Kill)
7243       .addReg(NewVReg4)
7244       .addImm(0)
7245       .addMemOperand(JTMMOLd));
7246
7247     if (RelocM == Reloc::PIC_) {
7248       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7249         .addReg(NewVReg5, RegState::Kill)
7250         .addReg(NewVReg4)
7251         .addJumpTableIndex(MJTI);
7252     } else {
7253       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7254         .addReg(NewVReg5, RegState::Kill)
7255         .addJumpTableIndex(MJTI);
7256     }
7257   }
7258
7259   // Add the jump table entries as successors to the MBB.
7260   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7261   for (std::vector<MachineBasicBlock*>::iterator
7262          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7263     MachineBasicBlock *CurMBB = *I;
7264     if (SeenMBBs.insert(CurMBB).second)
7265       DispContBB->addSuccessor(CurMBB);
7266   }
7267
7268   // N.B. the order the invoke BBs are processed in doesn't matter here.
7269   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7270   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7271   for (MachineBasicBlock *BB : InvokeBBs) {
7272
7273     // Remove the landing pad successor from the invoke block and replace it
7274     // with the new dispatch block.
7275     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7276                                                   BB->succ_end());
7277     while (!Successors.empty()) {
7278       MachineBasicBlock *SMBB = Successors.pop_back_val();
7279       if (SMBB->isLandingPad()) {
7280         BB->removeSuccessor(SMBB);
7281         MBBLPads.push_back(SMBB);
7282       }
7283     }
7284
7285     BB->addSuccessor(DispatchBB);
7286
7287     // Find the invoke call and mark all of the callee-saved registers as
7288     // 'implicit defined' so that they're spilled. This prevents code from
7289     // moving instructions to before the EH block, where they will never be
7290     // executed.
7291     for (MachineBasicBlock::reverse_iterator
7292            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7293       if (!II->isCall()) continue;
7294
7295       DenseMap<unsigned, bool> DefRegs;
7296       for (MachineInstr::mop_iterator
7297              OI = II->operands_begin(), OE = II->operands_end();
7298            OI != OE; ++OI) {
7299         if (!OI->isReg()) continue;
7300         DefRegs[OI->getReg()] = true;
7301       }
7302
7303       MachineInstrBuilder MIB(*MF, &*II);
7304
7305       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7306         unsigned Reg = SavedRegs[i];
7307         if (Subtarget->isThumb2() &&
7308             !ARM::tGPRRegClass.contains(Reg) &&
7309             !ARM::hGPRRegClass.contains(Reg))
7310           continue;
7311         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7312           continue;
7313         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7314           continue;
7315         if (!DefRegs[Reg])
7316           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7317       }
7318
7319       break;
7320     }
7321   }
7322
7323   // Mark all former landing pads as non-landing pads. The dispatch is the only
7324   // landing pad now.
7325   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7326          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7327     (*I)->setIsLandingPad(false);
7328
7329   // The instruction is gone now.
7330   MI->eraseFromParent();
7331 }
7332
7333 static
7334 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7335   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7336        E = MBB->succ_end(); I != E; ++I)
7337     if (*I != Succ)
7338       return *I;
7339   llvm_unreachable("Expecting a BB with two successors!");
7340 }
7341
7342 /// Return the load opcode for a given load size. If load size >= 8,
7343 /// neon opcode will be returned.
7344 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7345   if (LdSize >= 8)
7346     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7347                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7348   if (IsThumb1)
7349     return LdSize == 4 ? ARM::tLDRi
7350                        : LdSize == 2 ? ARM::tLDRHi
7351                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7352   if (IsThumb2)
7353     return LdSize == 4 ? ARM::t2LDR_POST
7354                        : LdSize == 2 ? ARM::t2LDRH_POST
7355                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7356   return LdSize == 4 ? ARM::LDR_POST_IMM
7357                      : LdSize == 2 ? ARM::LDRH_POST
7358                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7359 }
7360
7361 /// Return the store opcode for a given store size. If store size >= 8,
7362 /// neon opcode will be returned.
7363 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7364   if (StSize >= 8)
7365     return StSize == 16 ? ARM::VST1q32wb_fixed
7366                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7367   if (IsThumb1)
7368     return StSize == 4 ? ARM::tSTRi
7369                        : StSize == 2 ? ARM::tSTRHi
7370                                      : StSize == 1 ? ARM::tSTRBi : 0;
7371   if (IsThumb2)
7372     return StSize == 4 ? ARM::t2STR_POST
7373                        : StSize == 2 ? ARM::t2STRH_POST
7374                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7375   return StSize == 4 ? ARM::STR_POST_IMM
7376                      : StSize == 2 ? ARM::STRH_POST
7377                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7378 }
7379
7380 /// Emit a post-increment load operation with given size. The instructions
7381 /// will be added to BB at Pos.
7382 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7383                        const TargetInstrInfo *TII, DebugLoc dl,
7384                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7385                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7386   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7387   assert(LdOpc != 0 && "Should have a load opcode");
7388   if (LdSize >= 8) {
7389     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7390                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7391                        .addImm(0));
7392   } else if (IsThumb1) {
7393     // load + update AddrIn
7394     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7395                        .addReg(AddrIn).addImm(0));
7396     MachineInstrBuilder MIB =
7397         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7398     MIB = AddDefaultT1CC(MIB);
7399     MIB.addReg(AddrIn).addImm(LdSize);
7400     AddDefaultPred(MIB);
7401   } else if (IsThumb2) {
7402     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7403                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7404                        .addImm(LdSize));
7405   } else { // arm
7406     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7407                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7408                        .addReg(0).addImm(LdSize));
7409   }
7410 }
7411
7412 /// Emit a post-increment store operation with given size. The instructions
7413 /// will be added to BB at Pos.
7414 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7415                        const TargetInstrInfo *TII, DebugLoc dl,
7416                        unsigned StSize, unsigned Data, unsigned AddrIn,
7417                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7418   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7419   assert(StOpc != 0 && "Should have a store opcode");
7420   if (StSize >= 8) {
7421     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7422                        .addReg(AddrIn).addImm(0).addReg(Data));
7423   } else if (IsThumb1) {
7424     // store + update AddrIn
7425     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7426                        .addReg(AddrIn).addImm(0));
7427     MachineInstrBuilder MIB =
7428         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7429     MIB = AddDefaultT1CC(MIB);
7430     MIB.addReg(AddrIn).addImm(StSize);
7431     AddDefaultPred(MIB);
7432   } else if (IsThumb2) {
7433     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7434                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7435   } else { // arm
7436     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7437                        .addReg(Data).addReg(AddrIn).addReg(0)
7438                        .addImm(StSize));
7439   }
7440 }
7441
7442 MachineBasicBlock *
7443 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7444                                    MachineBasicBlock *BB) const {
7445   // This pseudo instruction has 3 operands: dst, src, size
7446   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7447   // Otherwise, we will generate unrolled scalar copies.
7448   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7449   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7450   MachineFunction::iterator It = BB;
7451   ++It;
7452
7453   unsigned dest = MI->getOperand(0).getReg();
7454   unsigned src = MI->getOperand(1).getReg();
7455   unsigned SizeVal = MI->getOperand(2).getImm();
7456   unsigned Align = MI->getOperand(3).getImm();
7457   DebugLoc dl = MI->getDebugLoc();
7458
7459   MachineFunction *MF = BB->getParent();
7460   MachineRegisterInfo &MRI = MF->getRegInfo();
7461   unsigned UnitSize = 0;
7462   const TargetRegisterClass *TRC = nullptr;
7463   const TargetRegisterClass *VecTRC = nullptr;
7464
7465   bool IsThumb1 = Subtarget->isThumb1Only();
7466   bool IsThumb2 = Subtarget->isThumb2();
7467
7468   if (Align & 1) {
7469     UnitSize = 1;
7470   } else if (Align & 2) {
7471     UnitSize = 2;
7472   } else {
7473     // Check whether we can use NEON instructions.
7474     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7475         Subtarget->hasNEON()) {
7476       if ((Align % 16 == 0) && SizeVal >= 16)
7477         UnitSize = 16;
7478       else if ((Align % 8 == 0) && SizeVal >= 8)
7479         UnitSize = 8;
7480     }
7481     // Can't use NEON instructions.
7482     if (UnitSize == 0)
7483       UnitSize = 4;
7484   }
7485
7486   // Select the correct opcode and register class for unit size load/store
7487   bool IsNeon = UnitSize >= 8;
7488   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7489   if (IsNeon)
7490     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7491                             : UnitSize == 8 ? &ARM::DPRRegClass
7492                                             : nullptr;
7493
7494   unsigned BytesLeft = SizeVal % UnitSize;
7495   unsigned LoopSize = SizeVal - BytesLeft;
7496
7497   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7498     // Use LDR and STR to copy.
7499     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7500     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7501     unsigned srcIn = src;
7502     unsigned destIn = dest;
7503     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7504       unsigned srcOut = MRI.createVirtualRegister(TRC);
7505       unsigned destOut = MRI.createVirtualRegister(TRC);
7506       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7507       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7508                  IsThumb1, IsThumb2);
7509       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7510                  IsThumb1, IsThumb2);
7511       srcIn = srcOut;
7512       destIn = destOut;
7513     }
7514
7515     // Handle the leftover bytes with LDRB and STRB.
7516     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7517     // [destOut] = STRB_POST(scratch, destIn, 1)
7518     for (unsigned i = 0; i < BytesLeft; i++) {
7519       unsigned srcOut = MRI.createVirtualRegister(TRC);
7520       unsigned destOut = MRI.createVirtualRegister(TRC);
7521       unsigned scratch = MRI.createVirtualRegister(TRC);
7522       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7523                  IsThumb1, IsThumb2);
7524       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7525                  IsThumb1, IsThumb2);
7526       srcIn = srcOut;
7527       destIn = destOut;
7528     }
7529     MI->eraseFromParent();   // The instruction is gone now.
7530     return BB;
7531   }
7532
7533   // Expand the pseudo op to a loop.
7534   // thisMBB:
7535   //   ...
7536   //   movw varEnd, # --> with thumb2
7537   //   movt varEnd, #
7538   //   ldrcp varEnd, idx --> without thumb2
7539   //   fallthrough --> loopMBB
7540   // loopMBB:
7541   //   PHI varPhi, varEnd, varLoop
7542   //   PHI srcPhi, src, srcLoop
7543   //   PHI destPhi, dst, destLoop
7544   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7545   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7546   //   subs varLoop, varPhi, #UnitSize
7547   //   bne loopMBB
7548   //   fallthrough --> exitMBB
7549   // exitMBB:
7550   //   epilogue to handle left-over bytes
7551   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7552   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7553   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7554   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7555   MF->insert(It, loopMBB);
7556   MF->insert(It, exitMBB);
7557
7558   // Transfer the remainder of BB and its successor edges to exitMBB.
7559   exitMBB->splice(exitMBB->begin(), BB,
7560                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7561   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7562
7563   // Load an immediate to varEnd.
7564   unsigned varEnd = MRI.createVirtualRegister(TRC);
7565   if (Subtarget->useMovt(*MF)) {
7566     unsigned Vtmp = varEnd;
7567     if ((LoopSize & 0xFFFF0000) != 0)
7568       Vtmp = MRI.createVirtualRegister(TRC);
7569     AddDefaultPred(BuildMI(BB, dl,
7570                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7571                            Vtmp).addImm(LoopSize & 0xFFFF));
7572
7573     if ((LoopSize & 0xFFFF0000) != 0)
7574       AddDefaultPred(BuildMI(BB, dl,
7575                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7576                              varEnd)
7577                          .addReg(Vtmp)
7578                          .addImm(LoopSize >> 16));
7579   } else {
7580     MachineConstantPool *ConstantPool = MF->getConstantPool();
7581     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7582     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7583
7584     // MachineConstantPool wants an explicit alignment.
7585     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7586     if (Align == 0)
7587       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7588     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7589
7590     if (IsThumb1)
7591       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7592           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7593     else
7594       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7595           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7596   }
7597   BB->addSuccessor(loopMBB);
7598
7599   // Generate the loop body:
7600   //   varPhi = PHI(varLoop, varEnd)
7601   //   srcPhi = PHI(srcLoop, src)
7602   //   destPhi = PHI(destLoop, dst)
7603   MachineBasicBlock *entryBB = BB;
7604   BB = loopMBB;
7605   unsigned varLoop = MRI.createVirtualRegister(TRC);
7606   unsigned varPhi = MRI.createVirtualRegister(TRC);
7607   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7608   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7609   unsigned destLoop = MRI.createVirtualRegister(TRC);
7610   unsigned destPhi = MRI.createVirtualRegister(TRC);
7611
7612   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7613     .addReg(varLoop).addMBB(loopMBB)
7614     .addReg(varEnd).addMBB(entryBB);
7615   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7616     .addReg(srcLoop).addMBB(loopMBB)
7617     .addReg(src).addMBB(entryBB);
7618   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7619     .addReg(destLoop).addMBB(loopMBB)
7620     .addReg(dest).addMBB(entryBB);
7621
7622   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7623   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7624   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7625   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7626              IsThumb1, IsThumb2);
7627   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7628              IsThumb1, IsThumb2);
7629
7630   // Decrement loop variable by UnitSize.
7631   if (IsThumb1) {
7632     MachineInstrBuilder MIB =
7633         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7634     MIB = AddDefaultT1CC(MIB);
7635     MIB.addReg(varPhi).addImm(UnitSize);
7636     AddDefaultPred(MIB);
7637   } else {
7638     MachineInstrBuilder MIB =
7639         BuildMI(*BB, BB->end(), dl,
7640                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7641     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7642     MIB->getOperand(5).setReg(ARM::CPSR);
7643     MIB->getOperand(5).setIsDef(true);
7644   }
7645   BuildMI(*BB, BB->end(), dl,
7646           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7647       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7648
7649   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7650   BB->addSuccessor(loopMBB);
7651   BB->addSuccessor(exitMBB);
7652
7653   // Add epilogue to handle BytesLeft.
7654   BB = exitMBB;
7655   MachineInstr *StartOfExit = exitMBB->begin();
7656
7657   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7658   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7659   unsigned srcIn = srcLoop;
7660   unsigned destIn = destLoop;
7661   for (unsigned i = 0; i < BytesLeft; i++) {
7662     unsigned srcOut = MRI.createVirtualRegister(TRC);
7663     unsigned destOut = MRI.createVirtualRegister(TRC);
7664     unsigned scratch = MRI.createVirtualRegister(TRC);
7665     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7666                IsThumb1, IsThumb2);
7667     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7668                IsThumb1, IsThumb2);
7669     srcIn = srcOut;
7670     destIn = destOut;
7671   }
7672
7673   MI->eraseFromParent();   // The instruction is gone now.
7674   return BB;
7675 }
7676
7677 MachineBasicBlock *
7678 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7679                                        MachineBasicBlock *MBB) const {
7680   const TargetMachine &TM = getTargetMachine();
7681   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7682   DebugLoc DL = MI->getDebugLoc();
7683
7684   assert(Subtarget->isTargetWindows() &&
7685          "__chkstk is only supported on Windows");
7686   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7687
7688   // __chkstk takes the number of words to allocate on the stack in R4, and
7689   // returns the stack adjustment in number of bytes in R4.  This will not
7690   // clober any other registers (other than the obvious lr).
7691   //
7692   // Although, technically, IP should be considered a register which may be
7693   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7694   // thumb-2 environment, so there is no interworking required.  As a result, we
7695   // do not expect a veneer to be emitted by the linker, clobbering IP.
7696   //
7697   // Each module receives its own copy of __chkstk, so no import thunk is
7698   // required, again, ensuring that IP is not clobbered.
7699   //
7700   // Finally, although some linkers may theoretically provide a trampoline for
7701   // out of range calls (which is quite common due to a 32M range limitation of
7702   // branches for Thumb), we can generate the long-call version via
7703   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7704   // IP.
7705
7706   switch (TM.getCodeModel()) {
7707   case CodeModel::Small:
7708   case CodeModel::Medium:
7709   case CodeModel::Default:
7710   case CodeModel::Kernel:
7711     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7712       .addImm((unsigned)ARMCC::AL).addReg(0)
7713       .addExternalSymbol("__chkstk")
7714       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7715       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7716       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7717     break;
7718   case CodeModel::Large:
7719   case CodeModel::JITDefault: {
7720     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7721     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7722
7723     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7724       .addExternalSymbol("__chkstk");
7725     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7726       .addImm((unsigned)ARMCC::AL).addReg(0)
7727       .addReg(Reg, RegState::Kill)
7728       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7729       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7730       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7731     break;
7732   }
7733   }
7734
7735   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7736                                       ARM::SP)
7737                               .addReg(ARM::SP).addReg(ARM::R4)));
7738
7739   MI->eraseFromParent();
7740   return MBB;
7741 }
7742
7743 MachineBasicBlock *
7744 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7745                                                MachineBasicBlock *BB) const {
7746   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7747   DebugLoc dl = MI->getDebugLoc();
7748   bool isThumb2 = Subtarget->isThumb2();
7749   switch (MI->getOpcode()) {
7750   default: {
7751     MI->dump();
7752     llvm_unreachable("Unexpected instr type to insert");
7753   }
7754   // The Thumb2 pre-indexed stores have the same MI operands, they just
7755   // define them differently in the .td files from the isel patterns, so
7756   // they need pseudos.
7757   case ARM::t2STR_preidx:
7758     MI->setDesc(TII->get(ARM::t2STR_PRE));
7759     return BB;
7760   case ARM::t2STRB_preidx:
7761     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7762     return BB;
7763   case ARM::t2STRH_preidx:
7764     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7765     return BB;
7766
7767   case ARM::STRi_preidx:
7768   case ARM::STRBi_preidx: {
7769     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7770       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7771     // Decode the offset.
7772     unsigned Offset = MI->getOperand(4).getImm();
7773     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7774     Offset = ARM_AM::getAM2Offset(Offset);
7775     if (isSub)
7776       Offset = -Offset;
7777
7778     MachineMemOperand *MMO = *MI->memoperands_begin();
7779     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7780       .addOperand(MI->getOperand(0))  // Rn_wb
7781       .addOperand(MI->getOperand(1))  // Rt
7782       .addOperand(MI->getOperand(2))  // Rn
7783       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7784       .addOperand(MI->getOperand(5))  // pred
7785       .addOperand(MI->getOperand(6))
7786       .addMemOperand(MMO);
7787     MI->eraseFromParent();
7788     return BB;
7789   }
7790   case ARM::STRr_preidx:
7791   case ARM::STRBr_preidx:
7792   case ARM::STRH_preidx: {
7793     unsigned NewOpc;
7794     switch (MI->getOpcode()) {
7795     default: llvm_unreachable("unexpected opcode!");
7796     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7797     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7798     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7799     }
7800     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7801     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7802       MIB.addOperand(MI->getOperand(i));
7803     MI->eraseFromParent();
7804     return BB;
7805   }
7806
7807   case ARM::tMOVCCr_pseudo: {
7808     // To "insert" a SELECT_CC instruction, we actually have to insert the
7809     // diamond control-flow pattern.  The incoming instruction knows the
7810     // destination vreg to set, the condition code register to branch on, the
7811     // true/false values to select between, and a branch opcode to use.
7812     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7813     MachineFunction::iterator It = BB;
7814     ++It;
7815
7816     //  thisMBB:
7817     //  ...
7818     //   TrueVal = ...
7819     //   cmpTY ccX, r1, r2
7820     //   bCC copy1MBB
7821     //   fallthrough --> copy0MBB
7822     MachineBasicBlock *thisMBB  = BB;
7823     MachineFunction *F = BB->getParent();
7824     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7825     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7826     F->insert(It, copy0MBB);
7827     F->insert(It, sinkMBB);
7828
7829     // Transfer the remainder of BB and its successor edges to sinkMBB.
7830     sinkMBB->splice(sinkMBB->begin(), BB,
7831                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7832     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7833
7834     BB->addSuccessor(copy0MBB);
7835     BB->addSuccessor(sinkMBB);
7836
7837     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7838       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7839
7840     //  copy0MBB:
7841     //   %FalseValue = ...
7842     //   # fallthrough to sinkMBB
7843     BB = copy0MBB;
7844
7845     // Update machine-CFG edges
7846     BB->addSuccessor(sinkMBB);
7847
7848     //  sinkMBB:
7849     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7850     //  ...
7851     BB = sinkMBB;
7852     BuildMI(*BB, BB->begin(), dl,
7853             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7854       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7855       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7856
7857     MI->eraseFromParent();   // The pseudo instruction is gone now.
7858     return BB;
7859   }
7860
7861   case ARM::BCCi64:
7862   case ARM::BCCZi64: {
7863     // If there is an unconditional branch to the other successor, remove it.
7864     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7865
7866     // Compare both parts that make up the double comparison separately for
7867     // equality.
7868     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7869
7870     unsigned LHS1 = MI->getOperand(1).getReg();
7871     unsigned LHS2 = MI->getOperand(2).getReg();
7872     if (RHSisZero) {
7873       AddDefaultPred(BuildMI(BB, dl,
7874                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7875                      .addReg(LHS1).addImm(0));
7876       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7877         .addReg(LHS2).addImm(0)
7878         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7879     } else {
7880       unsigned RHS1 = MI->getOperand(3).getReg();
7881       unsigned RHS2 = MI->getOperand(4).getReg();
7882       AddDefaultPred(BuildMI(BB, dl,
7883                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7884                      .addReg(LHS1).addReg(RHS1));
7885       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7886         .addReg(LHS2).addReg(RHS2)
7887         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7888     }
7889
7890     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7891     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7892     if (MI->getOperand(0).getImm() == ARMCC::NE)
7893       std::swap(destMBB, exitMBB);
7894
7895     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7896       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7897     if (isThumb2)
7898       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7899     else
7900       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7901
7902     MI->eraseFromParent();   // The pseudo instruction is gone now.
7903     return BB;
7904   }
7905
7906   case ARM::Int_eh_sjlj_setjmp:
7907   case ARM::Int_eh_sjlj_setjmp_nofp:
7908   case ARM::tInt_eh_sjlj_setjmp:
7909   case ARM::t2Int_eh_sjlj_setjmp:
7910   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7911     return BB;
7912
7913   case ARM::Int_eh_sjlj_setup_dispatch:
7914     EmitSjLjDispatchBlock(MI, BB);
7915     return BB;
7916
7917   case ARM::ABS:
7918   case ARM::t2ABS: {
7919     // To insert an ABS instruction, we have to insert the
7920     // diamond control-flow pattern.  The incoming instruction knows the
7921     // source vreg to test against 0, the destination vreg to set,
7922     // the condition code register to branch on, the
7923     // true/false values to select between, and a branch opcode to use.
7924     // It transforms
7925     //     V1 = ABS V0
7926     // into
7927     //     V2 = MOVS V0
7928     //     BCC                      (branch to SinkBB if V0 >= 0)
7929     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7930     //     SinkBB: V1 = PHI(V2, V3)
7931     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7932     MachineFunction::iterator BBI = BB;
7933     ++BBI;
7934     MachineFunction *Fn = BB->getParent();
7935     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7936     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7937     Fn->insert(BBI, RSBBB);
7938     Fn->insert(BBI, SinkBB);
7939
7940     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7941     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7942     bool ABSSrcKIll = MI->getOperand(1).isKill();
7943     bool isThumb2 = Subtarget->isThumb2();
7944     MachineRegisterInfo &MRI = Fn->getRegInfo();
7945     // In Thumb mode S must not be specified if source register is the SP or
7946     // PC and if destination register is the SP, so restrict register class
7947     unsigned NewRsbDstReg =
7948       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7949
7950     // Transfer the remainder of BB and its successor edges to sinkMBB.
7951     SinkBB->splice(SinkBB->begin(), BB,
7952                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7953     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7954
7955     BB->addSuccessor(RSBBB);
7956     BB->addSuccessor(SinkBB);
7957
7958     // fall through to SinkMBB
7959     RSBBB->addSuccessor(SinkBB);
7960
7961     // insert a cmp at the end of BB
7962     AddDefaultPred(BuildMI(BB, dl,
7963                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7964                    .addReg(ABSSrcReg).addImm(0));
7965
7966     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7967     BuildMI(BB, dl,
7968       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7969       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7970
7971     // insert rsbri in RSBBB
7972     // Note: BCC and rsbri will be converted into predicated rsbmi
7973     // by if-conversion pass
7974     BuildMI(*RSBBB, RSBBB->begin(), dl,
7975       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7976       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7977       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7978
7979     // insert PHI in SinkBB,
7980     // reuse ABSDstReg to not change uses of ABS instruction
7981     BuildMI(*SinkBB, SinkBB->begin(), dl,
7982       TII->get(ARM::PHI), ABSDstReg)
7983       .addReg(NewRsbDstReg).addMBB(RSBBB)
7984       .addReg(ABSSrcReg).addMBB(BB);
7985
7986     // remove ABS instruction
7987     MI->eraseFromParent();
7988
7989     // return last added BB
7990     return SinkBB;
7991   }
7992   case ARM::COPY_STRUCT_BYVAL_I32:
7993     ++NumLoopByVals;
7994     return EmitStructByval(MI, BB);
7995   case ARM::WIN__CHKSTK:
7996     return EmitLowered__chkstk(MI, BB);
7997   }
7998 }
7999
8000 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8001                                                       SDNode *Node) const {
8002   const MCInstrDesc *MCID = &MI->getDesc();
8003   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8004   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8005   // operand is still set to noreg. If needed, set the optional operand's
8006   // register to CPSR, and remove the redundant implicit def.
8007   //
8008   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8009
8010   // Rename pseudo opcodes.
8011   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8012   if (NewOpc) {
8013     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8014     MCID = &TII->get(NewOpc);
8015
8016     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8017            "converted opcode should be the same except for cc_out");
8018
8019     MI->setDesc(*MCID);
8020
8021     // Add the optional cc_out operand
8022     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8023   }
8024   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8025
8026   // Any ARM instruction that sets the 's' bit should specify an optional
8027   // "cc_out" operand in the last operand position.
8028   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8029     assert(!NewOpc && "Optional cc_out operand required");
8030     return;
8031   }
8032   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8033   // since we already have an optional CPSR def.
8034   bool definesCPSR = false;
8035   bool deadCPSR = false;
8036   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8037        i != e; ++i) {
8038     const MachineOperand &MO = MI->getOperand(i);
8039     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8040       definesCPSR = true;
8041       if (MO.isDead())
8042         deadCPSR = true;
8043       MI->RemoveOperand(i);
8044       break;
8045     }
8046   }
8047   if (!definesCPSR) {
8048     assert(!NewOpc && "Optional cc_out operand required");
8049     return;
8050   }
8051   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8052   if (deadCPSR) {
8053     assert(!MI->getOperand(ccOutIdx).getReg() &&
8054            "expect uninitialized optional cc_out operand");
8055     return;
8056   }
8057
8058   // If this instruction was defined with an optional CPSR def and its dag node
8059   // had a live implicit CPSR def, then activate the optional CPSR def.
8060   MachineOperand &MO = MI->getOperand(ccOutIdx);
8061   MO.setReg(ARM::CPSR);
8062   MO.setIsDef(true);
8063 }
8064
8065 //===----------------------------------------------------------------------===//
8066 //                           ARM Optimization Hooks
8067 //===----------------------------------------------------------------------===//
8068
8069 // Helper function that checks if N is a null or all ones constant.
8070 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8071   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8072   if (!C)
8073     return false;
8074   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8075 }
8076
8077 // Return true if N is conditionally 0 or all ones.
8078 // Detects these expressions where cc is an i1 value:
8079 //
8080 //   (select cc 0, y)   [AllOnes=0]
8081 //   (select cc y, 0)   [AllOnes=0]
8082 //   (zext cc)          [AllOnes=0]
8083 //   (sext cc)          [AllOnes=0/1]
8084 //   (select cc -1, y)  [AllOnes=1]
8085 //   (select cc y, -1)  [AllOnes=1]
8086 //
8087 // Invert is set when N is the null/all ones constant when CC is false.
8088 // OtherOp is set to the alternative value of N.
8089 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8090                                        SDValue &CC, bool &Invert,
8091                                        SDValue &OtherOp,
8092                                        SelectionDAG &DAG) {
8093   switch (N->getOpcode()) {
8094   default: return false;
8095   case ISD::SELECT: {
8096     CC = N->getOperand(0);
8097     SDValue N1 = N->getOperand(1);
8098     SDValue N2 = N->getOperand(2);
8099     if (isZeroOrAllOnes(N1, AllOnes)) {
8100       Invert = false;
8101       OtherOp = N2;
8102       return true;
8103     }
8104     if (isZeroOrAllOnes(N2, AllOnes)) {
8105       Invert = true;
8106       OtherOp = N1;
8107       return true;
8108     }
8109     return false;
8110   }
8111   case ISD::ZERO_EXTEND:
8112     // (zext cc) can never be the all ones value.
8113     if (AllOnes)
8114       return false;
8115     // Fall through.
8116   case ISD::SIGN_EXTEND: {
8117     SDLoc dl(N);
8118     EVT VT = N->getValueType(0);
8119     CC = N->getOperand(0);
8120     if (CC.getValueType() != MVT::i1)
8121       return false;
8122     Invert = !AllOnes;
8123     if (AllOnes)
8124       // When looking for an AllOnes constant, N is an sext, and the 'other'
8125       // value is 0.
8126       OtherOp = DAG.getConstant(0, dl, VT);
8127     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8128       // When looking for a 0 constant, N can be zext or sext.
8129       OtherOp = DAG.getConstant(1, dl, VT);
8130     else
8131       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8132                                 VT);
8133     return true;
8134   }
8135   }
8136 }
8137
8138 // Combine a constant select operand into its use:
8139 //
8140 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8141 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8142 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8143 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8144 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8145 //
8146 // The transform is rejected if the select doesn't have a constant operand that
8147 // is null, or all ones when AllOnes is set.
8148 //
8149 // Also recognize sext/zext from i1:
8150 //
8151 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8152 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8153 //
8154 // These transformations eventually create predicated instructions.
8155 //
8156 // @param N       The node to transform.
8157 // @param Slct    The N operand that is a select.
8158 // @param OtherOp The other N operand (x above).
8159 // @param DCI     Context.
8160 // @param AllOnes Require the select constant to be all ones instead of null.
8161 // @returns The new node, or SDValue() on failure.
8162 static
8163 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8164                             TargetLowering::DAGCombinerInfo &DCI,
8165                             bool AllOnes = false) {
8166   SelectionDAG &DAG = DCI.DAG;
8167   EVT VT = N->getValueType(0);
8168   SDValue NonConstantVal;
8169   SDValue CCOp;
8170   bool SwapSelectOps;
8171   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8172                                   NonConstantVal, DAG))
8173     return SDValue();
8174
8175   // Slct is now know to be the desired identity constant when CC is true.
8176   SDValue TrueVal = OtherOp;
8177   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8178                                  OtherOp, NonConstantVal);
8179   // Unless SwapSelectOps says CC should be false.
8180   if (SwapSelectOps)
8181     std::swap(TrueVal, FalseVal);
8182
8183   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8184                      CCOp, TrueVal, FalseVal);
8185 }
8186
8187 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8188 static
8189 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8190                                        TargetLowering::DAGCombinerInfo &DCI) {
8191   SDValue N0 = N->getOperand(0);
8192   SDValue N1 = N->getOperand(1);
8193   if (N0.getNode()->hasOneUse()) {
8194     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8195     if (Result.getNode())
8196       return Result;
8197   }
8198   if (N1.getNode()->hasOneUse()) {
8199     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8200     if (Result.getNode())
8201       return Result;
8202   }
8203   return SDValue();
8204 }
8205
8206 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8207 // (only after legalization).
8208 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8209                                  TargetLowering::DAGCombinerInfo &DCI,
8210                                  const ARMSubtarget *Subtarget) {
8211
8212   // Only perform optimization if after legalize, and if NEON is available. We
8213   // also expected both operands to be BUILD_VECTORs.
8214   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8215       || N0.getOpcode() != ISD::BUILD_VECTOR
8216       || N1.getOpcode() != ISD::BUILD_VECTOR)
8217     return SDValue();
8218
8219   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8220   EVT VT = N->getValueType(0);
8221   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8222     return SDValue();
8223
8224   // Check that the vector operands are of the right form.
8225   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8226   // operands, where N is the size of the formed vector.
8227   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8228   // index such that we have a pair wise add pattern.
8229
8230   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8231   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8232     return SDValue();
8233   SDValue Vec = N0->getOperand(0)->getOperand(0);
8234   SDNode *V = Vec.getNode();
8235   unsigned nextIndex = 0;
8236
8237   // For each operands to the ADD which are BUILD_VECTORs,
8238   // check to see if each of their operands are an EXTRACT_VECTOR with
8239   // the same vector and appropriate index.
8240   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8241     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8242         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8243
8244       SDValue ExtVec0 = N0->getOperand(i);
8245       SDValue ExtVec1 = N1->getOperand(i);
8246
8247       // First operand is the vector, verify its the same.
8248       if (V != ExtVec0->getOperand(0).getNode() ||
8249           V != ExtVec1->getOperand(0).getNode())
8250         return SDValue();
8251
8252       // Second is the constant, verify its correct.
8253       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8254       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8255
8256       // For the constant, we want to see all the even or all the odd.
8257       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8258           || C1->getZExtValue() != nextIndex+1)
8259         return SDValue();
8260
8261       // Increment index.
8262       nextIndex+=2;
8263     } else
8264       return SDValue();
8265   }
8266
8267   // Create VPADDL node.
8268   SelectionDAG &DAG = DCI.DAG;
8269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8270
8271   SDLoc dl(N);
8272
8273   // Build operand list.
8274   SmallVector<SDValue, 8> Ops;
8275   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8276                                 TLI.getPointerTy(DAG.getDataLayout())));
8277
8278   // Input is the vector.
8279   Ops.push_back(Vec);
8280
8281   // Get widened type and narrowed type.
8282   MVT widenType;
8283   unsigned numElem = VT.getVectorNumElements();
8284   
8285   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8286   switch (inputLaneType.getSimpleVT().SimpleTy) {
8287     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8288     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8289     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8290     default:
8291       llvm_unreachable("Invalid vector element type for padd optimization.");
8292   }
8293
8294   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8295   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8296   return DAG.getNode(ExtOp, dl, VT, tmp);
8297 }
8298
8299 static SDValue findMUL_LOHI(SDValue V) {
8300   if (V->getOpcode() == ISD::UMUL_LOHI ||
8301       V->getOpcode() == ISD::SMUL_LOHI)
8302     return V;
8303   return SDValue();
8304 }
8305
8306 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8307                                      TargetLowering::DAGCombinerInfo &DCI,
8308                                      const ARMSubtarget *Subtarget) {
8309
8310   if (Subtarget->isThumb1Only()) return SDValue();
8311
8312   // Only perform the checks after legalize when the pattern is available.
8313   if (DCI.isBeforeLegalize()) return SDValue();
8314
8315   // Look for multiply add opportunities.
8316   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8317   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8318   // a glue link from the first add to the second add.
8319   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8320   // a S/UMLAL instruction.
8321   //                  UMUL_LOHI
8322   //                 / :lo    \ :hi
8323   //                /          \          [no multiline comment]
8324   //    loAdd ->  ADDE         |
8325   //                 \ :glue  /
8326   //                  \      /
8327   //                    ADDC   <- hiAdd
8328   //
8329   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8330   SDValue AddcOp0 = AddcNode->getOperand(0);
8331   SDValue AddcOp1 = AddcNode->getOperand(1);
8332
8333   // Check if the two operands are from the same mul_lohi node.
8334   if (AddcOp0.getNode() == AddcOp1.getNode())
8335     return SDValue();
8336
8337   assert(AddcNode->getNumValues() == 2 &&
8338          AddcNode->getValueType(0) == MVT::i32 &&
8339          "Expect ADDC with two result values. First: i32");
8340
8341   // Check that we have a glued ADDC node.
8342   if (AddcNode->getValueType(1) != MVT::Glue)
8343     return SDValue();
8344
8345   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8346   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8347       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8348       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8349       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8350     return SDValue();
8351
8352   // Look for the glued ADDE.
8353   SDNode* AddeNode = AddcNode->getGluedUser();
8354   if (!AddeNode)
8355     return SDValue();
8356
8357   // Make sure it is really an ADDE.
8358   if (AddeNode->getOpcode() != ISD::ADDE)
8359     return SDValue();
8360
8361   assert(AddeNode->getNumOperands() == 3 &&
8362          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8363          "ADDE node has the wrong inputs");
8364
8365   // Check for the triangle shape.
8366   SDValue AddeOp0 = AddeNode->getOperand(0);
8367   SDValue AddeOp1 = AddeNode->getOperand(1);
8368
8369   // Make sure that the ADDE operands are not coming from the same node.
8370   if (AddeOp0.getNode() == AddeOp1.getNode())
8371     return SDValue();
8372
8373   // Find the MUL_LOHI node walking up ADDE's operands.
8374   bool IsLeftOperandMUL = false;
8375   SDValue MULOp = findMUL_LOHI(AddeOp0);
8376   if (MULOp == SDValue())
8377    MULOp = findMUL_LOHI(AddeOp1);
8378   else
8379     IsLeftOperandMUL = true;
8380   if (MULOp == SDValue())
8381     return SDValue();
8382
8383   // Figure out the right opcode.
8384   unsigned Opc = MULOp->getOpcode();
8385   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8386
8387   // Figure out the high and low input values to the MLAL node.
8388   SDValue* HiAdd = nullptr;
8389   SDValue* LoMul = nullptr;
8390   SDValue* LowAdd = nullptr;
8391
8392   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8393   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8394     return SDValue();
8395
8396   if (IsLeftOperandMUL)
8397     HiAdd = &AddeOp1;
8398   else
8399     HiAdd = &AddeOp0;
8400
8401
8402   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8403   // whose low result is fed to the ADDC we are checking.
8404
8405   if (AddcOp0 == MULOp.getValue(0)) {
8406     LoMul = &AddcOp0;
8407     LowAdd = &AddcOp1;
8408   }
8409   if (AddcOp1 == MULOp.getValue(0)) {
8410     LoMul = &AddcOp1;
8411     LowAdd = &AddcOp0;
8412   }
8413
8414   if (!LoMul)
8415     return SDValue();
8416
8417   // Create the merged node.
8418   SelectionDAG &DAG = DCI.DAG;
8419
8420   // Build operand list.
8421   SmallVector<SDValue, 8> Ops;
8422   Ops.push_back(LoMul->getOperand(0));
8423   Ops.push_back(LoMul->getOperand(1));
8424   Ops.push_back(*LowAdd);
8425   Ops.push_back(*HiAdd);
8426
8427   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8428                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8429
8430   // Replace the ADDs' nodes uses by the MLA node's values.
8431   SDValue HiMLALResult(MLALNode.getNode(), 1);
8432   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8433
8434   SDValue LoMLALResult(MLALNode.getNode(), 0);
8435   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8436
8437   // Return original node to notify the driver to stop replacing.
8438   SDValue resNode(AddcNode, 0);
8439   return resNode;
8440 }
8441
8442 /// PerformADDCCombine - Target-specific dag combine transform from
8443 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8444 static SDValue PerformADDCCombine(SDNode *N,
8445                                  TargetLowering::DAGCombinerInfo &DCI,
8446                                  const ARMSubtarget *Subtarget) {
8447
8448   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8449
8450 }
8451
8452 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8453 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8454 /// called with the default operands, and if that fails, with commuted
8455 /// operands.
8456 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8457                                           TargetLowering::DAGCombinerInfo &DCI,
8458                                           const ARMSubtarget *Subtarget){
8459
8460   // Attempt to create vpaddl for this add.
8461   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8462   if (Result.getNode())
8463     return Result;
8464
8465   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8466   if (N0.getNode()->hasOneUse()) {
8467     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8468     if (Result.getNode()) return Result;
8469   }
8470   return SDValue();
8471 }
8472
8473 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8474 ///
8475 static SDValue PerformADDCombine(SDNode *N,
8476                                  TargetLowering::DAGCombinerInfo &DCI,
8477                                  const ARMSubtarget *Subtarget) {
8478   SDValue N0 = N->getOperand(0);
8479   SDValue N1 = N->getOperand(1);
8480
8481   // First try with the default operand order.
8482   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8483   if (Result.getNode())
8484     return Result;
8485
8486   // If that didn't work, try again with the operands commuted.
8487   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8488 }
8489
8490 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8491 ///
8492 static SDValue PerformSUBCombine(SDNode *N,
8493                                  TargetLowering::DAGCombinerInfo &DCI) {
8494   SDValue N0 = N->getOperand(0);
8495   SDValue N1 = N->getOperand(1);
8496
8497   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8498   if (N1.getNode()->hasOneUse()) {
8499     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8500     if (Result.getNode()) return Result;
8501   }
8502
8503   return SDValue();
8504 }
8505
8506 /// PerformVMULCombine
8507 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8508 /// special multiplier accumulator forwarding.
8509 ///   vmul d3, d0, d2
8510 ///   vmla d3, d1, d2
8511 /// is faster than
8512 ///   vadd d3, d0, d1
8513 ///   vmul d3, d3, d2
8514 //  However, for (A + B) * (A + B),
8515 //    vadd d2, d0, d1
8516 //    vmul d3, d0, d2
8517 //    vmla d3, d1, d2
8518 //  is slower than
8519 //    vadd d2, d0, d1
8520 //    vmul d3, d2, d2
8521 static SDValue PerformVMULCombine(SDNode *N,
8522                                   TargetLowering::DAGCombinerInfo &DCI,
8523                                   const ARMSubtarget *Subtarget) {
8524   if (!Subtarget->hasVMLxForwarding())
8525     return SDValue();
8526
8527   SelectionDAG &DAG = DCI.DAG;
8528   SDValue N0 = N->getOperand(0);
8529   SDValue N1 = N->getOperand(1);
8530   unsigned Opcode = N0.getOpcode();
8531   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8532       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8533     Opcode = N1.getOpcode();
8534     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8535         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8536       return SDValue();
8537     std::swap(N0, N1);
8538   }
8539
8540   if (N0 == N1)
8541     return SDValue();
8542
8543   EVT VT = N->getValueType(0);
8544   SDLoc DL(N);
8545   SDValue N00 = N0->getOperand(0);
8546   SDValue N01 = N0->getOperand(1);
8547   return DAG.getNode(Opcode, DL, VT,
8548                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8549                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8550 }
8551
8552 static SDValue PerformMULCombine(SDNode *N,
8553                                  TargetLowering::DAGCombinerInfo &DCI,
8554                                  const ARMSubtarget *Subtarget) {
8555   SelectionDAG &DAG = DCI.DAG;
8556
8557   if (Subtarget->isThumb1Only())
8558     return SDValue();
8559
8560   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8561     return SDValue();
8562
8563   EVT VT = N->getValueType(0);
8564   if (VT.is64BitVector() || VT.is128BitVector())
8565     return PerformVMULCombine(N, DCI, Subtarget);
8566   if (VT != MVT::i32)
8567     return SDValue();
8568
8569   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8570   if (!C)
8571     return SDValue();
8572
8573   int64_t MulAmt = C->getSExtValue();
8574   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8575
8576   ShiftAmt = ShiftAmt & (32 - 1);
8577   SDValue V = N->getOperand(0);
8578   SDLoc DL(N);
8579
8580   SDValue Res;
8581   MulAmt >>= ShiftAmt;
8582
8583   if (MulAmt >= 0) {
8584     if (isPowerOf2_32(MulAmt - 1)) {
8585       // (mul x, 2^N + 1) => (add (shl x, N), x)
8586       Res = DAG.getNode(ISD::ADD, DL, VT,
8587                         V,
8588                         DAG.getNode(ISD::SHL, DL, VT,
8589                                     V,
8590                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8591                                                     MVT::i32)));
8592     } else if (isPowerOf2_32(MulAmt + 1)) {
8593       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8594       Res = DAG.getNode(ISD::SUB, DL, VT,
8595                         DAG.getNode(ISD::SHL, DL, VT,
8596                                     V,
8597                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8598                                                     MVT::i32)),
8599                         V);
8600     } else
8601       return SDValue();
8602   } else {
8603     uint64_t MulAmtAbs = -MulAmt;
8604     if (isPowerOf2_32(MulAmtAbs + 1)) {
8605       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8606       Res = DAG.getNode(ISD::SUB, DL, VT,
8607                         V,
8608                         DAG.getNode(ISD::SHL, DL, VT,
8609                                     V,
8610                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8611                                                     MVT::i32)));
8612     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8613       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8614       Res = DAG.getNode(ISD::ADD, DL, VT,
8615                         V,
8616                         DAG.getNode(ISD::SHL, DL, VT,
8617                                     V,
8618                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8619                                                     MVT::i32)));
8620       Res = DAG.getNode(ISD::SUB, DL, VT,
8621                         DAG.getConstant(0, DL, MVT::i32), Res);
8622
8623     } else
8624       return SDValue();
8625   }
8626
8627   if (ShiftAmt != 0)
8628     Res = DAG.getNode(ISD::SHL, DL, VT,
8629                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8630
8631   // Do not add new nodes to DAG combiner worklist.
8632   DCI.CombineTo(N, Res, false);
8633   return SDValue();
8634 }
8635
8636 static SDValue PerformANDCombine(SDNode *N,
8637                                  TargetLowering::DAGCombinerInfo &DCI,
8638                                  const ARMSubtarget *Subtarget) {
8639
8640   // Attempt to use immediate-form VBIC
8641   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8642   SDLoc dl(N);
8643   EVT VT = N->getValueType(0);
8644   SelectionDAG &DAG = DCI.DAG;
8645
8646   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8647     return SDValue();
8648
8649   APInt SplatBits, SplatUndef;
8650   unsigned SplatBitSize;
8651   bool HasAnyUndefs;
8652   if (BVN &&
8653       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8654     if (SplatBitSize <= 64) {
8655       EVT VbicVT;
8656       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8657                                       SplatUndef.getZExtValue(), SplatBitSize,
8658                                       DAG, dl, VbicVT, VT.is128BitVector(),
8659                                       OtherModImm);
8660       if (Val.getNode()) {
8661         SDValue Input =
8662           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8663         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8664         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8665       }
8666     }
8667   }
8668
8669   if (!Subtarget->isThumb1Only()) {
8670     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8671     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8672     if (Result.getNode())
8673       return Result;
8674   }
8675
8676   return SDValue();
8677 }
8678
8679 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8680 static SDValue PerformORCombine(SDNode *N,
8681                                 TargetLowering::DAGCombinerInfo &DCI,
8682                                 const ARMSubtarget *Subtarget) {
8683   // Attempt to use immediate-form VORR
8684   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8685   SDLoc dl(N);
8686   EVT VT = N->getValueType(0);
8687   SelectionDAG &DAG = DCI.DAG;
8688
8689   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8690     return SDValue();
8691
8692   APInt SplatBits, SplatUndef;
8693   unsigned SplatBitSize;
8694   bool HasAnyUndefs;
8695   if (BVN && Subtarget->hasNEON() &&
8696       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8697     if (SplatBitSize <= 64) {
8698       EVT VorrVT;
8699       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8700                                       SplatUndef.getZExtValue(), SplatBitSize,
8701                                       DAG, dl, VorrVT, VT.is128BitVector(),
8702                                       OtherModImm);
8703       if (Val.getNode()) {
8704         SDValue Input =
8705           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8706         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8707         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8708       }
8709     }
8710   }
8711
8712   if (!Subtarget->isThumb1Only()) {
8713     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8714     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8715     if (Result.getNode())
8716       return Result;
8717   }
8718
8719   // The code below optimizes (or (and X, Y), Z).
8720   // The AND operand needs to have a single user to make these optimizations
8721   // profitable.
8722   SDValue N0 = N->getOperand(0);
8723   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8724     return SDValue();
8725   SDValue N1 = N->getOperand(1);
8726
8727   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8728   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8729       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8730     APInt SplatUndef;
8731     unsigned SplatBitSize;
8732     bool HasAnyUndefs;
8733
8734     APInt SplatBits0, SplatBits1;
8735     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8736     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8737     // Ensure that the second operand of both ands are constants
8738     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8739                                       HasAnyUndefs) && !HasAnyUndefs) {
8740         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8741                                           HasAnyUndefs) && !HasAnyUndefs) {
8742             // Ensure that the bit width of the constants are the same and that
8743             // the splat arguments are logical inverses as per the pattern we
8744             // are trying to simplify.
8745             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8746                 SplatBits0 == ~SplatBits1) {
8747                 // Canonicalize the vector type to make instruction selection
8748                 // simpler.
8749                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8750                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8751                                              N0->getOperand(1),
8752                                              N0->getOperand(0),
8753                                              N1->getOperand(0));
8754                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8755             }
8756         }
8757     }
8758   }
8759
8760   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8761   // reasonable.
8762
8763   // BFI is only available on V6T2+
8764   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8765     return SDValue();
8766
8767   SDLoc DL(N);
8768   // 1) or (and A, mask), val => ARMbfi A, val, mask
8769   //      iff (val & mask) == val
8770   //
8771   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8772   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8773   //          && mask == ~mask2
8774   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8775   //          && ~mask == mask2
8776   //  (i.e., copy a bitfield value into another bitfield of the same width)
8777
8778   if (VT != MVT::i32)
8779     return SDValue();
8780
8781   SDValue N00 = N0.getOperand(0);
8782
8783   // The value and the mask need to be constants so we can verify this is
8784   // actually a bitfield set. If the mask is 0xffff, we can do better
8785   // via a movt instruction, so don't use BFI in that case.
8786   SDValue MaskOp = N0.getOperand(1);
8787   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8788   if (!MaskC)
8789     return SDValue();
8790   unsigned Mask = MaskC->getZExtValue();
8791   if (Mask == 0xffff)
8792     return SDValue();
8793   SDValue Res;
8794   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8796   if (N1C) {
8797     unsigned Val = N1C->getZExtValue();
8798     if ((Val & ~Mask) != Val)
8799       return SDValue();
8800
8801     if (ARM::isBitFieldInvertedMask(Mask)) {
8802       Val >>= countTrailingZeros(~Mask);
8803
8804       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8805                         DAG.getConstant(Val, DL, MVT::i32),
8806                         DAG.getConstant(Mask, DL, MVT::i32));
8807
8808       // Do not add new nodes to DAG combiner worklist.
8809       DCI.CombineTo(N, Res, false);
8810       return SDValue();
8811     }
8812   } else if (N1.getOpcode() == ISD::AND) {
8813     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8814     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8815     if (!N11C)
8816       return SDValue();
8817     unsigned Mask2 = N11C->getZExtValue();
8818
8819     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8820     // as is to match.
8821     if (ARM::isBitFieldInvertedMask(Mask) &&
8822         (Mask == ~Mask2)) {
8823       // The pack halfword instruction works better for masks that fit it,
8824       // so use that when it's available.
8825       if (Subtarget->hasT2ExtractPack() &&
8826           (Mask == 0xffff || Mask == 0xffff0000))
8827         return SDValue();
8828       // 2a
8829       unsigned amt = countTrailingZeros(Mask2);
8830       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8831                         DAG.getConstant(amt, DL, MVT::i32));
8832       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8833                         DAG.getConstant(Mask, DL, MVT::i32));
8834       // Do not add new nodes to DAG combiner worklist.
8835       DCI.CombineTo(N, Res, false);
8836       return SDValue();
8837     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8838                (~Mask == Mask2)) {
8839       // The pack halfword instruction works better for masks that fit it,
8840       // so use that when it's available.
8841       if (Subtarget->hasT2ExtractPack() &&
8842           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8843         return SDValue();
8844       // 2b
8845       unsigned lsb = countTrailingZeros(Mask);
8846       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8847                         DAG.getConstant(lsb, DL, MVT::i32));
8848       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8849                         DAG.getConstant(Mask2, DL, MVT::i32));
8850       // Do not add new nodes to DAG combiner worklist.
8851       DCI.CombineTo(N, Res, false);
8852       return SDValue();
8853     }
8854   }
8855
8856   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8857       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8858       ARM::isBitFieldInvertedMask(~Mask)) {
8859     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8860     // where lsb(mask) == #shamt and masked bits of B are known zero.
8861     SDValue ShAmt = N00.getOperand(1);
8862     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8863     unsigned LSB = countTrailingZeros(Mask);
8864     if (ShAmtC != LSB)
8865       return SDValue();
8866
8867     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8868                       DAG.getConstant(~Mask, DL, MVT::i32));
8869
8870     // Do not add new nodes to DAG combiner worklist.
8871     DCI.CombineTo(N, Res, false);
8872   }
8873
8874   return SDValue();
8875 }
8876
8877 static SDValue PerformXORCombine(SDNode *N,
8878                                  TargetLowering::DAGCombinerInfo &DCI,
8879                                  const ARMSubtarget *Subtarget) {
8880   EVT VT = N->getValueType(0);
8881   SelectionDAG &DAG = DCI.DAG;
8882
8883   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8884     return SDValue();
8885
8886   if (!Subtarget->isThumb1Only()) {
8887     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8888     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8889     if (Result.getNode())
8890       return Result;
8891   }
8892
8893   return SDValue();
8894 }
8895
8896 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8897 /// the bits being cleared by the AND are not demanded by the BFI.
8898 static SDValue PerformBFICombine(SDNode *N,
8899                                  TargetLowering::DAGCombinerInfo &DCI) {
8900   SDValue N1 = N->getOperand(1);
8901   if (N1.getOpcode() == ISD::AND) {
8902     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8903     if (!N11C)
8904       return SDValue();
8905     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8906     unsigned LSB = countTrailingZeros(~InvMask);
8907     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8908     assert(Width <
8909                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8910            "undefined behavior");
8911     unsigned Mask = (1u << Width) - 1;
8912     unsigned Mask2 = N11C->getZExtValue();
8913     if ((Mask & (~Mask2)) == 0)
8914       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8915                              N->getOperand(0), N1.getOperand(0),
8916                              N->getOperand(2));
8917   }
8918   return SDValue();
8919 }
8920
8921 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8922 /// ARMISD::VMOVRRD.
8923 static SDValue PerformVMOVRRDCombine(SDNode *N,
8924                                      TargetLowering::DAGCombinerInfo &DCI,
8925                                      const ARMSubtarget *Subtarget) {
8926   // vmovrrd(vmovdrr x, y) -> x,y
8927   SDValue InDouble = N->getOperand(0);
8928   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8929     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8930
8931   // vmovrrd(load f64) -> (load i32), (load i32)
8932   SDNode *InNode = InDouble.getNode();
8933   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8934       InNode->getValueType(0) == MVT::f64 &&
8935       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8936       !cast<LoadSDNode>(InNode)->isVolatile()) {
8937     // TODO: Should this be done for non-FrameIndex operands?
8938     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8939
8940     SelectionDAG &DAG = DCI.DAG;
8941     SDLoc DL(LD);
8942     SDValue BasePtr = LD->getBasePtr();
8943     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8944                                  LD->getPointerInfo(), LD->isVolatile(),
8945                                  LD->isNonTemporal(), LD->isInvariant(),
8946                                  LD->getAlignment());
8947
8948     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8949                                     DAG.getConstant(4, DL, MVT::i32));
8950     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8951                                  LD->getPointerInfo(), LD->isVolatile(),
8952                                  LD->isNonTemporal(), LD->isInvariant(),
8953                                  std::min(4U, LD->getAlignment() / 2));
8954
8955     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8956     if (DCI.DAG.getDataLayout().isBigEndian())
8957       std::swap (NewLD1, NewLD2);
8958     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8959     return Result;
8960   }
8961
8962   return SDValue();
8963 }
8964
8965 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8966 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8967 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8968   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8969   SDValue Op0 = N->getOperand(0);
8970   SDValue Op1 = N->getOperand(1);
8971   if (Op0.getOpcode() == ISD::BITCAST)
8972     Op0 = Op0.getOperand(0);
8973   if (Op1.getOpcode() == ISD::BITCAST)
8974     Op1 = Op1.getOperand(0);
8975   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8976       Op0.getNode() == Op1.getNode() &&
8977       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8978     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8979                        N->getValueType(0), Op0.getOperand(0));
8980   return SDValue();
8981 }
8982
8983 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8984 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8985 /// i64 vector to have f64 elements, since the value can then be loaded
8986 /// directly into a VFP register.
8987 static bool hasNormalLoadOperand(SDNode *N) {
8988   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8989   for (unsigned i = 0; i < NumElts; ++i) {
8990     SDNode *Elt = N->getOperand(i).getNode();
8991     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8992       return true;
8993   }
8994   return false;
8995 }
8996
8997 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8998 /// ISD::BUILD_VECTOR.
8999 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9000                                           TargetLowering::DAGCombinerInfo &DCI,
9001                                           const ARMSubtarget *Subtarget) {
9002   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9003   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9004   // into a pair of GPRs, which is fine when the value is used as a scalar,
9005   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9006   SelectionDAG &DAG = DCI.DAG;
9007   if (N->getNumOperands() == 2) {
9008     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9009     if (RV.getNode())
9010       return RV;
9011   }
9012
9013   // Load i64 elements as f64 values so that type legalization does not split
9014   // them up into i32 values.
9015   EVT VT = N->getValueType(0);
9016   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9017     return SDValue();
9018   SDLoc dl(N);
9019   SmallVector<SDValue, 8> Ops;
9020   unsigned NumElts = VT.getVectorNumElements();
9021   for (unsigned i = 0; i < NumElts; ++i) {
9022     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9023     Ops.push_back(V);
9024     // Make the DAGCombiner fold the bitcast.
9025     DCI.AddToWorklist(V.getNode());
9026   }
9027   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9028   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9029   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9030 }
9031
9032 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9033 static SDValue
9034 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9035   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9036   // At that time, we may have inserted bitcasts from integer to float.
9037   // If these bitcasts have survived DAGCombine, change the lowering of this
9038   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9039   // force to use floating point types.
9040
9041   // Make sure we can change the type of the vector.
9042   // This is possible iff:
9043   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9044   //    1.1. Vector is used only once.
9045   //    1.2. Use is a bit convert to an integer type.
9046   // 2. The size of its operands are 32-bits (64-bits are not legal).
9047   EVT VT = N->getValueType(0);
9048   EVT EltVT = VT.getVectorElementType();
9049
9050   // Check 1.1. and 2.
9051   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9052     return SDValue();
9053
9054   // By construction, the input type must be float.
9055   assert(EltVT == MVT::f32 && "Unexpected type!");
9056
9057   // Check 1.2.
9058   SDNode *Use = *N->use_begin();
9059   if (Use->getOpcode() != ISD::BITCAST ||
9060       Use->getValueType(0).isFloatingPoint())
9061     return SDValue();
9062
9063   // Check profitability.
9064   // Model is, if more than half of the relevant operands are bitcast from
9065   // i32, turn the build_vector into a sequence of insert_vector_elt.
9066   // Relevant operands are everything that is not statically
9067   // (i.e., at compile time) bitcasted.
9068   unsigned NumOfBitCastedElts = 0;
9069   unsigned NumElts = VT.getVectorNumElements();
9070   unsigned NumOfRelevantElts = NumElts;
9071   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9072     SDValue Elt = N->getOperand(Idx);
9073     if (Elt->getOpcode() == ISD::BITCAST) {
9074       // Assume only bit cast to i32 will go away.
9075       if (Elt->getOperand(0).getValueType() == MVT::i32)
9076         ++NumOfBitCastedElts;
9077     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9078       // Constants are statically casted, thus do not count them as
9079       // relevant operands.
9080       --NumOfRelevantElts;
9081   }
9082
9083   // Check if more than half of the elements require a non-free bitcast.
9084   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9085     return SDValue();
9086
9087   SelectionDAG &DAG = DCI.DAG;
9088   // Create the new vector type.
9089   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9090   // Check if the type is legal.
9091   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9092   if (!TLI.isTypeLegal(VecVT))
9093     return SDValue();
9094
9095   // Combine:
9096   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9097   // => BITCAST INSERT_VECTOR_ELT
9098   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9099   //                      (BITCAST EN), N.
9100   SDValue Vec = DAG.getUNDEF(VecVT);
9101   SDLoc dl(N);
9102   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9103     SDValue V = N->getOperand(Idx);
9104     if (V.getOpcode() == ISD::UNDEF)
9105       continue;
9106     if (V.getOpcode() == ISD::BITCAST &&
9107         V->getOperand(0).getValueType() == MVT::i32)
9108       // Fold obvious case.
9109       V = V.getOperand(0);
9110     else {
9111       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9112       // Make the DAGCombiner fold the bitcasts.
9113       DCI.AddToWorklist(V.getNode());
9114     }
9115     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9116     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9117   }
9118   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9119   // Make the DAGCombiner fold the bitcasts.
9120   DCI.AddToWorklist(Vec.getNode());
9121   return Vec;
9122 }
9123
9124 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9125 /// ISD::INSERT_VECTOR_ELT.
9126 static SDValue PerformInsertEltCombine(SDNode *N,
9127                                        TargetLowering::DAGCombinerInfo &DCI) {
9128   // Bitcast an i64 load inserted into a vector to f64.
9129   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9130   EVT VT = N->getValueType(0);
9131   SDNode *Elt = N->getOperand(1).getNode();
9132   if (VT.getVectorElementType() != MVT::i64 ||
9133       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9134     return SDValue();
9135
9136   SelectionDAG &DAG = DCI.DAG;
9137   SDLoc dl(N);
9138   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9139                                  VT.getVectorNumElements());
9140   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9141   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9142   // Make the DAGCombiner fold the bitcasts.
9143   DCI.AddToWorklist(Vec.getNode());
9144   DCI.AddToWorklist(V.getNode());
9145   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9146                                Vec, V, N->getOperand(2));
9147   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9148 }
9149
9150 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9151 /// ISD::VECTOR_SHUFFLE.
9152 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9153   // The LLVM shufflevector instruction does not require the shuffle mask
9154   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9155   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9156   // operands do not match the mask length, they are extended by concatenating
9157   // them with undef vectors.  That is probably the right thing for other
9158   // targets, but for NEON it is better to concatenate two double-register
9159   // size vector operands into a single quad-register size vector.  Do that
9160   // transformation here:
9161   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9162   //   shuffle(concat(v1, v2), undef)
9163   SDValue Op0 = N->getOperand(0);
9164   SDValue Op1 = N->getOperand(1);
9165   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9166       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9167       Op0.getNumOperands() != 2 ||
9168       Op1.getNumOperands() != 2)
9169     return SDValue();
9170   SDValue Concat0Op1 = Op0.getOperand(1);
9171   SDValue Concat1Op1 = Op1.getOperand(1);
9172   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9173       Concat1Op1.getOpcode() != ISD::UNDEF)
9174     return SDValue();
9175   // Skip the transformation if any of the types are illegal.
9176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9177   EVT VT = N->getValueType(0);
9178   if (!TLI.isTypeLegal(VT) ||
9179       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9180       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9181     return SDValue();
9182
9183   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9184                                   Op0.getOperand(0), Op1.getOperand(0));
9185   // Translate the shuffle mask.
9186   SmallVector<int, 16> NewMask;
9187   unsigned NumElts = VT.getVectorNumElements();
9188   unsigned HalfElts = NumElts/2;
9189   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9190   for (unsigned n = 0; n < NumElts; ++n) {
9191     int MaskElt = SVN->getMaskElt(n);
9192     int NewElt = -1;
9193     if (MaskElt < (int)HalfElts)
9194       NewElt = MaskElt;
9195     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9196       NewElt = HalfElts + MaskElt - NumElts;
9197     NewMask.push_back(NewElt);
9198   }
9199   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9200                               DAG.getUNDEF(VT), NewMask.data());
9201 }
9202
9203 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9204 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9205 /// base address updates.
9206 /// For generic load/stores, the memory type is assumed to be a vector.
9207 /// The caller is assumed to have checked legality.
9208 static SDValue CombineBaseUpdate(SDNode *N,
9209                                  TargetLowering::DAGCombinerInfo &DCI) {
9210   SelectionDAG &DAG = DCI.DAG;
9211   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9212                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9213   const bool isStore = N->getOpcode() == ISD::STORE;
9214   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9215   SDValue Addr = N->getOperand(AddrOpIdx);
9216   MemSDNode *MemN = cast<MemSDNode>(N);
9217   SDLoc dl(N);
9218
9219   // Search for a use of the address operand that is an increment.
9220   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9221          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9222     SDNode *User = *UI;
9223     if (User->getOpcode() != ISD::ADD ||
9224         UI.getUse().getResNo() != Addr.getResNo())
9225       continue;
9226
9227     // Check that the add is independent of the load/store.  Otherwise, folding
9228     // it would create a cycle.
9229     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9230       continue;
9231
9232     // Find the new opcode for the updating load/store.
9233     bool isLoadOp = true;
9234     bool isLaneOp = false;
9235     unsigned NewOpc = 0;
9236     unsigned NumVecs = 0;
9237     if (isIntrinsic) {
9238       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9239       switch (IntNo) {
9240       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9241       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9242         NumVecs = 1; break;
9243       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9244         NumVecs = 2; break;
9245       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9246         NumVecs = 3; break;
9247       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9248         NumVecs = 4; break;
9249       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9250         NumVecs = 2; isLaneOp = true; break;
9251       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9252         NumVecs = 3; isLaneOp = true; break;
9253       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9254         NumVecs = 4; isLaneOp = true; break;
9255       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9256         NumVecs = 1; isLoadOp = false; break;
9257       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9258         NumVecs = 2; isLoadOp = false; break;
9259       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9260         NumVecs = 3; isLoadOp = false; break;
9261       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9262         NumVecs = 4; isLoadOp = false; break;
9263       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9264         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9265       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9266         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9267       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9268         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9269       }
9270     } else {
9271       isLaneOp = true;
9272       switch (N->getOpcode()) {
9273       default: llvm_unreachable("unexpected opcode for Neon base update");
9274       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9275       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9276       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9277       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9278         NumVecs = 1; isLaneOp = false; break;
9279       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9280         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9281       }
9282     }
9283
9284     // Find the size of memory referenced by the load/store.
9285     EVT VecTy;
9286     if (isLoadOp) {
9287       VecTy = N->getValueType(0);
9288     } else if (isIntrinsic) {
9289       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9290     } else {
9291       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9292       VecTy = N->getOperand(1).getValueType();
9293     }
9294
9295     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9296     if (isLaneOp)
9297       NumBytes /= VecTy.getVectorNumElements();
9298
9299     // If the increment is a constant, it must match the memory ref size.
9300     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9301     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9302       uint64_t IncVal = CInc->getZExtValue();
9303       if (IncVal != NumBytes)
9304         continue;
9305     } else if (NumBytes >= 3 * 16) {
9306       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9307       // separate instructions that make it harder to use a non-constant update.
9308       continue;
9309     }
9310
9311     // OK, we found an ADD we can fold into the base update.
9312     // Now, create a _UPD node, taking care of not breaking alignment.
9313
9314     EVT AlignedVecTy = VecTy;
9315     unsigned Alignment = MemN->getAlignment();
9316
9317     // If this is a less-than-standard-aligned load/store, change the type to
9318     // match the standard alignment.
9319     // The alignment is overlooked when selecting _UPD variants; and it's
9320     // easier to introduce bitcasts here than fix that.
9321     // There are 3 ways to get to this base-update combine:
9322     // - intrinsics: they are assumed to be properly aligned (to the standard
9323     //   alignment of the memory type), so we don't need to do anything.
9324     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9325     //   intrinsics, so, likewise, there's nothing to do.
9326     // - generic load/store instructions: the alignment is specified as an
9327     //   explicit operand, rather than implicitly as the standard alignment
9328     //   of the memory type (like the intrisics).  We need to change the
9329     //   memory type to match the explicit alignment.  That way, we don't
9330     //   generate non-standard-aligned ARMISD::VLDx nodes.
9331     if (isa<LSBaseSDNode>(N)) {
9332       if (Alignment == 0)
9333         Alignment = 1;
9334       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9335         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9336         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9337         assert(!isLaneOp && "Unexpected generic load/store lane.");
9338         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9339         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9340       }
9341       // Don't set an explicit alignment on regular load/stores that we want
9342       // to transform to VLD/VST 1_UPD nodes.
9343       // This matches the behavior of regular load/stores, which only get an
9344       // explicit alignment if the MMO alignment is larger than the standard
9345       // alignment of the memory type.
9346       // Intrinsics, however, always get an explicit alignment, set to the
9347       // alignment of the MMO.
9348       Alignment = 1;
9349     }
9350
9351     // Create the new updating load/store node.
9352     // First, create an SDVTList for the new updating node's results.
9353     EVT Tys[6];
9354     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9355     unsigned n;
9356     for (n = 0; n < NumResultVecs; ++n)
9357       Tys[n] = AlignedVecTy;
9358     Tys[n++] = MVT::i32;
9359     Tys[n] = MVT::Other;
9360     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9361
9362     // Then, gather the new node's operands.
9363     SmallVector<SDValue, 8> Ops;
9364     Ops.push_back(N->getOperand(0)); // incoming chain
9365     Ops.push_back(N->getOperand(AddrOpIdx));
9366     Ops.push_back(Inc);
9367
9368     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9369       // Try to match the intrinsic's signature
9370       Ops.push_back(StN->getValue());
9371     } else {
9372       // Loads (and of course intrinsics) match the intrinsics' signature,
9373       // so just add all but the alignment operand.
9374       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9375         Ops.push_back(N->getOperand(i));
9376     }
9377
9378     // For all node types, the alignment operand is always the last one.
9379     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9380
9381     // If this is a non-standard-aligned STORE, the penultimate operand is the
9382     // stored value.  Bitcast it to the aligned type.
9383     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9384       SDValue &StVal = Ops[Ops.size()-2];
9385       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9386     }
9387
9388     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9389                                            Ops, AlignedVecTy,
9390                                            MemN->getMemOperand());
9391
9392     // Update the uses.
9393     SmallVector<SDValue, 5> NewResults;
9394     for (unsigned i = 0; i < NumResultVecs; ++i)
9395       NewResults.push_back(SDValue(UpdN.getNode(), i));
9396
9397     // If this is an non-standard-aligned LOAD, the first result is the loaded
9398     // value.  Bitcast it to the expected result type.
9399     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9400       SDValue &LdVal = NewResults[0];
9401       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9402     }
9403
9404     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9405     DCI.CombineTo(N, NewResults);
9406     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9407
9408     break;
9409   }
9410   return SDValue();
9411 }
9412
9413 static SDValue PerformVLDCombine(SDNode *N,
9414                                  TargetLowering::DAGCombinerInfo &DCI) {
9415   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9416     return SDValue();
9417
9418   return CombineBaseUpdate(N, DCI);
9419 }
9420
9421 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9422 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9423 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9424 /// return true.
9425 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9426   SelectionDAG &DAG = DCI.DAG;
9427   EVT VT = N->getValueType(0);
9428   // vldN-dup instructions only support 64-bit vectors for N > 1.
9429   if (!VT.is64BitVector())
9430     return false;
9431
9432   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9433   SDNode *VLD = N->getOperand(0).getNode();
9434   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9435     return false;
9436   unsigned NumVecs = 0;
9437   unsigned NewOpc = 0;
9438   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9439   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9440     NumVecs = 2;
9441     NewOpc = ARMISD::VLD2DUP;
9442   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9443     NumVecs = 3;
9444     NewOpc = ARMISD::VLD3DUP;
9445   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9446     NumVecs = 4;
9447     NewOpc = ARMISD::VLD4DUP;
9448   } else {
9449     return false;
9450   }
9451
9452   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9453   // numbers match the load.
9454   unsigned VLDLaneNo =
9455     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9456   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9457        UI != UE; ++UI) {
9458     // Ignore uses of the chain result.
9459     if (UI.getUse().getResNo() == NumVecs)
9460       continue;
9461     SDNode *User = *UI;
9462     if (User->getOpcode() != ARMISD::VDUPLANE ||
9463         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9464       return false;
9465   }
9466
9467   // Create the vldN-dup node.
9468   EVT Tys[5];
9469   unsigned n;
9470   for (n = 0; n < NumVecs; ++n)
9471     Tys[n] = VT;
9472   Tys[n] = MVT::Other;
9473   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9474   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9475   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9476   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9477                                            Ops, VLDMemInt->getMemoryVT(),
9478                                            VLDMemInt->getMemOperand());
9479
9480   // Update the uses.
9481   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9482        UI != UE; ++UI) {
9483     unsigned ResNo = UI.getUse().getResNo();
9484     // Ignore uses of the chain result.
9485     if (ResNo == NumVecs)
9486       continue;
9487     SDNode *User = *UI;
9488     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9489   }
9490
9491   // Now the vldN-lane intrinsic is dead except for its chain result.
9492   // Update uses of the chain.
9493   std::vector<SDValue> VLDDupResults;
9494   for (unsigned n = 0; n < NumVecs; ++n)
9495     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9496   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9497   DCI.CombineTo(VLD, VLDDupResults);
9498
9499   return true;
9500 }
9501
9502 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9503 /// ARMISD::VDUPLANE.
9504 static SDValue PerformVDUPLANECombine(SDNode *N,
9505                                       TargetLowering::DAGCombinerInfo &DCI) {
9506   SDValue Op = N->getOperand(0);
9507
9508   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9509   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9510   if (CombineVLDDUP(N, DCI))
9511     return SDValue(N, 0);
9512
9513   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9514   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9515   while (Op.getOpcode() == ISD::BITCAST)
9516     Op = Op.getOperand(0);
9517   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9518     return SDValue();
9519
9520   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9521   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9522   // The canonical VMOV for a zero vector uses a 32-bit element size.
9523   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9524   unsigned EltBits;
9525   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9526     EltSize = 8;
9527   EVT VT = N->getValueType(0);
9528   if (EltSize > VT.getVectorElementType().getSizeInBits())
9529     return SDValue();
9530
9531   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9532 }
9533
9534 static SDValue PerformLOADCombine(SDNode *N,
9535                                   TargetLowering::DAGCombinerInfo &DCI) {
9536   EVT VT = N->getValueType(0);
9537
9538   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9539   if (ISD::isNormalLoad(N) && VT.isVector() &&
9540       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9541     return CombineBaseUpdate(N, DCI);
9542
9543   return SDValue();
9544 }
9545
9546 /// PerformSTORECombine - Target-specific dag combine xforms for
9547 /// ISD::STORE.
9548 static SDValue PerformSTORECombine(SDNode *N,
9549                                    TargetLowering::DAGCombinerInfo &DCI) {
9550   StoreSDNode *St = cast<StoreSDNode>(N);
9551   if (St->isVolatile())
9552     return SDValue();
9553
9554   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9555   // pack all of the elements in one place.  Next, store to memory in fewer
9556   // chunks.
9557   SDValue StVal = St->getValue();
9558   EVT VT = StVal.getValueType();
9559   if (St->isTruncatingStore() && VT.isVector()) {
9560     SelectionDAG &DAG = DCI.DAG;
9561     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9562     EVT StVT = St->getMemoryVT();
9563     unsigned NumElems = VT.getVectorNumElements();
9564     assert(StVT != VT && "Cannot truncate to the same type");
9565     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9566     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9567
9568     // From, To sizes and ElemCount must be pow of two
9569     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9570
9571     // We are going to use the original vector elt for storing.
9572     // Accumulated smaller vector elements must be a multiple of the store size.
9573     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9574
9575     unsigned SizeRatio  = FromEltSz / ToEltSz;
9576     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9577
9578     // Create a type on which we perform the shuffle.
9579     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9580                                      NumElems*SizeRatio);
9581     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9582
9583     SDLoc DL(St);
9584     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9585     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9586     for (unsigned i = 0; i < NumElems; ++i)
9587       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9588                           ? (i + 1) * SizeRatio - 1
9589                           : i * SizeRatio;
9590
9591     // Can't shuffle using an illegal type.
9592     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9593
9594     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9595                                 DAG.getUNDEF(WideVec.getValueType()),
9596                                 ShuffleVec.data());
9597     // At this point all of the data is stored at the bottom of the
9598     // register. We now need to save it to mem.
9599
9600     // Find the largest store unit
9601     MVT StoreType = MVT::i8;
9602     for (MVT Tp : MVT::integer_valuetypes()) {
9603       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9604         StoreType = Tp;
9605     }
9606     // Didn't find a legal store type.
9607     if (!TLI.isTypeLegal(StoreType))
9608       return SDValue();
9609
9610     // Bitcast the original vector into a vector of store-size units
9611     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9612             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9613     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9614     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9615     SmallVector<SDValue, 8> Chains;
9616     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9617                                         TLI.getPointerTy(DAG.getDataLayout()));
9618     SDValue BasePtr = St->getBasePtr();
9619
9620     // Perform one or more big stores into memory.
9621     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9622     for (unsigned I = 0; I < E; I++) {
9623       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9624                                    StoreType, ShuffWide,
9625                                    DAG.getIntPtrConstant(I, DL));
9626       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9627                                 St->getPointerInfo(), St->isVolatile(),
9628                                 St->isNonTemporal(), St->getAlignment());
9629       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9630                             Increment);
9631       Chains.push_back(Ch);
9632     }
9633     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9634   }
9635
9636   if (!ISD::isNormalStore(St))
9637     return SDValue();
9638
9639   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9640   // ARM stores of arguments in the same cache line.
9641   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9642       StVal.getNode()->hasOneUse()) {
9643     SelectionDAG  &DAG = DCI.DAG;
9644     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9645     SDLoc DL(St);
9646     SDValue BasePtr = St->getBasePtr();
9647     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9648                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9649                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9650                                   St->isNonTemporal(), St->getAlignment());
9651
9652     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9653                                     DAG.getConstant(4, DL, MVT::i32));
9654     return DAG.getStore(NewST1.getValue(0), DL,
9655                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9656                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9657                         St->isNonTemporal(),
9658                         std::min(4U, St->getAlignment() / 2));
9659   }
9660
9661   if (StVal.getValueType() == MVT::i64 &&
9662       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9663
9664     // Bitcast an i64 store extracted from a vector to f64.
9665     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9666     SelectionDAG &DAG = DCI.DAG;
9667     SDLoc dl(StVal);
9668     SDValue IntVec = StVal.getOperand(0);
9669     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9670                                    IntVec.getValueType().getVectorNumElements());
9671     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9672     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9673                                  Vec, StVal.getOperand(1));
9674     dl = SDLoc(N);
9675     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9676     // Make the DAGCombiner fold the bitcasts.
9677     DCI.AddToWorklist(Vec.getNode());
9678     DCI.AddToWorklist(ExtElt.getNode());
9679     DCI.AddToWorklist(V.getNode());
9680     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9681                         St->getPointerInfo(), St->isVolatile(),
9682                         St->isNonTemporal(), St->getAlignment(),
9683                         St->getAAInfo());
9684   }
9685
9686   // If this is a legal vector store, try to combine it into a VST1_UPD.
9687   if (ISD::isNormalStore(N) && VT.isVector() &&
9688       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9689     return CombineBaseUpdate(N, DCI);
9690
9691   return SDValue();
9692 }
9693
9694 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9695 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9696 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9697 {
9698   integerPart cN;
9699   integerPart c0 = 0;
9700   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9701        I != E; I++) {
9702     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9703     if (!C)
9704       return false;
9705
9706     bool isExact;
9707     APFloat APF = C->getValueAPF();
9708     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9709         != APFloat::opOK || !isExact)
9710       return false;
9711
9712     c0 = (I == 0) ? cN : c0;
9713     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9714       return false;
9715   }
9716   C = c0;
9717   return true;
9718 }
9719
9720 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9721 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9722 /// when the VMUL has a constant operand that is a power of 2.
9723 ///
9724 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9725 ///  vmul.f32        d16, d17, d16
9726 ///  vcvt.s32.f32    d16, d16
9727 /// becomes:
9728 ///  vcvt.s32.f32    d16, d16, #3
9729 static SDValue PerformVCVTCombine(SDNode *N,
9730                                   TargetLowering::DAGCombinerInfo &DCI,
9731                                   const ARMSubtarget *Subtarget) {
9732   SelectionDAG &DAG = DCI.DAG;
9733   SDValue Op = N->getOperand(0);
9734
9735   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9736       Op.getOpcode() != ISD::FMUL)
9737     return SDValue();
9738
9739   uint64_t C;
9740   SDValue N0 = Op->getOperand(0);
9741   SDValue ConstVec = Op->getOperand(1);
9742   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9743
9744   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9745       !isConstVecPow2(ConstVec, isSigned, C))
9746     return SDValue();
9747
9748   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9749   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9750   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9751   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9752       NumLanes > 4) {
9753     // These instructions only exist converting from f32 to i32. We can handle
9754     // smaller integers by generating an extra truncate, but larger ones would
9755     // be lossy. We also can't handle more then 4 lanes, since these intructions
9756     // only support v2i32/v4i32 types.
9757     return SDValue();
9758   }
9759
9760   SDLoc dl(N);
9761   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9762     Intrinsic::arm_neon_vcvtfp2fxu;
9763   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9764                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9765                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9766                                  N0,
9767                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9768
9769   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9770     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9771
9772   return FixConv;
9773 }
9774
9775 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9776 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9777 /// when the VDIV has a constant operand that is a power of 2.
9778 ///
9779 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9780 ///  vcvt.f32.s32    d16, d16
9781 ///  vdiv.f32        d16, d17, d16
9782 /// becomes:
9783 ///  vcvt.f32.s32    d16, d16, #3
9784 static SDValue PerformVDIVCombine(SDNode *N,
9785                                   TargetLowering::DAGCombinerInfo &DCI,
9786                                   const ARMSubtarget *Subtarget) {
9787   SelectionDAG &DAG = DCI.DAG;
9788   SDValue Op = N->getOperand(0);
9789   unsigned OpOpcode = Op.getNode()->getOpcode();
9790
9791   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9792       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9793     return SDValue();
9794
9795   uint64_t C;
9796   SDValue ConstVec = N->getOperand(1);
9797   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9798
9799   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9800       !isConstVecPow2(ConstVec, isSigned, C))
9801     return SDValue();
9802
9803   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9804   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9805   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9806     // These instructions only exist converting from i32 to f32. We can handle
9807     // smaller integers by generating an extra extend, but larger ones would
9808     // be lossy.
9809     return SDValue();
9810   }
9811
9812   SDLoc dl(N);
9813   SDValue ConvInput = Op.getOperand(0);
9814   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9815   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9816     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9817                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9818                             ConvInput);
9819
9820   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9821     Intrinsic::arm_neon_vcvtfxu2fp;
9822   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9823                      Op.getValueType(),
9824                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9825                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9826 }
9827
9828 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9829 /// operand of a vector shift operation, where all the elements of the
9830 /// build_vector must have the same constant integer value.
9831 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9832   // Ignore bit_converts.
9833   while (Op.getOpcode() == ISD::BITCAST)
9834     Op = Op.getOperand(0);
9835   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9836   APInt SplatBits, SplatUndef;
9837   unsigned SplatBitSize;
9838   bool HasAnyUndefs;
9839   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9840                                       HasAnyUndefs, ElementBits) ||
9841       SplatBitSize > ElementBits)
9842     return false;
9843   Cnt = SplatBits.getSExtValue();
9844   return true;
9845 }
9846
9847 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9848 /// operand of a vector shift left operation.  That value must be in the range:
9849 ///   0 <= Value < ElementBits for a left shift; or
9850 ///   0 <= Value <= ElementBits for a long left shift.
9851 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9852   assert(VT.isVector() && "vector shift count is not a vector type");
9853   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9854   if (! getVShiftImm(Op, ElementBits, Cnt))
9855     return false;
9856   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9857 }
9858
9859 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9860 /// operand of a vector shift right operation.  For a shift opcode, the value
9861 /// is positive, but for an intrinsic the value count must be negative. The
9862 /// absolute value must be in the range:
9863 ///   1 <= |Value| <= ElementBits for a right shift; or
9864 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9865 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9866                          int64_t &Cnt) {
9867   assert(VT.isVector() && "vector shift count is not a vector type");
9868   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9869   if (! getVShiftImm(Op, ElementBits, Cnt))
9870     return false;
9871   if (!isIntrinsic)
9872     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9873   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9874     Cnt = -Cnt;
9875     return true;
9876   }
9877   return false;
9878 }
9879
9880 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9881 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9882   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9883   switch (IntNo) {
9884   default:
9885     // Don't do anything for most intrinsics.
9886     break;
9887
9888   case Intrinsic::arm_neon_vabds:
9889     if (!N->getValueType(0).isInteger())
9890       return SDValue();
9891     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9892                        N->getOperand(1), N->getOperand(2));
9893   case Intrinsic::arm_neon_vabdu:
9894     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9895                        N->getOperand(1), N->getOperand(2));
9896
9897   // Vector shifts: check for immediate versions and lower them.
9898   // Note: This is done during DAG combining instead of DAG legalizing because
9899   // the build_vectors for 64-bit vector element shift counts are generally
9900   // not legal, and it is hard to see their values after they get legalized to
9901   // loads from a constant pool.
9902   case Intrinsic::arm_neon_vshifts:
9903   case Intrinsic::arm_neon_vshiftu:
9904   case Intrinsic::arm_neon_vrshifts:
9905   case Intrinsic::arm_neon_vrshiftu:
9906   case Intrinsic::arm_neon_vrshiftn:
9907   case Intrinsic::arm_neon_vqshifts:
9908   case Intrinsic::arm_neon_vqshiftu:
9909   case Intrinsic::arm_neon_vqshiftsu:
9910   case Intrinsic::arm_neon_vqshiftns:
9911   case Intrinsic::arm_neon_vqshiftnu:
9912   case Intrinsic::arm_neon_vqshiftnsu:
9913   case Intrinsic::arm_neon_vqrshiftns:
9914   case Intrinsic::arm_neon_vqrshiftnu:
9915   case Intrinsic::arm_neon_vqrshiftnsu: {
9916     EVT VT = N->getOperand(1).getValueType();
9917     int64_t Cnt;
9918     unsigned VShiftOpc = 0;
9919
9920     switch (IntNo) {
9921     case Intrinsic::arm_neon_vshifts:
9922     case Intrinsic::arm_neon_vshiftu:
9923       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9924         VShiftOpc = ARMISD::VSHL;
9925         break;
9926       }
9927       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9928         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9929                      ARMISD::VSHRs : ARMISD::VSHRu);
9930         break;
9931       }
9932       return SDValue();
9933
9934     case Intrinsic::arm_neon_vrshifts:
9935     case Intrinsic::arm_neon_vrshiftu:
9936       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9937         break;
9938       return SDValue();
9939
9940     case Intrinsic::arm_neon_vqshifts:
9941     case Intrinsic::arm_neon_vqshiftu:
9942       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9943         break;
9944       return SDValue();
9945
9946     case Intrinsic::arm_neon_vqshiftsu:
9947       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9948         break;
9949       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9950
9951     case Intrinsic::arm_neon_vrshiftn:
9952     case Intrinsic::arm_neon_vqshiftns:
9953     case Intrinsic::arm_neon_vqshiftnu:
9954     case Intrinsic::arm_neon_vqshiftnsu:
9955     case Intrinsic::arm_neon_vqrshiftns:
9956     case Intrinsic::arm_neon_vqrshiftnu:
9957     case Intrinsic::arm_neon_vqrshiftnsu:
9958       // Narrowing shifts require an immediate right shift.
9959       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9960         break;
9961       llvm_unreachable("invalid shift count for narrowing vector shift "
9962                        "intrinsic");
9963
9964     default:
9965       llvm_unreachable("unhandled vector shift");
9966     }
9967
9968     switch (IntNo) {
9969     case Intrinsic::arm_neon_vshifts:
9970     case Intrinsic::arm_neon_vshiftu:
9971       // Opcode already set above.
9972       break;
9973     case Intrinsic::arm_neon_vrshifts:
9974       VShiftOpc = ARMISD::VRSHRs; break;
9975     case Intrinsic::arm_neon_vrshiftu:
9976       VShiftOpc = ARMISD::VRSHRu; break;
9977     case Intrinsic::arm_neon_vrshiftn:
9978       VShiftOpc = ARMISD::VRSHRN; break;
9979     case Intrinsic::arm_neon_vqshifts:
9980       VShiftOpc = ARMISD::VQSHLs; break;
9981     case Intrinsic::arm_neon_vqshiftu:
9982       VShiftOpc = ARMISD::VQSHLu; break;
9983     case Intrinsic::arm_neon_vqshiftsu:
9984       VShiftOpc = ARMISD::VQSHLsu; break;
9985     case Intrinsic::arm_neon_vqshiftns:
9986       VShiftOpc = ARMISD::VQSHRNs; break;
9987     case Intrinsic::arm_neon_vqshiftnu:
9988       VShiftOpc = ARMISD::VQSHRNu; break;
9989     case Intrinsic::arm_neon_vqshiftnsu:
9990       VShiftOpc = ARMISD::VQSHRNsu; break;
9991     case Intrinsic::arm_neon_vqrshiftns:
9992       VShiftOpc = ARMISD::VQRSHRNs; break;
9993     case Intrinsic::arm_neon_vqrshiftnu:
9994       VShiftOpc = ARMISD::VQRSHRNu; break;
9995     case Intrinsic::arm_neon_vqrshiftnsu:
9996       VShiftOpc = ARMISD::VQRSHRNsu; break;
9997     }
9998
9999     SDLoc dl(N);
10000     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10001                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10002   }
10003
10004   case Intrinsic::arm_neon_vshiftins: {
10005     EVT VT = N->getOperand(1).getValueType();
10006     int64_t Cnt;
10007     unsigned VShiftOpc = 0;
10008
10009     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10010       VShiftOpc = ARMISD::VSLI;
10011     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10012       VShiftOpc = ARMISD::VSRI;
10013     else {
10014       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10015     }
10016
10017     SDLoc dl(N);
10018     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10019                        N->getOperand(1), N->getOperand(2),
10020                        DAG.getConstant(Cnt, dl, MVT::i32));
10021   }
10022
10023   case Intrinsic::arm_neon_vqrshifts:
10024   case Intrinsic::arm_neon_vqrshiftu:
10025     // No immediate versions of these to check for.
10026     break;
10027   }
10028
10029   return SDValue();
10030 }
10031
10032 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10033 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10034 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10035 /// vector element shift counts are generally not legal, and it is hard to see
10036 /// their values after they get legalized to loads from a constant pool.
10037 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10038                                    const ARMSubtarget *ST) {
10039   EVT VT = N->getValueType(0);
10040   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10041     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10042     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10043     SDValue N1 = N->getOperand(1);
10044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10045       SDValue N0 = N->getOperand(0);
10046       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10047           DAG.MaskedValueIsZero(N0.getOperand(0),
10048                                 APInt::getHighBitsSet(32, 16)))
10049         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10050     }
10051   }
10052
10053   // Nothing to be done for scalar shifts.
10054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10055   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10056     return SDValue();
10057
10058   assert(ST->hasNEON() && "unexpected vector shift");
10059   int64_t Cnt;
10060
10061   switch (N->getOpcode()) {
10062   default: llvm_unreachable("unexpected shift opcode");
10063
10064   case ISD::SHL:
10065     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10066       SDLoc dl(N);
10067       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10068                          DAG.getConstant(Cnt, dl, MVT::i32));
10069     }
10070     break;
10071
10072   case ISD::SRA:
10073   case ISD::SRL:
10074     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10075       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10076                             ARMISD::VSHRs : ARMISD::VSHRu);
10077       SDLoc dl(N);
10078       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10079                          DAG.getConstant(Cnt, dl, MVT::i32));
10080     }
10081   }
10082   return SDValue();
10083 }
10084
10085 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10086 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10087 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10088                                     const ARMSubtarget *ST) {
10089   SDValue N0 = N->getOperand(0);
10090
10091   // Check for sign- and zero-extensions of vector extract operations of 8-
10092   // and 16-bit vector elements.  NEON supports these directly.  They are
10093   // handled during DAG combining because type legalization will promote them
10094   // to 32-bit types and it is messy to recognize the operations after that.
10095   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10096     SDValue Vec = N0.getOperand(0);
10097     SDValue Lane = N0.getOperand(1);
10098     EVT VT = N->getValueType(0);
10099     EVT EltVT = N0.getValueType();
10100     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10101
10102     if (VT == MVT::i32 &&
10103         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10104         TLI.isTypeLegal(Vec.getValueType()) &&
10105         isa<ConstantSDNode>(Lane)) {
10106
10107       unsigned Opc = 0;
10108       switch (N->getOpcode()) {
10109       default: llvm_unreachable("unexpected opcode");
10110       case ISD::SIGN_EXTEND:
10111         Opc = ARMISD::VGETLANEs;
10112         break;
10113       case ISD::ZERO_EXTEND:
10114       case ISD::ANY_EXTEND:
10115         Opc = ARMISD::VGETLANEu;
10116         break;
10117       }
10118       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10119     }
10120   }
10121
10122   return SDValue();
10123 }
10124
10125 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10126 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10127 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10128                                        const ARMSubtarget *ST) {
10129   // If the target supports NEON, try to use vmax/vmin instructions for f32
10130   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10131   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10132   // a NaN; only do the transformation when it matches that behavior.
10133
10134   // For now only do this when using NEON for FP operations; if using VFP, it
10135   // is not obvious that the benefit outweighs the cost of switching to the
10136   // NEON pipeline.
10137   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10138       N->getValueType(0) != MVT::f32)
10139     return SDValue();
10140
10141   SDValue CondLHS = N->getOperand(0);
10142   SDValue CondRHS = N->getOperand(1);
10143   SDValue LHS = N->getOperand(2);
10144   SDValue RHS = N->getOperand(3);
10145   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10146
10147   unsigned Opcode = 0;
10148   bool IsReversed;
10149   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10150     IsReversed = false; // x CC y ? x : y
10151   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10152     IsReversed = true ; // x CC y ? y : x
10153   } else {
10154     return SDValue();
10155   }
10156
10157   bool IsUnordered;
10158   switch (CC) {
10159   default: break;
10160   case ISD::SETOLT:
10161   case ISD::SETOLE:
10162   case ISD::SETLT:
10163   case ISD::SETLE:
10164   case ISD::SETULT:
10165   case ISD::SETULE:
10166     // If LHS is NaN, an ordered comparison will be false and the result will
10167     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10168     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10169     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10170     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10171       break;
10172     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10173     // will return -0, so vmin can only be used for unsafe math or if one of
10174     // the operands is known to be nonzero.
10175     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10176         !DAG.getTarget().Options.UnsafeFPMath &&
10177         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10178       break;
10179     Opcode = IsReversed ? ISD::FMAXNAN : ISD::FMINNAN;
10180     break;
10181
10182   case ISD::SETOGT:
10183   case ISD::SETOGE:
10184   case ISD::SETGT:
10185   case ISD::SETGE:
10186   case ISD::SETUGT:
10187   case ISD::SETUGE:
10188     // If LHS is NaN, an ordered comparison will be false and the result will
10189     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10190     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10191     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10192     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10193       break;
10194     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10195     // will return +0, so vmax can only be used for unsafe math or if one of
10196     // the operands is known to be nonzero.
10197     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10198         !DAG.getTarget().Options.UnsafeFPMath &&
10199         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10200       break;
10201     Opcode = IsReversed ? ISD::FMINNAN : ISD::FMAXNAN;
10202     break;
10203   }
10204
10205   if (!Opcode)
10206     return SDValue();
10207   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10208 }
10209
10210 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10211 SDValue
10212 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10213   SDValue Cmp = N->getOperand(4);
10214   if (Cmp.getOpcode() != ARMISD::CMPZ)
10215     // Only looking at EQ and NE cases.
10216     return SDValue();
10217
10218   EVT VT = N->getValueType(0);
10219   SDLoc dl(N);
10220   SDValue LHS = Cmp.getOperand(0);
10221   SDValue RHS = Cmp.getOperand(1);
10222   SDValue FalseVal = N->getOperand(0);
10223   SDValue TrueVal = N->getOperand(1);
10224   SDValue ARMcc = N->getOperand(2);
10225   ARMCC::CondCodes CC =
10226     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10227
10228   // Simplify
10229   //   mov     r1, r0
10230   //   cmp     r1, x
10231   //   mov     r0, y
10232   //   moveq   r0, x
10233   // to
10234   //   cmp     r0, x
10235   //   movne   r0, y
10236   //
10237   //   mov     r1, r0
10238   //   cmp     r1, x
10239   //   mov     r0, x
10240   //   movne   r0, y
10241   // to
10242   //   cmp     r0, x
10243   //   movne   r0, y
10244   /// FIXME: Turn this into a target neutral optimization?
10245   SDValue Res;
10246   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10247     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10248                       N->getOperand(3), Cmp);
10249   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10250     SDValue ARMcc;
10251     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10252     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10253                       N->getOperand(3), NewCmp);
10254   }
10255
10256   if (Res.getNode()) {
10257     APInt KnownZero, KnownOne;
10258     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10259     // Capture demanded bits information that would be otherwise lost.
10260     if (KnownZero == 0xfffffffe)
10261       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10262                         DAG.getValueType(MVT::i1));
10263     else if (KnownZero == 0xffffff00)
10264       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10265                         DAG.getValueType(MVT::i8));
10266     else if (KnownZero == 0xffff0000)
10267       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10268                         DAG.getValueType(MVT::i16));
10269   }
10270
10271   return Res;
10272 }
10273
10274 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10275                                              DAGCombinerInfo &DCI) const {
10276   switch (N->getOpcode()) {
10277   default: break;
10278   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10279   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10280   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10281   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10282   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10283   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10284   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10285   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10286   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10287   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10288   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10289   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10290   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10291   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10292   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10293   case ISD::FP_TO_SINT:
10294   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10295   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10296   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10297   case ISD::SHL:
10298   case ISD::SRA:
10299   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10300   case ISD::SIGN_EXTEND:
10301   case ISD::ZERO_EXTEND:
10302   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10303   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10304   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10305   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10306   case ARMISD::VLD2DUP:
10307   case ARMISD::VLD3DUP:
10308   case ARMISD::VLD4DUP:
10309     return PerformVLDCombine(N, DCI);
10310   case ARMISD::BUILD_VECTOR:
10311     return PerformARMBUILD_VECTORCombine(N, DCI);
10312   case ISD::INTRINSIC_VOID:
10313   case ISD::INTRINSIC_W_CHAIN:
10314     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10315     case Intrinsic::arm_neon_vld1:
10316     case Intrinsic::arm_neon_vld2:
10317     case Intrinsic::arm_neon_vld3:
10318     case Intrinsic::arm_neon_vld4:
10319     case Intrinsic::arm_neon_vld2lane:
10320     case Intrinsic::arm_neon_vld3lane:
10321     case Intrinsic::arm_neon_vld4lane:
10322     case Intrinsic::arm_neon_vst1:
10323     case Intrinsic::arm_neon_vst2:
10324     case Intrinsic::arm_neon_vst3:
10325     case Intrinsic::arm_neon_vst4:
10326     case Intrinsic::arm_neon_vst2lane:
10327     case Intrinsic::arm_neon_vst3lane:
10328     case Intrinsic::arm_neon_vst4lane:
10329       return PerformVLDCombine(N, DCI);
10330     default: break;
10331     }
10332     break;
10333   }
10334   return SDValue();
10335 }
10336
10337 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10338                                                           EVT VT) const {
10339   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10340 }
10341
10342 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10343                                                        unsigned,
10344                                                        unsigned,
10345                                                        bool *Fast) const {
10346   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10347   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10348
10349   switch (VT.getSimpleVT().SimpleTy) {
10350   default:
10351     return false;
10352   case MVT::i8:
10353   case MVT::i16:
10354   case MVT::i32: {
10355     // Unaligned access can use (for example) LRDB, LRDH, LDR
10356     if (AllowsUnaligned) {
10357       if (Fast)
10358         *Fast = Subtarget->hasV7Ops();
10359       return true;
10360     }
10361     return false;
10362   }
10363   case MVT::f64:
10364   case MVT::v2f64: {
10365     // For any little-endian targets with neon, we can support unaligned ld/st
10366     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10367     // A big-endian target may also explicitly support unaligned accesses
10368     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10369       if (Fast)
10370         *Fast = true;
10371       return true;
10372     }
10373     return false;
10374   }
10375   }
10376 }
10377
10378 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10379                        unsigned AlignCheck) {
10380   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10381           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10382 }
10383
10384 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10385                                            unsigned DstAlign, unsigned SrcAlign,
10386                                            bool IsMemset, bool ZeroMemset,
10387                                            bool MemcpyStrSrc,
10388                                            MachineFunction &MF) const {
10389   const Function *F = MF.getFunction();
10390
10391   // See if we can use NEON instructions for this...
10392   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10393       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10394     bool Fast;
10395     if (Size >= 16 &&
10396         (memOpAlign(SrcAlign, DstAlign, 16) ||
10397          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10398       return MVT::v2f64;
10399     } else if (Size >= 8 &&
10400                (memOpAlign(SrcAlign, DstAlign, 8) ||
10401                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10402                  Fast))) {
10403       return MVT::f64;
10404     }
10405   }
10406
10407   // Lowering to i32/i16 if the size permits.
10408   if (Size >= 4)
10409     return MVT::i32;
10410   else if (Size >= 2)
10411     return MVT::i16;
10412
10413   // Let the target-independent logic figure it out.
10414   return MVT::Other;
10415 }
10416
10417 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10418   if (Val.getOpcode() != ISD::LOAD)
10419     return false;
10420
10421   EVT VT1 = Val.getValueType();
10422   if (!VT1.isSimple() || !VT1.isInteger() ||
10423       !VT2.isSimple() || !VT2.isInteger())
10424     return false;
10425
10426   switch (VT1.getSimpleVT().SimpleTy) {
10427   default: break;
10428   case MVT::i1:
10429   case MVT::i8:
10430   case MVT::i16:
10431     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10432     return true;
10433   }
10434
10435   return false;
10436 }
10437
10438 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10439   EVT VT = ExtVal.getValueType();
10440
10441   if (!isTypeLegal(VT))
10442     return false;
10443
10444   // Don't create a loadext if we can fold the extension into a wide/long
10445   // instruction.
10446   // If there's more than one user instruction, the loadext is desirable no
10447   // matter what.  There can be two uses by the same instruction.
10448   if (ExtVal->use_empty() ||
10449       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10450     return true;
10451
10452   SDNode *U = *ExtVal->use_begin();
10453   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10454        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10455     return false;
10456
10457   return true;
10458 }
10459
10460 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10461   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10462     return false;
10463
10464   if (!isTypeLegal(EVT::getEVT(Ty1)))
10465     return false;
10466
10467   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10468
10469   // Assuming the caller doesn't have a zeroext or signext return parameter,
10470   // truncation all the way down to i1 is valid.
10471   return true;
10472 }
10473
10474
10475 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10476   if (V < 0)
10477     return false;
10478
10479   unsigned Scale = 1;
10480   switch (VT.getSimpleVT().SimpleTy) {
10481   default: return false;
10482   case MVT::i1:
10483   case MVT::i8:
10484     // Scale == 1;
10485     break;
10486   case MVT::i16:
10487     // Scale == 2;
10488     Scale = 2;
10489     break;
10490   case MVT::i32:
10491     // Scale == 4;
10492     Scale = 4;
10493     break;
10494   }
10495
10496   if ((V & (Scale - 1)) != 0)
10497     return false;
10498   V /= Scale;
10499   return V == (V & ((1LL << 5) - 1));
10500 }
10501
10502 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10503                                       const ARMSubtarget *Subtarget) {
10504   bool isNeg = false;
10505   if (V < 0) {
10506     isNeg = true;
10507     V = - V;
10508   }
10509
10510   switch (VT.getSimpleVT().SimpleTy) {
10511   default: return false;
10512   case MVT::i1:
10513   case MVT::i8:
10514   case MVT::i16:
10515   case MVT::i32:
10516     // + imm12 or - imm8
10517     if (isNeg)
10518       return V == (V & ((1LL << 8) - 1));
10519     return V == (V & ((1LL << 12) - 1));
10520   case MVT::f32:
10521   case MVT::f64:
10522     // Same as ARM mode. FIXME: NEON?
10523     if (!Subtarget->hasVFP2())
10524       return false;
10525     if ((V & 3) != 0)
10526       return false;
10527     V >>= 2;
10528     return V == (V & ((1LL << 8) - 1));
10529   }
10530 }
10531
10532 /// isLegalAddressImmediate - Return true if the integer value can be used
10533 /// as the offset of the target addressing mode for load / store of the
10534 /// given type.
10535 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10536                                     const ARMSubtarget *Subtarget) {
10537   if (V == 0)
10538     return true;
10539
10540   if (!VT.isSimple())
10541     return false;
10542
10543   if (Subtarget->isThumb1Only())
10544     return isLegalT1AddressImmediate(V, VT);
10545   else if (Subtarget->isThumb2())
10546     return isLegalT2AddressImmediate(V, VT, Subtarget);
10547
10548   // ARM mode.
10549   if (V < 0)
10550     V = - V;
10551   switch (VT.getSimpleVT().SimpleTy) {
10552   default: return false;
10553   case MVT::i1:
10554   case MVT::i8:
10555   case MVT::i32:
10556     // +- imm12
10557     return V == (V & ((1LL << 12) - 1));
10558   case MVT::i16:
10559     // +- imm8
10560     return V == (V & ((1LL << 8) - 1));
10561   case MVT::f32:
10562   case MVT::f64:
10563     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10564       return false;
10565     if ((V & 3) != 0)
10566       return false;
10567     V >>= 2;
10568     return V == (V & ((1LL << 8) - 1));
10569   }
10570 }
10571
10572 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10573                                                       EVT VT) const {
10574   int Scale = AM.Scale;
10575   if (Scale < 0)
10576     return false;
10577
10578   switch (VT.getSimpleVT().SimpleTy) {
10579   default: return false;
10580   case MVT::i1:
10581   case MVT::i8:
10582   case MVT::i16:
10583   case MVT::i32:
10584     if (Scale == 1)
10585       return true;
10586     // r + r << imm
10587     Scale = Scale & ~1;
10588     return Scale == 2 || Scale == 4 || Scale == 8;
10589   case MVT::i64:
10590     // r + r
10591     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10592       return true;
10593     return false;
10594   case MVT::isVoid:
10595     // Note, we allow "void" uses (basically, uses that aren't loads or
10596     // stores), because arm allows folding a scale into many arithmetic
10597     // operations.  This should be made more precise and revisited later.
10598
10599     // Allow r << imm, but the imm has to be a multiple of two.
10600     if (Scale & 1) return false;
10601     return isPowerOf2_32(Scale);
10602   }
10603 }
10604
10605 /// isLegalAddressingMode - Return true if the addressing mode represented
10606 /// by AM is legal for this target, for a load/store of the specified type.
10607 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10608                                               const AddrMode &AM, Type *Ty,
10609                                               unsigned AS) const {
10610   EVT VT = getValueType(DL, Ty, true);
10611   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10612     return false;
10613
10614   // Can never fold addr of global into load/store.
10615   if (AM.BaseGV)
10616     return false;
10617
10618   switch (AM.Scale) {
10619   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10620     break;
10621   case 1:
10622     if (Subtarget->isThumb1Only())
10623       return false;
10624     // FALL THROUGH.
10625   default:
10626     // ARM doesn't support any R+R*scale+imm addr modes.
10627     if (AM.BaseOffs)
10628       return false;
10629
10630     if (!VT.isSimple())
10631       return false;
10632
10633     if (Subtarget->isThumb2())
10634       return isLegalT2ScaledAddressingMode(AM, VT);
10635
10636     int Scale = AM.Scale;
10637     switch (VT.getSimpleVT().SimpleTy) {
10638     default: return false;
10639     case MVT::i1:
10640     case MVT::i8:
10641     case MVT::i32:
10642       if (Scale < 0) Scale = -Scale;
10643       if (Scale == 1)
10644         return true;
10645       // r + r << imm
10646       return isPowerOf2_32(Scale & ~1);
10647     case MVT::i16:
10648     case MVT::i64:
10649       // r + r
10650       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10651         return true;
10652       return false;
10653
10654     case MVT::isVoid:
10655       // Note, we allow "void" uses (basically, uses that aren't loads or
10656       // stores), because arm allows folding a scale into many arithmetic
10657       // operations.  This should be made more precise and revisited later.
10658
10659       // Allow r << imm, but the imm has to be a multiple of two.
10660       if (Scale & 1) return false;
10661       return isPowerOf2_32(Scale);
10662     }
10663   }
10664   return true;
10665 }
10666
10667 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10668 /// icmp immediate, that is the target has icmp instructions which can compare
10669 /// a register against the immediate without having to materialize the
10670 /// immediate into a register.
10671 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10672   // Thumb2 and ARM modes can use cmn for negative immediates.
10673   if (!Subtarget->isThumb())
10674     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10675   if (Subtarget->isThumb2())
10676     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10677   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10678   return Imm >= 0 && Imm <= 255;
10679 }
10680
10681 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10682 /// *or sub* immediate, that is the target has add or sub instructions which can
10683 /// add a register with the immediate without having to materialize the
10684 /// immediate into a register.
10685 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10686   // Same encoding for add/sub, just flip the sign.
10687   int64_t AbsImm = std::abs(Imm);
10688   if (!Subtarget->isThumb())
10689     return ARM_AM::getSOImmVal(AbsImm) != -1;
10690   if (Subtarget->isThumb2())
10691     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10692   // Thumb1 only has 8-bit unsigned immediate.
10693   return AbsImm >= 0 && AbsImm <= 255;
10694 }
10695
10696 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10697                                       bool isSEXTLoad, SDValue &Base,
10698                                       SDValue &Offset, bool &isInc,
10699                                       SelectionDAG &DAG) {
10700   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10701     return false;
10702
10703   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10704     // AddressingMode 3
10705     Base = Ptr->getOperand(0);
10706     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10707       int RHSC = (int)RHS->getZExtValue();
10708       if (RHSC < 0 && RHSC > -256) {
10709         assert(Ptr->getOpcode() == ISD::ADD);
10710         isInc = false;
10711         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10712         return true;
10713       }
10714     }
10715     isInc = (Ptr->getOpcode() == ISD::ADD);
10716     Offset = Ptr->getOperand(1);
10717     return true;
10718   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10719     // AddressingMode 2
10720     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10721       int RHSC = (int)RHS->getZExtValue();
10722       if (RHSC < 0 && RHSC > -0x1000) {
10723         assert(Ptr->getOpcode() == ISD::ADD);
10724         isInc = false;
10725         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10726         Base = Ptr->getOperand(0);
10727         return true;
10728       }
10729     }
10730
10731     if (Ptr->getOpcode() == ISD::ADD) {
10732       isInc = true;
10733       ARM_AM::ShiftOpc ShOpcVal=
10734         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10735       if (ShOpcVal != ARM_AM::no_shift) {
10736         Base = Ptr->getOperand(1);
10737         Offset = Ptr->getOperand(0);
10738       } else {
10739         Base = Ptr->getOperand(0);
10740         Offset = Ptr->getOperand(1);
10741       }
10742       return true;
10743     }
10744
10745     isInc = (Ptr->getOpcode() == ISD::ADD);
10746     Base = Ptr->getOperand(0);
10747     Offset = Ptr->getOperand(1);
10748     return true;
10749   }
10750
10751   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10752   return false;
10753 }
10754
10755 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10756                                      bool isSEXTLoad, SDValue &Base,
10757                                      SDValue &Offset, bool &isInc,
10758                                      SelectionDAG &DAG) {
10759   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10760     return false;
10761
10762   Base = Ptr->getOperand(0);
10763   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10764     int RHSC = (int)RHS->getZExtValue();
10765     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10766       assert(Ptr->getOpcode() == ISD::ADD);
10767       isInc = false;
10768       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10769       return true;
10770     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10771       isInc = Ptr->getOpcode() == ISD::ADD;
10772       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10773       return true;
10774     }
10775   }
10776
10777   return false;
10778 }
10779
10780 /// getPreIndexedAddressParts - returns true by value, base pointer and
10781 /// offset pointer and addressing mode by reference if the node's address
10782 /// can be legally represented as pre-indexed load / store address.
10783 bool
10784 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10785                                              SDValue &Offset,
10786                                              ISD::MemIndexedMode &AM,
10787                                              SelectionDAG &DAG) const {
10788   if (Subtarget->isThumb1Only())
10789     return false;
10790
10791   EVT VT;
10792   SDValue Ptr;
10793   bool isSEXTLoad = false;
10794   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10795     Ptr = LD->getBasePtr();
10796     VT  = LD->getMemoryVT();
10797     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10798   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10799     Ptr = ST->getBasePtr();
10800     VT  = ST->getMemoryVT();
10801   } else
10802     return false;
10803
10804   bool isInc;
10805   bool isLegal = false;
10806   if (Subtarget->isThumb2())
10807     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10808                                        Offset, isInc, DAG);
10809   else
10810     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10811                                         Offset, isInc, DAG);
10812   if (!isLegal)
10813     return false;
10814
10815   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10816   return true;
10817 }
10818
10819 /// getPostIndexedAddressParts - returns true by value, base pointer and
10820 /// offset pointer and addressing mode by reference if this node can be
10821 /// combined with a load / store to form a post-indexed load / store.
10822 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10823                                                    SDValue &Base,
10824                                                    SDValue &Offset,
10825                                                    ISD::MemIndexedMode &AM,
10826                                                    SelectionDAG &DAG) const {
10827   if (Subtarget->isThumb1Only())
10828     return false;
10829
10830   EVT VT;
10831   SDValue Ptr;
10832   bool isSEXTLoad = false;
10833   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10834     VT  = LD->getMemoryVT();
10835     Ptr = LD->getBasePtr();
10836     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10837   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10838     VT  = ST->getMemoryVT();
10839     Ptr = ST->getBasePtr();
10840   } else
10841     return false;
10842
10843   bool isInc;
10844   bool isLegal = false;
10845   if (Subtarget->isThumb2())
10846     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10847                                        isInc, DAG);
10848   else
10849     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10850                                         isInc, DAG);
10851   if (!isLegal)
10852     return false;
10853
10854   if (Ptr != Base) {
10855     // Swap base ptr and offset to catch more post-index load / store when
10856     // it's legal. In Thumb2 mode, offset must be an immediate.
10857     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10858         !Subtarget->isThumb2())
10859       std::swap(Base, Offset);
10860
10861     // Post-indexed load / store update the base pointer.
10862     if (Ptr != Base)
10863       return false;
10864   }
10865
10866   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10867   return true;
10868 }
10869
10870 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10871                                                       APInt &KnownZero,
10872                                                       APInt &KnownOne,
10873                                                       const SelectionDAG &DAG,
10874                                                       unsigned Depth) const {
10875   unsigned BitWidth = KnownOne.getBitWidth();
10876   KnownZero = KnownOne = APInt(BitWidth, 0);
10877   switch (Op.getOpcode()) {
10878   default: break;
10879   case ARMISD::ADDC:
10880   case ARMISD::ADDE:
10881   case ARMISD::SUBC:
10882   case ARMISD::SUBE:
10883     // These nodes' second result is a boolean
10884     if (Op.getResNo() == 0)
10885       break;
10886     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10887     break;
10888   case ARMISD::CMOV: {
10889     // Bits are known zero/one if known on the LHS and RHS.
10890     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10891     if (KnownZero == 0 && KnownOne == 0) return;
10892
10893     APInt KnownZeroRHS, KnownOneRHS;
10894     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10895     KnownZero &= KnownZeroRHS;
10896     KnownOne  &= KnownOneRHS;
10897     return;
10898   }
10899   case ISD::INTRINSIC_W_CHAIN: {
10900     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10901     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10902     switch (IntID) {
10903     default: return;
10904     case Intrinsic::arm_ldaex:
10905     case Intrinsic::arm_ldrex: {
10906       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10907       unsigned MemBits = VT.getScalarType().getSizeInBits();
10908       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10909       return;
10910     }
10911     }
10912   }
10913   }
10914 }
10915
10916 //===----------------------------------------------------------------------===//
10917 //                           ARM Inline Assembly Support
10918 //===----------------------------------------------------------------------===//
10919
10920 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10921   // Looking for "rev" which is V6+.
10922   if (!Subtarget->hasV6Ops())
10923     return false;
10924
10925   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10926   std::string AsmStr = IA->getAsmString();
10927   SmallVector<StringRef, 4> AsmPieces;
10928   SplitString(AsmStr, AsmPieces, ";\n");
10929
10930   switch (AsmPieces.size()) {
10931   default: return false;
10932   case 1:
10933     AsmStr = AsmPieces[0];
10934     AsmPieces.clear();
10935     SplitString(AsmStr, AsmPieces, " \t,");
10936
10937     // rev $0, $1
10938     if (AsmPieces.size() == 3 &&
10939         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10940         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10941       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10942       if (Ty && Ty->getBitWidth() == 32)
10943         return IntrinsicLowering::LowerToByteSwap(CI);
10944     }
10945     break;
10946   }
10947
10948   return false;
10949 }
10950
10951 /// getConstraintType - Given a constraint letter, return the type of
10952 /// constraint it is for this target.
10953 ARMTargetLowering::ConstraintType
10954 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10955   if (Constraint.size() == 1) {
10956     switch (Constraint[0]) {
10957     default:  break;
10958     case 'l': return C_RegisterClass;
10959     case 'w': return C_RegisterClass;
10960     case 'h': return C_RegisterClass;
10961     case 'x': return C_RegisterClass;
10962     case 't': return C_RegisterClass;
10963     case 'j': return C_Other; // Constant for movw.
10964       // An address with a single base register. Due to the way we
10965       // currently handle addresses it is the same as an 'r' memory constraint.
10966     case 'Q': return C_Memory;
10967     }
10968   } else if (Constraint.size() == 2) {
10969     switch (Constraint[0]) {
10970     default: break;
10971     // All 'U+' constraints are addresses.
10972     case 'U': return C_Memory;
10973     }
10974   }
10975   return TargetLowering::getConstraintType(Constraint);
10976 }
10977
10978 /// Examine constraint type and operand type and determine a weight value.
10979 /// This object must already have been set up with the operand type
10980 /// and the current alternative constraint selected.
10981 TargetLowering::ConstraintWeight
10982 ARMTargetLowering::getSingleConstraintMatchWeight(
10983     AsmOperandInfo &info, const char *constraint) const {
10984   ConstraintWeight weight = CW_Invalid;
10985   Value *CallOperandVal = info.CallOperandVal;
10986     // If we don't have a value, we can't do a match,
10987     // but allow it at the lowest weight.
10988   if (!CallOperandVal)
10989     return CW_Default;
10990   Type *type = CallOperandVal->getType();
10991   // Look at the constraint type.
10992   switch (*constraint) {
10993   default:
10994     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10995     break;
10996   case 'l':
10997     if (type->isIntegerTy()) {
10998       if (Subtarget->isThumb())
10999         weight = CW_SpecificReg;
11000       else
11001         weight = CW_Register;
11002     }
11003     break;
11004   case 'w':
11005     if (type->isFloatingPointTy())
11006       weight = CW_Register;
11007     break;
11008   }
11009   return weight;
11010 }
11011
11012 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11013 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11014     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11015   if (Constraint.size() == 1) {
11016     // GCC ARM Constraint Letters
11017     switch (Constraint[0]) {
11018     case 'l': // Low regs or general regs.
11019       if (Subtarget->isThumb())
11020         return RCPair(0U, &ARM::tGPRRegClass);
11021       return RCPair(0U, &ARM::GPRRegClass);
11022     case 'h': // High regs or no regs.
11023       if (Subtarget->isThumb())
11024         return RCPair(0U, &ARM::hGPRRegClass);
11025       break;
11026     case 'r':
11027       if (Subtarget->isThumb1Only())
11028         return RCPair(0U, &ARM::tGPRRegClass);
11029       return RCPair(0U, &ARM::GPRRegClass);
11030     case 'w':
11031       if (VT == MVT::Other)
11032         break;
11033       if (VT == MVT::f32)
11034         return RCPair(0U, &ARM::SPRRegClass);
11035       if (VT.getSizeInBits() == 64)
11036         return RCPair(0U, &ARM::DPRRegClass);
11037       if (VT.getSizeInBits() == 128)
11038         return RCPair(0U, &ARM::QPRRegClass);
11039       break;
11040     case 'x':
11041       if (VT == MVT::Other)
11042         break;
11043       if (VT == MVT::f32)
11044         return RCPair(0U, &ARM::SPR_8RegClass);
11045       if (VT.getSizeInBits() == 64)
11046         return RCPair(0U, &ARM::DPR_8RegClass);
11047       if (VT.getSizeInBits() == 128)
11048         return RCPair(0U, &ARM::QPR_8RegClass);
11049       break;
11050     case 't':
11051       if (VT == MVT::f32)
11052         return RCPair(0U, &ARM::SPRRegClass);
11053       break;
11054     }
11055   }
11056   if (StringRef("{cc}").equals_lower(Constraint))
11057     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11058
11059   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11060 }
11061
11062 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11063 /// vector.  If it is invalid, don't add anything to Ops.
11064 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11065                                                      std::string &Constraint,
11066                                                      std::vector<SDValue>&Ops,
11067                                                      SelectionDAG &DAG) const {
11068   SDValue Result;
11069
11070   // Currently only support length 1 constraints.
11071   if (Constraint.length() != 1) return;
11072
11073   char ConstraintLetter = Constraint[0];
11074   switch (ConstraintLetter) {
11075   default: break;
11076   case 'j':
11077   case 'I': case 'J': case 'K': case 'L':
11078   case 'M': case 'N': case 'O':
11079     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11080     if (!C)
11081       return;
11082
11083     int64_t CVal64 = C->getSExtValue();
11084     int CVal = (int) CVal64;
11085     // None of these constraints allow values larger than 32 bits.  Check
11086     // that the value fits in an int.
11087     if (CVal != CVal64)
11088       return;
11089
11090     switch (ConstraintLetter) {
11091       case 'j':
11092         // Constant suitable for movw, must be between 0 and
11093         // 65535.
11094         if (Subtarget->hasV6T2Ops())
11095           if (CVal >= 0 && CVal <= 65535)
11096             break;
11097         return;
11098       case 'I':
11099         if (Subtarget->isThumb1Only()) {
11100           // This must be a constant between 0 and 255, for ADD
11101           // immediates.
11102           if (CVal >= 0 && CVal <= 255)
11103             break;
11104         } else if (Subtarget->isThumb2()) {
11105           // A constant that can be used as an immediate value in a
11106           // data-processing instruction.
11107           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11108             break;
11109         } else {
11110           // A constant that can be used as an immediate value in a
11111           // data-processing instruction.
11112           if (ARM_AM::getSOImmVal(CVal) != -1)
11113             break;
11114         }
11115         return;
11116
11117       case 'J':
11118         if (Subtarget->isThumb()) {  // FIXME thumb2
11119           // This must be a constant between -255 and -1, for negated ADD
11120           // immediates. This can be used in GCC with an "n" modifier that
11121           // prints the negated value, for use with SUB instructions. It is
11122           // not useful otherwise but is implemented for compatibility.
11123           if (CVal >= -255 && CVal <= -1)
11124             break;
11125         } else {
11126           // This must be a constant between -4095 and 4095. It is not clear
11127           // what this constraint is intended for. Implemented for
11128           // compatibility with GCC.
11129           if (CVal >= -4095 && CVal <= 4095)
11130             break;
11131         }
11132         return;
11133
11134       case 'K':
11135         if (Subtarget->isThumb1Only()) {
11136           // A 32-bit value where only one byte has a nonzero value. Exclude
11137           // zero to match GCC. This constraint is used by GCC internally for
11138           // constants that can be loaded with a move/shift combination.
11139           // It is not useful otherwise but is implemented for compatibility.
11140           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11141             break;
11142         } else if (Subtarget->isThumb2()) {
11143           // A constant whose bitwise inverse can be used as an immediate
11144           // value in a data-processing instruction. This can be used in GCC
11145           // with a "B" modifier that prints the inverted value, for use with
11146           // BIC and MVN instructions. It is not useful otherwise but is
11147           // implemented for compatibility.
11148           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11149             break;
11150         } else {
11151           // A constant whose bitwise inverse can be used as an immediate
11152           // value in a data-processing instruction. This can be used in GCC
11153           // with a "B" modifier that prints the inverted value, for use with
11154           // BIC and MVN instructions. It is not useful otherwise but is
11155           // implemented for compatibility.
11156           if (ARM_AM::getSOImmVal(~CVal) != -1)
11157             break;
11158         }
11159         return;
11160
11161       case 'L':
11162         if (Subtarget->isThumb1Only()) {
11163           // This must be a constant between -7 and 7,
11164           // for 3-operand ADD/SUB immediate instructions.
11165           if (CVal >= -7 && CVal < 7)
11166             break;
11167         } else if (Subtarget->isThumb2()) {
11168           // A constant whose negation can be used as an immediate value in a
11169           // data-processing instruction. This can be used in GCC with an "n"
11170           // modifier that prints the negated value, for use with SUB
11171           // instructions. It is not useful otherwise but is implemented for
11172           // compatibility.
11173           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11174             break;
11175         } else {
11176           // A constant whose negation can be used as an immediate value in a
11177           // data-processing instruction. This can be used in GCC with an "n"
11178           // modifier that prints the negated value, for use with SUB
11179           // instructions. It is not useful otherwise but is implemented for
11180           // compatibility.
11181           if (ARM_AM::getSOImmVal(-CVal) != -1)
11182             break;
11183         }
11184         return;
11185
11186       case 'M':
11187         if (Subtarget->isThumb()) { // FIXME thumb2
11188           // This must be a multiple of 4 between 0 and 1020, for
11189           // ADD sp + immediate.
11190           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11191             break;
11192         } else {
11193           // A power of two or a constant between 0 and 32.  This is used in
11194           // GCC for the shift amount on shifted register operands, but it is
11195           // useful in general for any shift amounts.
11196           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11197             break;
11198         }
11199         return;
11200
11201       case 'N':
11202         if (Subtarget->isThumb()) {  // FIXME thumb2
11203           // This must be a constant between 0 and 31, for shift amounts.
11204           if (CVal >= 0 && CVal <= 31)
11205             break;
11206         }
11207         return;
11208
11209       case 'O':
11210         if (Subtarget->isThumb()) {  // FIXME thumb2
11211           // This must be a multiple of 4 between -508 and 508, for
11212           // ADD/SUB sp = sp + immediate.
11213           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11214             break;
11215         }
11216         return;
11217     }
11218     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11219     break;
11220   }
11221
11222   if (Result.getNode()) {
11223     Ops.push_back(Result);
11224     return;
11225   }
11226   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11227 }
11228
11229 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11230   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11231          "Register-based DivRem lowering only");
11232   unsigned Opcode = Op->getOpcode();
11233   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11234          "Invalid opcode for Div/Rem lowering");
11235   bool isSigned = (Opcode == ISD::SDIVREM);
11236   EVT VT = Op->getValueType(0);
11237   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11238
11239   RTLIB::Libcall LC;
11240   switch (VT.getSimpleVT().SimpleTy) {
11241   default: llvm_unreachable("Unexpected request for libcall!");
11242   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11243   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11244   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11245   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11246   }
11247
11248   SDValue InChain = DAG.getEntryNode();
11249
11250   TargetLowering::ArgListTy Args;
11251   TargetLowering::ArgListEntry Entry;
11252   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11253     EVT ArgVT = Op->getOperand(i).getValueType();
11254     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11255     Entry.Node = Op->getOperand(i);
11256     Entry.Ty = ArgTy;
11257     Entry.isSExt = isSigned;
11258     Entry.isZExt = !isSigned;
11259     Args.push_back(Entry);
11260   }
11261
11262   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11263                                          getPointerTy(DAG.getDataLayout()));
11264
11265   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11266
11267   SDLoc dl(Op);
11268   TargetLowering::CallLoweringInfo CLI(DAG);
11269   CLI.setDebugLoc(dl).setChain(InChain)
11270     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11271     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11272
11273   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11274   return CallInfo.first;
11275 }
11276
11277 SDValue
11278 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11279   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11280   SDLoc DL(Op);
11281
11282   // Get the inputs.
11283   SDValue Chain = Op.getOperand(0);
11284   SDValue Size  = Op.getOperand(1);
11285
11286   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11287                               DAG.getConstant(2, DL, MVT::i32));
11288
11289   SDValue Flag;
11290   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11291   Flag = Chain.getValue(1);
11292
11293   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11294   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11295
11296   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11297   Chain = NewSP.getValue(1);
11298
11299   SDValue Ops[2] = { NewSP, Chain };
11300   return DAG.getMergeValues(Ops, DL);
11301 }
11302
11303 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11304   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11305          "Unexpected type for custom-lowering FP_EXTEND");
11306
11307   RTLIB::Libcall LC;
11308   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11309
11310   SDValue SrcVal = Op.getOperand(0);
11311   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11312                      /*isSigned*/ false, SDLoc(Op)).first;
11313 }
11314
11315 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11316   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11317          Subtarget->isFPOnlySP() &&
11318          "Unexpected type for custom-lowering FP_ROUND");
11319
11320   RTLIB::Libcall LC;
11321   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11322
11323   SDValue SrcVal = Op.getOperand(0);
11324   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11325                      /*isSigned*/ false, SDLoc(Op)).first;
11326 }
11327
11328 bool
11329 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11330   // The ARM target isn't yet aware of offsets.
11331   return false;
11332 }
11333
11334 bool ARM::isBitFieldInvertedMask(unsigned v) {
11335   if (v == 0xffffffff)
11336     return false;
11337
11338   // there can be 1's on either or both "outsides", all the "inside"
11339   // bits must be 0's
11340   return isShiftedMask_32(~v);
11341 }
11342
11343 /// isFPImmLegal - Returns true if the target can instruction select the
11344 /// specified FP immediate natively. If false, the legalizer will
11345 /// materialize the FP immediate as a load from a constant pool.
11346 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11347   if (!Subtarget->hasVFP3())
11348     return false;
11349   if (VT == MVT::f32)
11350     return ARM_AM::getFP32Imm(Imm) != -1;
11351   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11352     return ARM_AM::getFP64Imm(Imm) != -1;
11353   return false;
11354 }
11355
11356 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11357 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11358 /// specified in the intrinsic calls.
11359 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11360                                            const CallInst &I,
11361                                            unsigned Intrinsic) const {
11362   switch (Intrinsic) {
11363   case Intrinsic::arm_neon_vld1:
11364   case Intrinsic::arm_neon_vld2:
11365   case Intrinsic::arm_neon_vld3:
11366   case Intrinsic::arm_neon_vld4:
11367   case Intrinsic::arm_neon_vld2lane:
11368   case Intrinsic::arm_neon_vld3lane:
11369   case Intrinsic::arm_neon_vld4lane: {
11370     Info.opc = ISD::INTRINSIC_W_CHAIN;
11371     // Conservatively set memVT to the entire set of vectors loaded.
11372     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11373     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11374     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11375     Info.ptrVal = I.getArgOperand(0);
11376     Info.offset = 0;
11377     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11378     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11379     Info.vol = false; // volatile loads with NEON intrinsics not supported
11380     Info.readMem = true;
11381     Info.writeMem = false;
11382     return true;
11383   }
11384   case Intrinsic::arm_neon_vst1:
11385   case Intrinsic::arm_neon_vst2:
11386   case Intrinsic::arm_neon_vst3:
11387   case Intrinsic::arm_neon_vst4:
11388   case Intrinsic::arm_neon_vst2lane:
11389   case Intrinsic::arm_neon_vst3lane:
11390   case Intrinsic::arm_neon_vst4lane: {
11391     Info.opc = ISD::INTRINSIC_VOID;
11392     // Conservatively set memVT to the entire set of vectors stored.
11393     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11394     unsigned NumElts = 0;
11395     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11396       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11397       if (!ArgTy->isVectorTy())
11398         break;
11399       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11400     }
11401     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11402     Info.ptrVal = I.getArgOperand(0);
11403     Info.offset = 0;
11404     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11405     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11406     Info.vol = false; // volatile stores with NEON intrinsics not supported
11407     Info.readMem = false;
11408     Info.writeMem = true;
11409     return true;
11410   }
11411   case Intrinsic::arm_ldaex:
11412   case Intrinsic::arm_ldrex: {
11413     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11414     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11415     Info.opc = ISD::INTRINSIC_W_CHAIN;
11416     Info.memVT = MVT::getVT(PtrTy->getElementType());
11417     Info.ptrVal = I.getArgOperand(0);
11418     Info.offset = 0;
11419     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11420     Info.vol = true;
11421     Info.readMem = true;
11422     Info.writeMem = false;
11423     return true;
11424   }
11425   case Intrinsic::arm_stlex:
11426   case Intrinsic::arm_strex: {
11427     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11428     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11429     Info.opc = ISD::INTRINSIC_W_CHAIN;
11430     Info.memVT = MVT::getVT(PtrTy->getElementType());
11431     Info.ptrVal = I.getArgOperand(1);
11432     Info.offset = 0;
11433     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11434     Info.vol = true;
11435     Info.readMem = false;
11436     Info.writeMem = true;
11437     return true;
11438   }
11439   case Intrinsic::arm_stlexd:
11440   case Intrinsic::arm_strexd: {
11441     Info.opc = ISD::INTRINSIC_W_CHAIN;
11442     Info.memVT = MVT::i64;
11443     Info.ptrVal = I.getArgOperand(2);
11444     Info.offset = 0;
11445     Info.align = 8;
11446     Info.vol = true;
11447     Info.readMem = false;
11448     Info.writeMem = true;
11449     return true;
11450   }
11451   case Intrinsic::arm_ldaexd:
11452   case Intrinsic::arm_ldrexd: {
11453     Info.opc = ISD::INTRINSIC_W_CHAIN;
11454     Info.memVT = MVT::i64;
11455     Info.ptrVal = I.getArgOperand(0);
11456     Info.offset = 0;
11457     Info.align = 8;
11458     Info.vol = true;
11459     Info.readMem = true;
11460     Info.writeMem = false;
11461     return true;
11462   }
11463   default:
11464     break;
11465   }
11466
11467   return false;
11468 }
11469
11470 /// \brief Returns true if it is beneficial to convert a load of a constant
11471 /// to just the constant itself.
11472 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11473                                                           Type *Ty) const {
11474   assert(Ty->isIntegerTy());
11475
11476   unsigned Bits = Ty->getPrimitiveSizeInBits();
11477   if (Bits == 0 || Bits > 32)
11478     return false;
11479   return true;
11480 }
11481
11482 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11483
11484 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11485                                         ARM_MB::MemBOpt Domain) const {
11486   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11487
11488   // First, if the target has no DMB, see what fallback we can use.
11489   if (!Subtarget->hasDataBarrier()) {
11490     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11491     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11492     // here.
11493     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11494       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11495       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11496                         Builder.getInt32(0), Builder.getInt32(7),
11497                         Builder.getInt32(10), Builder.getInt32(5)};
11498       return Builder.CreateCall(MCR, args);
11499     } else {
11500       // Instead of using barriers, atomic accesses on these subtargets use
11501       // libcalls.
11502       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11503     }
11504   } else {
11505     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11506     // Only a full system barrier exists in the M-class architectures.
11507     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11508     Constant *CDomain = Builder.getInt32(Domain);
11509     return Builder.CreateCall(DMB, CDomain);
11510   }
11511 }
11512
11513 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11514 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11515                                          AtomicOrdering Ord, bool IsStore,
11516                                          bool IsLoad) const {
11517   if (!getInsertFencesForAtomic())
11518     return nullptr;
11519
11520   switch (Ord) {
11521   case NotAtomic:
11522   case Unordered:
11523     llvm_unreachable("Invalid fence: unordered/non-atomic");
11524   case Monotonic:
11525   case Acquire:
11526     return nullptr; // Nothing to do
11527   case SequentiallyConsistent:
11528     if (!IsStore)
11529       return nullptr; // Nothing to do
11530     /*FALLTHROUGH*/
11531   case Release:
11532   case AcquireRelease:
11533     if (Subtarget->isSwift())
11534       return makeDMB(Builder, ARM_MB::ISHST);
11535     // FIXME: add a comment with a link to documentation justifying this.
11536     else
11537       return makeDMB(Builder, ARM_MB::ISH);
11538   }
11539   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11540 }
11541
11542 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11543                                           AtomicOrdering Ord, bool IsStore,
11544                                           bool IsLoad) const {
11545   if (!getInsertFencesForAtomic())
11546     return nullptr;
11547
11548   switch (Ord) {
11549   case NotAtomic:
11550   case Unordered:
11551     llvm_unreachable("Invalid fence: unordered/not-atomic");
11552   case Monotonic:
11553   case Release:
11554     return nullptr; // Nothing to do
11555   case Acquire:
11556   case AcquireRelease:
11557   case SequentiallyConsistent:
11558     return makeDMB(Builder, ARM_MB::ISH);
11559   }
11560   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11561 }
11562
11563 // Loads and stores less than 64-bits are already atomic; ones above that
11564 // are doomed anyway, so defer to the default libcall and blame the OS when
11565 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11566 // anything for those.
11567 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11568   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11569   return (Size == 64) && !Subtarget->isMClass();
11570 }
11571
11572 // Loads and stores less than 64-bits are already atomic; ones above that
11573 // are doomed anyway, so defer to the default libcall and blame the OS when
11574 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11575 // anything for those.
11576 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11577 // guarantee, see DDI0406C ARM architecture reference manual,
11578 // sections A8.8.72-74 LDRD)
11579 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11580   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11581   return (Size == 64) && !Subtarget->isMClass();
11582 }
11583
11584 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11585 // and up to 64 bits on the non-M profiles
11586 TargetLoweringBase::AtomicRMWExpansionKind
11587 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11588   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11589   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11590              ? AtomicRMWExpansionKind::LLSC
11591              : AtomicRMWExpansionKind::None;
11592 }
11593
11594 // This has so far only been implemented for MachO.
11595 bool ARMTargetLowering::useLoadStackGuardNode() const {
11596   return Subtarget->isTargetMachO();
11597 }
11598
11599 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11600                                                   unsigned &Cost) const {
11601   // If we do not have NEON, vector types are not natively supported.
11602   if (!Subtarget->hasNEON())
11603     return false;
11604
11605   // Floating point values and vector values map to the same register file.
11606   // Therefore, although we could do a store extract of a vector type, this is
11607   // better to leave at float as we have more freedom in the addressing mode for
11608   // those.
11609   if (VectorTy->isFPOrFPVectorTy())
11610     return false;
11611
11612   // If the index is unknown at compile time, this is very expensive to lower
11613   // and it is not possible to combine the store with the extract.
11614   if (!isa<ConstantInt>(Idx))
11615     return false;
11616
11617   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11618   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11619   // We can do a store + vector extract on any vector that fits perfectly in a D
11620   // or Q register.
11621   if (BitWidth == 64 || BitWidth == 128) {
11622     Cost = 0;
11623     return true;
11624   }
11625   return false;
11626 }
11627
11628 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11629                                          AtomicOrdering Ord) const {
11630   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11631   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11632   bool IsAcquire = isAtLeastAcquire(Ord);
11633
11634   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11635   // intrinsic must return {i32, i32} and we have to recombine them into a
11636   // single i64 here.
11637   if (ValTy->getPrimitiveSizeInBits() == 64) {
11638     Intrinsic::ID Int =
11639         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11640     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11641
11642     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11643     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11644
11645     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11646     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11647     if (!Subtarget->isLittle())
11648       std::swap (Lo, Hi);
11649     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11650     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11651     return Builder.CreateOr(
11652         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11653   }
11654
11655   Type *Tys[] = { Addr->getType() };
11656   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11657   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11658
11659   return Builder.CreateTruncOrBitCast(
11660       Builder.CreateCall(Ldrex, Addr),
11661       cast<PointerType>(Addr->getType())->getElementType());
11662 }
11663
11664 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11665                                                Value *Addr,
11666                                                AtomicOrdering Ord) const {
11667   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11668   bool IsRelease = isAtLeastRelease(Ord);
11669
11670   // Since the intrinsics must have legal type, the i64 intrinsics take two
11671   // parameters: "i32, i32". We must marshal Val into the appropriate form
11672   // before the call.
11673   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11674     Intrinsic::ID Int =
11675         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11676     Function *Strex = Intrinsic::getDeclaration(M, Int);
11677     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11678
11679     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11680     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11681     if (!Subtarget->isLittle())
11682       std::swap (Lo, Hi);
11683     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11684     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11685   }
11686
11687   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11688   Type *Tys[] = { Addr->getType() };
11689   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11690
11691   return Builder.CreateCall(
11692       Strex, {Builder.CreateZExtOrBitCast(
11693                   Val, Strex->getFunctionType()->getParamType(0)),
11694               Addr});
11695 }
11696
11697 /// \brief Lower an interleaved load into a vldN intrinsic.
11698 ///
11699 /// E.g. Lower an interleaved load (Factor = 2):
11700 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11701 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11702 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11703 ///
11704 ///      Into:
11705 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11706 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11707 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11708 bool ARMTargetLowering::lowerInterleavedLoad(
11709     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11710     ArrayRef<unsigned> Indices, unsigned Factor) const {
11711   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11712          "Invalid interleave factor");
11713   assert(!Shuffles.empty() && "Empty shufflevector input");
11714   assert(Shuffles.size() == Indices.size() &&
11715          "Unmatched number of shufflevectors and indices");
11716
11717   VectorType *VecTy = Shuffles[0]->getType();
11718   Type *EltTy = VecTy->getVectorElementType();
11719
11720   const DataLayout &DL = LI->getModule()->getDataLayout();
11721   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11722   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11723
11724   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11725   // support i64/f64 element).
11726   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11727     return false;
11728
11729   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11730   // load integer vectors first and then convert to pointer vectors.
11731   if (EltTy->isPointerTy())
11732     VecTy =
11733         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11734
11735   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11736                                             Intrinsic::arm_neon_vld3,
11737                                             Intrinsic::arm_neon_vld4};
11738
11739   Function *VldnFunc =
11740       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11741
11742   IRBuilder<> Builder(LI);
11743   SmallVector<Value *, 2> Ops;
11744
11745   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11746   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11747   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11748
11749   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11750
11751   // Replace uses of each shufflevector with the corresponding vector loaded
11752   // by ldN.
11753   for (unsigned i = 0; i < Shuffles.size(); i++) {
11754     ShuffleVectorInst *SV = Shuffles[i];
11755     unsigned Index = Indices[i];
11756
11757     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11758
11759     // Convert the integer vector to pointer vector if the element is pointer.
11760     if (EltTy->isPointerTy())
11761       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11762
11763     SV->replaceAllUsesWith(SubVec);
11764   }
11765
11766   return true;
11767 }
11768
11769 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11770 ///
11771 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11772 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11773                                    unsigned NumElts) {
11774   SmallVector<Constant *, 16> Mask;
11775   for (unsigned i = 0; i < NumElts; i++)
11776     Mask.push_back(Builder.getInt32(Start + i));
11777
11778   return ConstantVector::get(Mask);
11779 }
11780
11781 /// \brief Lower an interleaved store into a vstN intrinsic.
11782 ///
11783 /// E.g. Lower an interleaved store (Factor = 3):
11784 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11785 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11786 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11787 ///
11788 ///      Into:
11789 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11790 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11791 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11792 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11793 ///
11794 /// Note that the new shufflevectors will be removed and we'll only generate one
11795 /// vst3 instruction in CodeGen.
11796 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11797                                               ShuffleVectorInst *SVI,
11798                                               unsigned Factor) const {
11799   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11800          "Invalid interleave factor");
11801
11802   VectorType *VecTy = SVI->getType();
11803   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11804          "Invalid interleaved store");
11805
11806   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11807   Type *EltTy = VecTy->getVectorElementType();
11808   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11809
11810   const DataLayout &DL = SI->getModule()->getDataLayout();
11811   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11812   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11813
11814   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11815   // doesn't support i64/f64 element).
11816   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11817     return false;
11818
11819   Value *Op0 = SVI->getOperand(0);
11820   Value *Op1 = SVI->getOperand(1);
11821   IRBuilder<> Builder(SI);
11822
11823   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11824   // vectors to integer vectors.
11825   if (EltTy->isPointerTy()) {
11826     Type *IntTy = DL.getIntPtrType(EltTy);
11827
11828     // Convert to the corresponding integer vector.
11829     Type *IntVecTy =
11830         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11831     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11832     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11833
11834     SubVecTy = VectorType::get(IntTy, NumSubElts);
11835   }
11836
11837   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11838                                        Intrinsic::arm_neon_vst3,
11839                                        Intrinsic::arm_neon_vst4};
11840   Function *VstNFunc = Intrinsic::getDeclaration(
11841       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11842
11843   SmallVector<Value *, 6> Ops;
11844
11845   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11846   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11847
11848   // Split the shufflevector operands into sub vectors for the new vstN call.
11849   for (unsigned i = 0; i < Factor; i++)
11850     Ops.push_back(Builder.CreateShuffleVector(
11851         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11852
11853   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11854   Builder.CreateCall(VstNFunc, Ops);
11855   return true;
11856 }
11857
11858 enum HABaseType {
11859   HA_UNKNOWN = 0,
11860   HA_FLOAT,
11861   HA_DOUBLE,
11862   HA_VECT64,
11863   HA_VECT128
11864 };
11865
11866 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11867                                    uint64_t &Members) {
11868   if (auto *ST = dyn_cast<StructType>(Ty)) {
11869     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11870       uint64_t SubMembers = 0;
11871       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11872         return false;
11873       Members += SubMembers;
11874     }
11875   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11876     uint64_t SubMembers = 0;
11877     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11878       return false;
11879     Members += SubMembers * AT->getNumElements();
11880   } else if (Ty->isFloatTy()) {
11881     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11882       return false;
11883     Members = 1;
11884     Base = HA_FLOAT;
11885   } else if (Ty->isDoubleTy()) {
11886     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11887       return false;
11888     Members = 1;
11889     Base = HA_DOUBLE;
11890   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11891     Members = 1;
11892     switch (Base) {
11893     case HA_FLOAT:
11894     case HA_DOUBLE:
11895       return false;
11896     case HA_VECT64:
11897       return VT->getBitWidth() == 64;
11898     case HA_VECT128:
11899       return VT->getBitWidth() == 128;
11900     case HA_UNKNOWN:
11901       switch (VT->getBitWidth()) {
11902       case 64:
11903         Base = HA_VECT64;
11904         return true;
11905       case 128:
11906         Base = HA_VECT128;
11907         return true;
11908       default:
11909         return false;
11910       }
11911     }
11912   }
11913
11914   return (Members > 0 && Members <= 4);
11915 }
11916
11917 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11918 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11919 /// passing according to AAPCS rules.
11920 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11921     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11922   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11923       CallingConv::ARM_AAPCS_VFP)
11924     return false;
11925
11926   HABaseType Base = HA_UNKNOWN;
11927   uint64_t Members = 0;
11928   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11929   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11930
11931   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11932   return IsHA || IsIntArray;
11933 }