Fix unused variable warning introduced in r244314
[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 targetting 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   // We have target-specific dag combine patterns for the following nodes:
945   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
946   setTargetDAGCombine(ISD::ADD);
947   setTargetDAGCombine(ISD::SUB);
948   setTargetDAGCombine(ISD::MUL);
949   setTargetDAGCombine(ISD::AND);
950   setTargetDAGCombine(ISD::OR);
951   setTargetDAGCombine(ISD::XOR);
952
953   if (Subtarget->hasV6Ops())
954     setTargetDAGCombine(ISD::SRL);
955
956   setStackPointerRegisterToSaveRestore(ARM::SP);
957
958   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
959       !Subtarget->hasVFP2())
960     setSchedulingPreference(Sched::RegPressure);
961   else
962     setSchedulingPreference(Sched::Hybrid);
963
964   //// temporary - rewrite interface to use type
965   MaxStoresPerMemset = 8;
966   MaxStoresPerMemsetOptSize = 4;
967   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
968   MaxStoresPerMemcpyOptSize = 2;
969   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
970   MaxStoresPerMemmoveOptSize = 2;
971
972   // On ARM arguments smaller than 4 bytes are extended, so all arguments
973   // are at least 4 bytes aligned.
974   setMinStackArgumentAlignment(4);
975
976   // Prefer likely predicted branches to selects on out-of-order cores.
977   PredictableSelectIsExpensive = Subtarget->isLikeA9();
978
979   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
980 }
981
982 bool ARMTargetLowering::useSoftFloat() const {
983   return Subtarget->useSoftFloat();
984 }
985
986 // FIXME: It might make sense to define the representative register class as the
987 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
988 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
989 // SPR's representative would be DPR_VFP2. This should work well if register
990 // pressure tracking were modified such that a register use would increment the
991 // pressure of the register class's representative and all of it's super
992 // classes' representatives transitively. We have not implemented this because
993 // of the difficulty prior to coalescing of modeling operand register classes
994 // due to the common occurrence of cross class copies and subregister insertions
995 // and extractions.
996 std::pair<const TargetRegisterClass *, uint8_t>
997 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
998                                            MVT VT) const {
999   const TargetRegisterClass *RRC = nullptr;
1000   uint8_t Cost = 1;
1001   switch (VT.SimpleTy) {
1002   default:
1003     return TargetLowering::findRepresentativeClass(TRI, VT);
1004   // Use DPR as representative register class for all floating point
1005   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1006   // the cost is 1 for both f32 and f64.
1007   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1008   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1009     RRC = &ARM::DPRRegClass;
1010     // When NEON is used for SP, only half of the register file is available
1011     // because operations that define both SP and DP results will be constrained
1012     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1013     // coalescing by double-counting the SP regs. See the FIXME above.
1014     if (Subtarget->useNEONForSinglePrecisionFP())
1015       Cost = 2;
1016     break;
1017   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1018   case MVT::v4f32: case MVT::v2f64:
1019     RRC = &ARM::DPRRegClass;
1020     Cost = 2;
1021     break;
1022   case MVT::v4i64:
1023     RRC = &ARM::DPRRegClass;
1024     Cost = 4;
1025     break;
1026   case MVT::v8i64:
1027     RRC = &ARM::DPRRegClass;
1028     Cost = 8;
1029     break;
1030   }
1031   return std::make_pair(RRC, Cost);
1032 }
1033
1034 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1035   switch ((ARMISD::NodeType)Opcode) {
1036   case ARMISD::FIRST_NUMBER:  break;
1037   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1038   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1039   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1040   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1041   case ARMISD::CALL:          return "ARMISD::CALL";
1042   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1043   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1044   case ARMISD::tCALL:         return "ARMISD::tCALL";
1045   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1046   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1047   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1048   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1049   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1050   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1051   case ARMISD::CMP:           return "ARMISD::CMP";
1052   case ARMISD::CMN:           return "ARMISD::CMN";
1053   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1054   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1055   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1056   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1057   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1058
1059   case ARMISD::CMOV:          return "ARMISD::CMOV";
1060
1061   case ARMISD::RBIT:          return "ARMISD::RBIT";
1062
1063   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1064   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1065   case ARMISD::RRX:           return "ARMISD::RRX";
1066
1067   case ARMISD::ADDC:          return "ARMISD::ADDC";
1068   case ARMISD::ADDE:          return "ARMISD::ADDE";
1069   case ARMISD::SUBC:          return "ARMISD::SUBC";
1070   case ARMISD::SUBE:          return "ARMISD::SUBE";
1071
1072   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1073   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1074
1075   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1076   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1077   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1078
1079   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1080
1081   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1082
1083   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1084
1085   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1086
1087   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1088
1089   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1090
1091   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1092   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1093   case ARMISD::VCGE:          return "ARMISD::VCGE";
1094   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1095   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1096   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1097   case ARMISD::VCGT:          return "ARMISD::VCGT";
1098   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1099   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1100   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1101   case ARMISD::VTST:          return "ARMISD::VTST";
1102
1103   case ARMISD::VSHL:          return "ARMISD::VSHL";
1104   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1105   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1106   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1107   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1108   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1109   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1110   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1111   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1112   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1113   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1114   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1115   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1116   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1117   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1118   case ARMISD::VSLI:          return "ARMISD::VSLI";
1119   case ARMISD::VSRI:          return "ARMISD::VSRI";
1120   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1121   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1122   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1123   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1124   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1125   case ARMISD::VDUP:          return "ARMISD::VDUP";
1126   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1127   case ARMISD::VEXT:          return "ARMISD::VEXT";
1128   case ARMISD::VREV64:        return "ARMISD::VREV64";
1129   case ARMISD::VREV32:        return "ARMISD::VREV32";
1130   case ARMISD::VREV16:        return "ARMISD::VREV16";
1131   case ARMISD::VZIP:          return "ARMISD::VZIP";
1132   case ARMISD::VUZP:          return "ARMISD::VUZP";
1133   case ARMISD::VTRN:          return "ARMISD::VTRN";
1134   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1135   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1136   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1137   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1138   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1139   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1140   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1141   case ARMISD::FMAX:          return "ARMISD::FMAX";
1142   case ARMISD::FMIN:          return "ARMISD::FMIN";
1143   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1144   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1145   case ARMISD::BFI:           return "ARMISD::BFI";
1146   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1147   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1148   case ARMISD::VBSL:          return "ARMISD::VBSL";
1149   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1150   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1151   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1152   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1153   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1154   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1155   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1156   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1157   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1158   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1159   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1160   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1161   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1162   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1163   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1164   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1165   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1166   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1167   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1168   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1169   }
1170   return nullptr;
1171 }
1172
1173 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1174                                           EVT VT) const {
1175   if (!VT.isVector())
1176     return getPointerTy(DL);
1177   return VT.changeVectorElementTypeToInteger();
1178 }
1179
1180 /// getRegClassFor - Return the register class that should be used for the
1181 /// specified value type.
1182 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1183   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1184   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1185   // load / store 4 to 8 consecutive D registers.
1186   if (Subtarget->hasNEON()) {
1187     if (VT == MVT::v4i64)
1188       return &ARM::QQPRRegClass;
1189     if (VT == MVT::v8i64)
1190       return &ARM::QQQQPRRegClass;
1191   }
1192   return TargetLowering::getRegClassFor(VT);
1193 }
1194
1195 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1196 // source/dest is aligned and the copy size is large enough. We therefore want
1197 // to align such objects passed to memory intrinsics.
1198 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1199                                                unsigned &PrefAlign) const {
1200   if (!isa<MemIntrinsic>(CI))
1201     return false;
1202   MinSize = 8;
1203   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1204   // cycle faster than 4-byte aligned LDM.
1205   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1206   return true;
1207 }
1208
1209 // Create a fast isel object.
1210 FastISel *
1211 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1212                                   const TargetLibraryInfo *libInfo) const {
1213   return ARM::createFastISel(funcInfo, libInfo);
1214 }
1215
1216 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1217   unsigned NumVals = N->getNumValues();
1218   if (!NumVals)
1219     return Sched::RegPressure;
1220
1221   for (unsigned i = 0; i != NumVals; ++i) {
1222     EVT VT = N->getValueType(i);
1223     if (VT == MVT::Glue || VT == MVT::Other)
1224       continue;
1225     if (VT.isFloatingPoint() || VT.isVector())
1226       return Sched::ILP;
1227   }
1228
1229   if (!N->isMachineOpcode())
1230     return Sched::RegPressure;
1231
1232   // Load are scheduled for latency even if there instruction itinerary
1233   // is not available.
1234   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1235   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1236
1237   if (MCID.getNumDefs() == 0)
1238     return Sched::RegPressure;
1239   if (!Itins->isEmpty() &&
1240       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1241     return Sched::ILP;
1242
1243   return Sched::RegPressure;
1244 }
1245
1246 //===----------------------------------------------------------------------===//
1247 // Lowering Code
1248 //===----------------------------------------------------------------------===//
1249
1250 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1251 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1252   switch (CC) {
1253   default: llvm_unreachable("Unknown condition code!");
1254   case ISD::SETNE:  return ARMCC::NE;
1255   case ISD::SETEQ:  return ARMCC::EQ;
1256   case ISD::SETGT:  return ARMCC::GT;
1257   case ISD::SETGE:  return ARMCC::GE;
1258   case ISD::SETLT:  return ARMCC::LT;
1259   case ISD::SETLE:  return ARMCC::LE;
1260   case ISD::SETUGT: return ARMCC::HI;
1261   case ISD::SETUGE: return ARMCC::HS;
1262   case ISD::SETULT: return ARMCC::LO;
1263   case ISD::SETULE: return ARMCC::LS;
1264   }
1265 }
1266
1267 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1268 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1269                         ARMCC::CondCodes &CondCode2) {
1270   CondCode2 = ARMCC::AL;
1271   switch (CC) {
1272   default: llvm_unreachable("Unknown FP condition!");
1273   case ISD::SETEQ:
1274   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1275   case ISD::SETGT:
1276   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1277   case ISD::SETGE:
1278   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1279   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1280   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1281   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1282   case ISD::SETO:   CondCode = ARMCC::VC; break;
1283   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1284   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1285   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1286   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1287   case ISD::SETLT:
1288   case ISD::SETULT: CondCode = ARMCC::LT; break;
1289   case ISD::SETLE:
1290   case ISD::SETULE: CondCode = ARMCC::LE; break;
1291   case ISD::SETNE:
1292   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1293   }
1294 }
1295
1296 //===----------------------------------------------------------------------===//
1297 //                      Calling Convention Implementation
1298 //===----------------------------------------------------------------------===//
1299
1300 #include "ARMGenCallingConv.inc"
1301
1302 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1303 /// account presence of floating point hardware and calling convention
1304 /// limitations, such as support for variadic functions.
1305 CallingConv::ID
1306 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1307                                            bool isVarArg) const {
1308   switch (CC) {
1309   default:
1310     llvm_unreachable("Unsupported calling convention");
1311   case CallingConv::ARM_AAPCS:
1312   case CallingConv::ARM_APCS:
1313   case CallingConv::GHC:
1314     return CC;
1315   case CallingConv::ARM_AAPCS_VFP:
1316     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1317   case CallingConv::C:
1318     if (!Subtarget->isAAPCS_ABI())
1319       return CallingConv::ARM_APCS;
1320     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1321              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1322              !isVarArg)
1323       return CallingConv::ARM_AAPCS_VFP;
1324     else
1325       return CallingConv::ARM_AAPCS;
1326   case CallingConv::Fast:
1327     if (!Subtarget->isAAPCS_ABI()) {
1328       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1329         return CallingConv::Fast;
1330       return CallingConv::ARM_APCS;
1331     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1332       return CallingConv::ARM_AAPCS_VFP;
1333     else
1334       return CallingConv::ARM_AAPCS;
1335   }
1336 }
1337
1338 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1339 /// CallingConvention.
1340 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1341                                                  bool Return,
1342                                                  bool isVarArg) const {
1343   switch (getEffectiveCallingConv(CC, isVarArg)) {
1344   default:
1345     llvm_unreachable("Unsupported calling convention");
1346   case CallingConv::ARM_APCS:
1347     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1348   case CallingConv::ARM_AAPCS:
1349     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1350   case CallingConv::ARM_AAPCS_VFP:
1351     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1352   case CallingConv::Fast:
1353     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1354   case CallingConv::GHC:
1355     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1356   }
1357 }
1358
1359 /// LowerCallResult - Lower the result values of a call into the
1360 /// appropriate copies out of appropriate physical registers.
1361 SDValue
1362 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1363                                    CallingConv::ID CallConv, bool isVarArg,
1364                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1365                                    SDLoc dl, SelectionDAG &DAG,
1366                                    SmallVectorImpl<SDValue> &InVals,
1367                                    bool isThisReturn, SDValue ThisVal) const {
1368
1369   // Assign locations to each value returned by this call.
1370   SmallVector<CCValAssign, 16> RVLocs;
1371   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1372                     *DAG.getContext(), Call);
1373   CCInfo.AnalyzeCallResult(Ins,
1374                            CCAssignFnForNode(CallConv, /* Return*/ true,
1375                                              isVarArg));
1376
1377   // Copy all of the result registers out of their specified physreg.
1378   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1379     CCValAssign VA = RVLocs[i];
1380
1381     // Pass 'this' value directly from the argument to return value, to avoid
1382     // reg unit interference
1383     if (i == 0 && isThisReturn) {
1384       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1385              "unexpected return calling convention register assignment");
1386       InVals.push_back(ThisVal);
1387       continue;
1388     }
1389
1390     SDValue Val;
1391     if (VA.needsCustom()) {
1392       // Handle f64 or half of a v2f64.
1393       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1394                                       InFlag);
1395       Chain = Lo.getValue(1);
1396       InFlag = Lo.getValue(2);
1397       VA = RVLocs[++i]; // skip ahead to next loc
1398       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1399                                       InFlag);
1400       Chain = Hi.getValue(1);
1401       InFlag = Hi.getValue(2);
1402       if (!Subtarget->isLittle())
1403         std::swap (Lo, Hi);
1404       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1405
1406       if (VA.getLocVT() == MVT::v2f64) {
1407         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1408         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1409                           DAG.getConstant(0, dl, MVT::i32));
1410
1411         VA = RVLocs[++i]; // skip ahead to next loc
1412         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1413         Chain = Lo.getValue(1);
1414         InFlag = Lo.getValue(2);
1415         VA = RVLocs[++i]; // skip ahead to next loc
1416         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1417         Chain = Hi.getValue(1);
1418         InFlag = Hi.getValue(2);
1419         if (!Subtarget->isLittle())
1420           std::swap (Lo, Hi);
1421         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1422         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1423                           DAG.getConstant(1, dl, MVT::i32));
1424       }
1425     } else {
1426       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1427                                InFlag);
1428       Chain = Val.getValue(1);
1429       InFlag = Val.getValue(2);
1430     }
1431
1432     switch (VA.getLocInfo()) {
1433     default: llvm_unreachable("Unknown loc info!");
1434     case CCValAssign::Full: break;
1435     case CCValAssign::BCvt:
1436       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1437       break;
1438     }
1439
1440     InVals.push_back(Val);
1441   }
1442
1443   return Chain;
1444 }
1445
1446 /// LowerMemOpCallTo - Store the argument to the stack.
1447 SDValue
1448 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1449                                     SDValue StackPtr, SDValue Arg,
1450                                     SDLoc dl, SelectionDAG &DAG,
1451                                     const CCValAssign &VA,
1452                                     ISD::ArgFlagsTy Flags) const {
1453   unsigned LocMemOffset = VA.getLocMemOffset();
1454   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1455   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1456                        StackPtr, PtrOff);
1457   return DAG.getStore(Chain, dl, Arg, PtrOff,
1458                       MachinePointerInfo::getStack(LocMemOffset),
1459                       false, false, 0);
1460 }
1461
1462 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1463                                          SDValue Chain, SDValue &Arg,
1464                                          RegsToPassVector &RegsToPass,
1465                                          CCValAssign &VA, CCValAssign &NextVA,
1466                                          SDValue &StackPtr,
1467                                          SmallVectorImpl<SDValue> &MemOpChains,
1468                                          ISD::ArgFlagsTy Flags) const {
1469
1470   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1471                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1472   unsigned id = Subtarget->isLittle() ? 0 : 1;
1473   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1474
1475   if (NextVA.isRegLoc())
1476     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1477   else {
1478     assert(NextVA.isMemLoc());
1479     if (!StackPtr.getNode())
1480       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1481                                     getPointerTy(DAG.getDataLayout()));
1482
1483     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1484                                            dl, DAG, NextVA,
1485                                            Flags));
1486   }
1487 }
1488
1489 /// LowerCall - Lowering a call into a callseq_start <-
1490 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1491 /// nodes.
1492 SDValue
1493 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1494                              SmallVectorImpl<SDValue> &InVals) const {
1495   SelectionDAG &DAG                     = CLI.DAG;
1496   SDLoc &dl                             = CLI.DL;
1497   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1498   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1499   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1500   SDValue Chain                         = CLI.Chain;
1501   SDValue Callee                        = CLI.Callee;
1502   bool &isTailCall                      = CLI.IsTailCall;
1503   CallingConv::ID CallConv              = CLI.CallConv;
1504   bool doesNotRet                       = CLI.DoesNotReturn;
1505   bool isVarArg                         = CLI.IsVarArg;
1506
1507   MachineFunction &MF = DAG.getMachineFunction();
1508   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1509   bool isThisReturn   = false;
1510   bool isSibCall      = false;
1511   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1512
1513   // Disable tail calls if they're not supported.
1514   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1515     isTailCall = false;
1516
1517   if (isTailCall) {
1518     // Check if it's really possible to do a tail call.
1519     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1520                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1521                                                    Outs, OutVals, Ins, DAG);
1522     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1523       report_fatal_error("failed to perform tail call elimination on a call "
1524                          "site marked musttail");
1525     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1526     // detected sibcalls.
1527     if (isTailCall) {
1528       ++NumTailCalls;
1529       isSibCall = true;
1530     }
1531   }
1532
1533   // Analyze operands of the call, assigning locations to each operand.
1534   SmallVector<CCValAssign, 16> ArgLocs;
1535   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1536                     *DAG.getContext(), Call);
1537   CCInfo.AnalyzeCallOperands(Outs,
1538                              CCAssignFnForNode(CallConv, /* Return*/ false,
1539                                                isVarArg));
1540
1541   // Get a count of how many bytes are to be pushed on the stack.
1542   unsigned NumBytes = CCInfo.getNextStackOffset();
1543
1544   // For tail calls, memory operands are available in our caller's stack.
1545   if (isSibCall)
1546     NumBytes = 0;
1547
1548   // Adjust the stack pointer for the new arguments...
1549   // These operations are automatically eliminated by the prolog/epilog pass
1550   if (!isSibCall)
1551     Chain = DAG.getCALLSEQ_START(Chain,
1552                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1553
1554   SDValue StackPtr =
1555       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1556
1557   RegsToPassVector RegsToPass;
1558   SmallVector<SDValue, 8> MemOpChains;
1559
1560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1561   // of tail call optimization, arguments are handled later.
1562   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1563        i != e;
1564        ++i, ++realArgIdx) {
1565     CCValAssign &VA = ArgLocs[i];
1566     SDValue Arg = OutVals[realArgIdx];
1567     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1568     bool isByVal = Flags.isByVal();
1569
1570     // Promote the value if needed.
1571     switch (VA.getLocInfo()) {
1572     default: llvm_unreachable("Unknown loc info!");
1573     case CCValAssign::Full: break;
1574     case CCValAssign::SExt:
1575       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1576       break;
1577     case CCValAssign::ZExt:
1578       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1579       break;
1580     case CCValAssign::AExt:
1581       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1582       break;
1583     case CCValAssign::BCvt:
1584       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1585       break;
1586     }
1587
1588     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1589     if (VA.needsCustom()) {
1590       if (VA.getLocVT() == MVT::v2f64) {
1591         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1592                                   DAG.getConstant(0, dl, MVT::i32));
1593         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1594                                   DAG.getConstant(1, dl, MVT::i32));
1595
1596         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1597                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1598
1599         VA = ArgLocs[++i]; // skip ahead to next loc
1600         if (VA.isRegLoc()) {
1601           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1602                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1603         } else {
1604           assert(VA.isMemLoc());
1605
1606           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1607                                                  dl, DAG, VA, Flags));
1608         }
1609       } else {
1610         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1611                          StackPtr, MemOpChains, Flags);
1612       }
1613     } else if (VA.isRegLoc()) {
1614       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1615         assert(VA.getLocVT() == MVT::i32 &&
1616                "unexpected calling convention register assignment");
1617         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1618                "unexpected use of 'returned'");
1619         isThisReturn = true;
1620       }
1621       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1622     } else if (isByVal) {
1623       assert(VA.isMemLoc());
1624       unsigned offset = 0;
1625
1626       // True if this byval aggregate will be split between registers
1627       // and memory.
1628       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1629       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1630
1631       if (CurByValIdx < ByValArgsCount) {
1632
1633         unsigned RegBegin, RegEnd;
1634         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1635
1636         EVT PtrVT =
1637             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1638         unsigned int i, j;
1639         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1640           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1641           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1642           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1643                                      MachinePointerInfo(),
1644                                      false, false, false,
1645                                      DAG.InferPtrAlignment(AddArg));
1646           MemOpChains.push_back(Load.getValue(1));
1647           RegsToPass.push_back(std::make_pair(j, Load));
1648         }
1649
1650         // If parameter size outsides register area, "offset" value
1651         // helps us to calculate stack slot for remained part properly.
1652         offset = RegEnd - RegBegin;
1653
1654         CCInfo.nextInRegsParam();
1655       }
1656
1657       if (Flags.getByValSize() > 4*offset) {
1658         auto PtrVT = getPointerTy(DAG.getDataLayout());
1659         unsigned LocMemOffset = VA.getLocMemOffset();
1660         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1661         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1662         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1663         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1664         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1665                                            MVT::i32);
1666         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1667                                             MVT::i32);
1668
1669         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1670         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1671         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1672                                           Ops));
1673       }
1674     } else if (!isSibCall) {
1675       assert(VA.isMemLoc());
1676
1677       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1678                                              dl, DAG, VA, Flags));
1679     }
1680   }
1681
1682   if (!MemOpChains.empty())
1683     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1684
1685   // Build a sequence of copy-to-reg nodes chained together with token chain
1686   // and flag operands which copy the outgoing args into the appropriate regs.
1687   SDValue InFlag;
1688   // Tail call byval lowering might overwrite argument registers so in case of
1689   // tail call optimization the copies to registers are lowered later.
1690   if (!isTailCall)
1691     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1692       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1693                                RegsToPass[i].second, InFlag);
1694       InFlag = Chain.getValue(1);
1695     }
1696
1697   // For tail calls lower the arguments to the 'real' stack slot.
1698   if (isTailCall) {
1699     // Force all the incoming stack arguments to be loaded from the stack
1700     // before any new outgoing arguments are stored to the stack, because the
1701     // outgoing stack slots may alias the incoming argument stack slots, and
1702     // the alias isn't otherwise explicit. This is slightly more conservative
1703     // than necessary, because it means that each store effectively depends
1704     // on every argument instead of just those arguments it would clobber.
1705
1706     // Do not flag preceding copytoreg stuff together with the following stuff.
1707     InFlag = SDValue();
1708     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1709       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1710                                RegsToPass[i].second, InFlag);
1711       InFlag = Chain.getValue(1);
1712     }
1713     InFlag = SDValue();
1714   }
1715
1716   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1717   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1718   // node so that legalize doesn't hack it.
1719   bool isDirect = false;
1720   bool isARMFunc = false;
1721   bool isLocalARMFunc = false;
1722   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1723   auto PtrVt = getPointerTy(DAG.getDataLayout());
1724
1725   if (Subtarget->genLongCalls()) {
1726     assert((Subtarget->isTargetWindows() ||
1727             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1728            "long-calls with non-static relocation model!");
1729     // Handle a global address or an external symbol. If it's not one of
1730     // those, the target's already in a register, so we don't need to do
1731     // anything extra.
1732     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1733       const GlobalValue *GV = G->getGlobal();
1734       // Create a constant pool entry for the callee address
1735       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1736       ARMConstantPoolValue *CPV =
1737         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1738
1739       // Get the address of the callee into a register
1740       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1741       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1742       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1743                            MachinePointerInfo::getConstantPool(), false, false,
1744                            false, 0);
1745     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1746       const char *Sym = S->getSymbol();
1747
1748       // Create a constant pool entry for the callee address
1749       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1750       ARMConstantPoolValue *CPV =
1751         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1752                                       ARMPCLabelIndex, 0);
1753       // Get the address of the callee into a register
1754       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1755       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1756       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1757                            MachinePointerInfo::getConstantPool(), false, false,
1758                            false, 0);
1759     }
1760   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1761     const GlobalValue *GV = G->getGlobal();
1762     isDirect = true;
1763     bool isDef = GV->isStrongDefinitionForLinker();
1764     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1765                    getTargetMachine().getRelocationModel() != Reloc::Static;
1766     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1767     // ARM call to a local ARM function is predicable.
1768     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1769     // tBX takes a register source operand.
1770     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1771       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1772       Callee = DAG.getNode(
1773           ARMISD::WrapperPIC, dl, PtrVt,
1774           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1775       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1776                            MachinePointerInfo::getGOT(), false, false, true, 0);
1777     } else if (Subtarget->isTargetCOFF()) {
1778       assert(Subtarget->isTargetWindows() &&
1779              "Windows is the only supported COFF target");
1780       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1781                                  ? ARMII::MO_DLLIMPORT
1782                                  : ARMII::MO_NO_FLAG;
1783       Callee =
1784           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1785       if (GV->hasDLLImportStorageClass())
1786         Callee =
1787             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1788                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1789                         MachinePointerInfo::getGOT(), false, false, false, 0);
1790     } else {
1791       // On ELF targets for PIC code, direct calls should go through the PLT
1792       unsigned OpFlags = 0;
1793       if (Subtarget->isTargetELF() &&
1794           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1795         OpFlags = ARMII::MO_PLT;
1796       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1797     }
1798   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1799     isDirect = true;
1800     bool isStub = Subtarget->isTargetMachO() &&
1801                   getTargetMachine().getRelocationModel() != Reloc::Static;
1802     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1803     // tBX takes a register source operand.
1804     const char *Sym = S->getSymbol();
1805     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1806       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1807       ARMConstantPoolValue *CPV =
1808         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1809                                       ARMPCLabelIndex, 4);
1810       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1811       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1812       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1813                            MachinePointerInfo::getConstantPool(), false, false,
1814                            false, 0);
1815       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1816       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1817     } else {
1818       unsigned OpFlags = 0;
1819       // On ELF targets for PIC code, direct calls should go through the PLT
1820       if (Subtarget->isTargetELF() &&
1821                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1822         OpFlags = ARMII::MO_PLT;
1823       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1824     }
1825   }
1826
1827   // FIXME: handle tail calls differently.
1828   unsigned CallOpc;
1829   if (Subtarget->isThumb()) {
1830     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1831       CallOpc = ARMISD::CALL_NOLINK;
1832     else
1833       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1834   } else {
1835     if (!isDirect && !Subtarget->hasV5TOps())
1836       CallOpc = ARMISD::CALL_NOLINK;
1837     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1838              // Emit regular call when code size is the priority
1839              !MF.getFunction()->optForMinSize())
1840       // "mov lr, pc; b _foo" to avoid confusing the RSP
1841       CallOpc = ARMISD::CALL_NOLINK;
1842     else
1843       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1844   }
1845
1846   std::vector<SDValue> Ops;
1847   Ops.push_back(Chain);
1848   Ops.push_back(Callee);
1849
1850   // Add argument registers to the end of the list so that they are known live
1851   // into the call.
1852   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1853     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1854                                   RegsToPass[i].second.getValueType()));
1855
1856   // Add a register mask operand representing the call-preserved registers.
1857   if (!isTailCall) {
1858     const uint32_t *Mask;
1859     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1860     if (isThisReturn) {
1861       // For 'this' returns, use the R0-preserving mask if applicable
1862       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1863       if (!Mask) {
1864         // Set isThisReturn to false if the calling convention is not one that
1865         // allows 'returned' to be modeled in this way, so LowerCallResult does
1866         // not try to pass 'this' straight through
1867         isThisReturn = false;
1868         Mask = ARI->getCallPreservedMask(MF, CallConv);
1869       }
1870     } else
1871       Mask = ARI->getCallPreservedMask(MF, CallConv);
1872
1873     assert(Mask && "Missing call preserved mask for calling convention");
1874     Ops.push_back(DAG.getRegisterMask(Mask));
1875   }
1876
1877   if (InFlag.getNode())
1878     Ops.push_back(InFlag);
1879
1880   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1881   if (isTailCall) {
1882     MF.getFrameInfo()->setHasTailCall();
1883     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1884   }
1885
1886   // Returns a chain and a flag for retval copy to use.
1887   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1888   InFlag = Chain.getValue(1);
1889
1890   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1891                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1892   if (!Ins.empty())
1893     InFlag = Chain.getValue(1);
1894
1895   // Handle result values, copying them out of physregs into vregs that we
1896   // return.
1897   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1898                          InVals, isThisReturn,
1899                          isThisReturn ? OutVals[0] : SDValue());
1900 }
1901
1902 /// HandleByVal - Every parameter *after* a byval parameter is passed
1903 /// on the stack.  Remember the next parameter register to allocate,
1904 /// and then confiscate the rest of the parameter registers to insure
1905 /// this.
1906 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1907                                     unsigned Align) const {
1908   assert((State->getCallOrPrologue() == Prologue ||
1909           State->getCallOrPrologue() == Call) &&
1910          "unhandled ParmContext");
1911
1912   // Byval (as with any stack) slots are always at least 4 byte aligned.
1913   Align = std::max(Align, 4U);
1914
1915   unsigned Reg = State->AllocateReg(GPRArgRegs);
1916   if (!Reg)
1917     return;
1918
1919   unsigned AlignInRegs = Align / 4;
1920   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1921   for (unsigned i = 0; i < Waste; ++i)
1922     Reg = State->AllocateReg(GPRArgRegs);
1923
1924   if (!Reg)
1925     return;
1926
1927   unsigned Excess = 4 * (ARM::R4 - Reg);
1928
1929   // Special case when NSAA != SP and parameter size greater than size of
1930   // all remained GPR regs. In that case we can't split parameter, we must
1931   // send it to stack. We also must set NCRN to R4, so waste all
1932   // remained registers.
1933   const unsigned NSAAOffset = State->getNextStackOffset();
1934   if (NSAAOffset != 0 && Size > Excess) {
1935     while (State->AllocateReg(GPRArgRegs))
1936       ;
1937     return;
1938   }
1939
1940   // First register for byval parameter is the first register that wasn't
1941   // allocated before this method call, so it would be "reg".
1942   // If parameter is small enough to be saved in range [reg, r4), then
1943   // the end (first after last) register would be reg + param-size-in-regs,
1944   // else parameter would be splitted between registers and stack,
1945   // end register would be r4 in this case.
1946   unsigned ByValRegBegin = Reg;
1947   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1948   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1949   // Note, first register is allocated in the beginning of function already,
1950   // allocate remained amount of registers we need.
1951   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1952     State->AllocateReg(GPRArgRegs);
1953   // A byval parameter that is split between registers and memory needs its
1954   // size truncated here.
1955   // In the case where the entire structure fits in registers, we set the
1956   // size in memory to zero.
1957   Size = std::max<int>(Size - Excess, 0);
1958 }
1959
1960 /// MatchingStackOffset - Return true if the given stack call argument is
1961 /// already available in the same position (relatively) of the caller's
1962 /// incoming argument stack.
1963 static
1964 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1965                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1966                          const TargetInstrInfo *TII) {
1967   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1968   int FI = INT_MAX;
1969   if (Arg.getOpcode() == ISD::CopyFromReg) {
1970     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1971     if (!TargetRegisterInfo::isVirtualRegister(VR))
1972       return false;
1973     MachineInstr *Def = MRI->getVRegDef(VR);
1974     if (!Def)
1975       return false;
1976     if (!Flags.isByVal()) {
1977       if (!TII->isLoadFromStackSlot(Def, FI))
1978         return false;
1979     } else {
1980       return false;
1981     }
1982   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1983     if (Flags.isByVal())
1984       // ByVal argument is passed in as a pointer but it's now being
1985       // dereferenced. e.g.
1986       // define @foo(%struct.X* %A) {
1987       //   tail call @bar(%struct.X* byval %A)
1988       // }
1989       return false;
1990     SDValue Ptr = Ld->getBasePtr();
1991     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1992     if (!FINode)
1993       return false;
1994     FI = FINode->getIndex();
1995   } else
1996     return false;
1997
1998   assert(FI != INT_MAX);
1999   if (!MFI->isFixedObjectIndex(FI))
2000     return false;
2001   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2002 }
2003
2004 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2005 /// for tail call optimization. Targets which want to do tail call
2006 /// optimization should implement this function.
2007 bool
2008 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2009                                                      CallingConv::ID CalleeCC,
2010                                                      bool isVarArg,
2011                                                      bool isCalleeStructRet,
2012                                                      bool isCallerStructRet,
2013                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2014                                     const SmallVectorImpl<SDValue> &OutVals,
2015                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2016                                                      SelectionDAG& DAG) const {
2017   const Function *CallerF = DAG.getMachineFunction().getFunction();
2018   CallingConv::ID CallerCC = CallerF->getCallingConv();
2019   bool CCMatch = CallerCC == CalleeCC;
2020
2021   // Look for obvious safe cases to perform tail call optimization that do not
2022   // require ABI changes. This is what gcc calls sibcall.
2023
2024   // Do not sibcall optimize vararg calls unless the call site is not passing
2025   // any arguments.
2026   if (isVarArg && !Outs.empty())
2027     return false;
2028
2029   // Exception-handling functions need a special set of instructions to indicate
2030   // a return to the hardware. Tail-calling another function would probably
2031   // break this.
2032   if (CallerF->hasFnAttribute("interrupt"))
2033     return false;
2034
2035   // Also avoid sibcall optimization if either caller or callee uses struct
2036   // return semantics.
2037   if (isCalleeStructRet || isCallerStructRet)
2038     return false;
2039
2040   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2041   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2042   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2043   // support in the assembler and linker to be used. This would need to be
2044   // fixed to fully support tail calls in Thumb1.
2045   //
2046   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2047   // LR.  This means if we need to reload LR, it takes an extra instructions,
2048   // which outweighs the value of the tail call; but here we don't know yet
2049   // whether LR is going to be used.  Probably the right approach is to
2050   // generate the tail call here and turn it back into CALL/RET in
2051   // emitEpilogue if LR is used.
2052
2053   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2054   // but we need to make sure there are enough registers; the only valid
2055   // registers are the 4 used for parameters.  We don't currently do this
2056   // case.
2057   if (Subtarget->isThumb1Only())
2058     return false;
2059
2060   // Externally-defined functions with weak linkage should not be
2061   // tail-called on ARM when the OS does not support dynamic
2062   // pre-emption of symbols, as the AAELF spec requires normal calls
2063   // to undefined weak functions to be replaced with a NOP or jump to the
2064   // next instruction. The behaviour of branch instructions in this
2065   // situation (as used for tail calls) is implementation-defined, so we
2066   // cannot rely on the linker replacing the tail call with a return.
2067   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2068     const GlobalValue *GV = G->getGlobal();
2069     const Triple &TT = getTargetMachine().getTargetTriple();
2070     if (GV->hasExternalWeakLinkage() &&
2071         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2072       return false;
2073   }
2074
2075   // If the calling conventions do not match, then we'd better make sure the
2076   // results are returned in the same way as what the caller expects.
2077   if (!CCMatch) {
2078     SmallVector<CCValAssign, 16> RVLocs1;
2079     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2080                        *DAG.getContext(), Call);
2081     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2082
2083     SmallVector<CCValAssign, 16> RVLocs2;
2084     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2085                        *DAG.getContext(), Call);
2086     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2087
2088     if (RVLocs1.size() != RVLocs2.size())
2089       return false;
2090     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2091       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2092         return false;
2093       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2094         return false;
2095       if (RVLocs1[i].isRegLoc()) {
2096         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2097           return false;
2098       } else {
2099         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2100           return false;
2101       }
2102     }
2103   }
2104
2105   // If Caller's vararg or byval argument has been split between registers and
2106   // stack, do not perform tail call, since part of the argument is in caller's
2107   // local frame.
2108   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2109                                       getInfo<ARMFunctionInfo>();
2110   if (AFI_Caller->getArgRegsSaveSize())
2111     return false;
2112
2113   // If the callee takes no arguments then go on to check the results of the
2114   // call.
2115   if (!Outs.empty()) {
2116     // Check if stack adjustment is needed. For now, do not do this if any
2117     // argument is passed on the stack.
2118     SmallVector<CCValAssign, 16> ArgLocs;
2119     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2120                       *DAG.getContext(), Call);
2121     CCInfo.AnalyzeCallOperands(Outs,
2122                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2123     if (CCInfo.getNextStackOffset()) {
2124       MachineFunction &MF = DAG.getMachineFunction();
2125
2126       // Check if the arguments are already laid out in the right way as
2127       // the caller's fixed stack objects.
2128       MachineFrameInfo *MFI = MF.getFrameInfo();
2129       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2130       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2131       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2132            i != e;
2133            ++i, ++realArgIdx) {
2134         CCValAssign &VA = ArgLocs[i];
2135         EVT RegVT = VA.getLocVT();
2136         SDValue Arg = OutVals[realArgIdx];
2137         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2138         if (VA.getLocInfo() == CCValAssign::Indirect)
2139           return false;
2140         if (VA.needsCustom()) {
2141           // f64 and vector types are split into multiple registers or
2142           // register/stack-slot combinations.  The types will not match
2143           // the registers; give up on memory f64 refs until we figure
2144           // out what to do about this.
2145           if (!VA.isRegLoc())
2146             return false;
2147           if (!ArgLocs[++i].isRegLoc())
2148             return false;
2149           if (RegVT == MVT::v2f64) {
2150             if (!ArgLocs[++i].isRegLoc())
2151               return false;
2152             if (!ArgLocs[++i].isRegLoc())
2153               return false;
2154           }
2155         } else if (!VA.isRegLoc()) {
2156           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2157                                    MFI, MRI, TII))
2158             return false;
2159         }
2160       }
2161     }
2162   }
2163
2164   return true;
2165 }
2166
2167 bool
2168 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2169                                   MachineFunction &MF, bool isVarArg,
2170                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2171                                   LLVMContext &Context) const {
2172   SmallVector<CCValAssign, 16> RVLocs;
2173   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2174   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2175                                                     isVarArg));
2176 }
2177
2178 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2179                                     SDLoc DL, SelectionDAG &DAG) {
2180   const MachineFunction &MF = DAG.getMachineFunction();
2181   const Function *F = MF.getFunction();
2182
2183   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2184
2185   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2186   // version of the "preferred return address". These offsets affect the return
2187   // instruction if this is a return from PL1 without hypervisor extensions.
2188   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2189   //    SWI:     0      "subs pc, lr, #0"
2190   //    ABORT:   +4     "subs pc, lr, #4"
2191   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2192   // UNDEF varies depending on where the exception came from ARM or Thumb
2193   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2194
2195   int64_t LROffset;
2196   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2197       IntKind == "ABORT")
2198     LROffset = 4;
2199   else if (IntKind == "SWI" || IntKind == "UNDEF")
2200     LROffset = 0;
2201   else
2202     report_fatal_error("Unsupported interrupt attribute. If present, value "
2203                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2204
2205   RetOps.insert(RetOps.begin() + 1,
2206                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2207
2208   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2209 }
2210
2211 SDValue
2212 ARMTargetLowering::LowerReturn(SDValue Chain,
2213                                CallingConv::ID CallConv, bool isVarArg,
2214                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2215                                const SmallVectorImpl<SDValue> &OutVals,
2216                                SDLoc dl, SelectionDAG &DAG) const {
2217
2218   // CCValAssign - represent the assignment of the return value to a location.
2219   SmallVector<CCValAssign, 16> RVLocs;
2220
2221   // CCState - Info about the registers and stack slots.
2222   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2223                     *DAG.getContext(), Call);
2224
2225   // Analyze outgoing return values.
2226   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2227                                                isVarArg));
2228
2229   SDValue Flag;
2230   SmallVector<SDValue, 4> RetOps;
2231   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2232   bool isLittleEndian = Subtarget->isLittle();
2233
2234   MachineFunction &MF = DAG.getMachineFunction();
2235   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2236   AFI->setReturnRegsCount(RVLocs.size());
2237
2238   // Copy the result values into the output registers.
2239   for (unsigned i = 0, realRVLocIdx = 0;
2240        i != RVLocs.size();
2241        ++i, ++realRVLocIdx) {
2242     CCValAssign &VA = RVLocs[i];
2243     assert(VA.isRegLoc() && "Can only return in registers!");
2244
2245     SDValue Arg = OutVals[realRVLocIdx];
2246
2247     switch (VA.getLocInfo()) {
2248     default: llvm_unreachable("Unknown loc info!");
2249     case CCValAssign::Full: break;
2250     case CCValAssign::BCvt:
2251       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2252       break;
2253     }
2254
2255     if (VA.needsCustom()) {
2256       if (VA.getLocVT() == MVT::v2f64) {
2257         // Extract the first half and return it in two registers.
2258         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2259                                    DAG.getConstant(0, dl, MVT::i32));
2260         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2261                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2262
2263         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2264                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2265                                  Flag);
2266         Flag = Chain.getValue(1);
2267         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2268         VA = RVLocs[++i]; // skip ahead to next loc
2269         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2270                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
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
2276         // Extract the 2nd half and fall through to handle it as an f64 value.
2277         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2278                           DAG.getConstant(1, dl, MVT::i32));
2279       }
2280       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2281       // available.
2282       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2283                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2284       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2285                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2286                                Flag);
2287       Flag = Chain.getValue(1);
2288       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2289       VA = RVLocs[++i]; // skip ahead to next loc
2290       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2291                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2292                                Flag);
2293     } else
2294       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2295
2296     // Guarantee that all emitted copies are
2297     // stuck together, avoiding something bad.
2298     Flag = Chain.getValue(1);
2299     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2300   }
2301
2302   // Update chain and glue.
2303   RetOps[0] = Chain;
2304   if (Flag.getNode())
2305     RetOps.push_back(Flag);
2306
2307   // CPUs which aren't M-class use a special sequence to return from
2308   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2309   // though we use "subs pc, lr, #N").
2310   //
2311   // M-class CPUs actually use a normal return sequence with a special
2312   // (hardware-provided) value in LR, so the normal code path works.
2313   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2314       !Subtarget->isMClass()) {
2315     if (Subtarget->isThumb1Only())
2316       report_fatal_error("interrupt attribute is not supported in Thumb1");
2317     return LowerInterruptReturn(RetOps, dl, DAG);
2318   }
2319
2320   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2321 }
2322
2323 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2324   if (N->getNumValues() != 1)
2325     return false;
2326   if (!N->hasNUsesOfValue(1, 0))
2327     return false;
2328
2329   SDValue TCChain = Chain;
2330   SDNode *Copy = *N->use_begin();
2331   if (Copy->getOpcode() == ISD::CopyToReg) {
2332     // If the copy has a glue operand, we conservatively assume it isn't safe to
2333     // perform a tail call.
2334     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2335       return false;
2336     TCChain = Copy->getOperand(0);
2337   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2338     SDNode *VMov = Copy;
2339     // f64 returned in a pair of GPRs.
2340     SmallPtrSet<SDNode*, 2> Copies;
2341     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2342          UI != UE; ++UI) {
2343       if (UI->getOpcode() != ISD::CopyToReg)
2344         return false;
2345       Copies.insert(*UI);
2346     }
2347     if (Copies.size() > 2)
2348       return false;
2349
2350     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2351          UI != UE; ++UI) {
2352       SDValue UseChain = UI->getOperand(0);
2353       if (Copies.count(UseChain.getNode()))
2354         // Second CopyToReg
2355         Copy = *UI;
2356       else {
2357         // We are at the top of this chain.
2358         // If the copy has a glue operand, we conservatively assume it
2359         // isn't safe to perform a tail call.
2360         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2361           return false;
2362         // First CopyToReg
2363         TCChain = UseChain;
2364       }
2365     }
2366   } else if (Copy->getOpcode() == ISD::BITCAST) {
2367     // f32 returned in a single GPR.
2368     if (!Copy->hasOneUse())
2369       return false;
2370     Copy = *Copy->use_begin();
2371     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2372       return false;
2373     // If the copy has a glue operand, we conservatively assume it isn't safe to
2374     // perform a tail call.
2375     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2376       return false;
2377     TCChain = Copy->getOperand(0);
2378   } else {
2379     return false;
2380   }
2381
2382   bool HasRet = false;
2383   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2384        UI != UE; ++UI) {
2385     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2386         UI->getOpcode() != ARMISD::INTRET_FLAG)
2387       return false;
2388     HasRet = true;
2389   }
2390
2391   if (!HasRet)
2392     return false;
2393
2394   Chain = TCChain;
2395   return true;
2396 }
2397
2398 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2399   if (!Subtarget->supportsTailCall())
2400     return false;
2401
2402   auto Attr =
2403       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2404   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2405     return false;
2406
2407   return !Subtarget->isThumb1Only();
2408 }
2409
2410 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2411 // and pass the lower and high parts through.
2412 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2413   SDLoc DL(Op);
2414   SDValue WriteValue = Op->getOperand(2);
2415
2416   // This function is only supposed to be called for i64 type argument.
2417   assert(WriteValue.getValueType() == MVT::i64
2418           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2419
2420   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2421                            DAG.getConstant(0, DL, MVT::i32));
2422   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2423                            DAG.getConstant(1, DL, MVT::i32));
2424   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2425   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2426 }
2427
2428 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2429 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2430 // one of the above mentioned nodes. It has to be wrapped because otherwise
2431 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2432 // be used to form addressing mode. These wrapped nodes will be selected
2433 // into MOVi.
2434 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2435   EVT PtrVT = Op.getValueType();
2436   // FIXME there is no actual debug info here
2437   SDLoc dl(Op);
2438   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2439   SDValue Res;
2440   if (CP->isMachineConstantPoolEntry())
2441     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2442                                     CP->getAlignment());
2443   else
2444     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2445                                     CP->getAlignment());
2446   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2447 }
2448
2449 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2450   return MachineJumpTableInfo::EK_Inline;
2451 }
2452
2453 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2454                                              SelectionDAG &DAG) const {
2455   MachineFunction &MF = DAG.getMachineFunction();
2456   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2457   unsigned ARMPCLabelIndex = 0;
2458   SDLoc DL(Op);
2459   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2460   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2461   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2462   SDValue CPAddr;
2463   if (RelocM == Reloc::Static) {
2464     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2465   } else {
2466     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2467     ARMPCLabelIndex = AFI->createPICLabelUId();
2468     ARMConstantPoolValue *CPV =
2469       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2470                                       ARMCP::CPBlockAddress, PCAdj);
2471     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2472   }
2473   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2474   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2475                                MachinePointerInfo::getConstantPool(),
2476                                false, false, false, 0);
2477   if (RelocM == Reloc::Static)
2478     return Result;
2479   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2480   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2481 }
2482
2483 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2484 SDValue
2485 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2486                                                  SelectionDAG &DAG) const {
2487   SDLoc dl(GA);
2488   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2489   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2490   MachineFunction &MF = DAG.getMachineFunction();
2491   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2492   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2493   ARMConstantPoolValue *CPV =
2494     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2495                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2496   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2497   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2498   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2499                          MachinePointerInfo::getConstantPool(),
2500                          false, false, false, 0);
2501   SDValue Chain = Argument.getValue(1);
2502
2503   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2504   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2505
2506   // call __tls_get_addr.
2507   ArgListTy Args;
2508   ArgListEntry Entry;
2509   Entry.Node = Argument;
2510   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2511   Args.push_back(Entry);
2512
2513   // FIXME: is there useful debug info available here?
2514   TargetLowering::CallLoweringInfo CLI(DAG);
2515   CLI.setDebugLoc(dl).setChain(Chain)
2516     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2517                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2518                0);
2519
2520   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2521   return CallResult.first;
2522 }
2523
2524 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2525 // "local exec" model.
2526 SDValue
2527 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2528                                         SelectionDAG &DAG,
2529                                         TLSModel::Model model) const {
2530   const GlobalValue *GV = GA->getGlobal();
2531   SDLoc dl(GA);
2532   SDValue Offset;
2533   SDValue Chain = DAG.getEntryNode();
2534   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2535   // Get the Thread Pointer
2536   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2537
2538   if (model == TLSModel::InitialExec) {
2539     MachineFunction &MF = DAG.getMachineFunction();
2540     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2541     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2542     // Initial exec model.
2543     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2544     ARMConstantPoolValue *CPV =
2545       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2546                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2547                                       true);
2548     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2549     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2550     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2551                          MachinePointerInfo::getConstantPool(),
2552                          false, false, false, 0);
2553     Chain = Offset.getValue(1);
2554
2555     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2556     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2557
2558     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2559                          MachinePointerInfo::getConstantPool(),
2560                          false, false, false, 0);
2561   } else {
2562     // local exec model
2563     assert(model == TLSModel::LocalExec);
2564     ARMConstantPoolValue *CPV =
2565       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2566     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2567     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2568     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2569                          MachinePointerInfo::getConstantPool(),
2570                          false, false, false, 0);
2571   }
2572
2573   // The address of the thread local variable is the add of the thread
2574   // pointer with the offset of the variable.
2575   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2576 }
2577
2578 SDValue
2579 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2580   // TODO: implement the "local dynamic" model
2581   assert(Subtarget->isTargetELF() &&
2582          "TLS not implemented for non-ELF targets");
2583   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2584   if (DAG.getTarget().Options.EmulatedTLS)
2585     return LowerToTLSEmulatedModel(GA, DAG);
2586
2587   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2588
2589   switch (model) {
2590     case TLSModel::GeneralDynamic:
2591     case TLSModel::LocalDynamic:
2592       return LowerToTLSGeneralDynamicModel(GA, DAG);
2593     case TLSModel::InitialExec:
2594     case TLSModel::LocalExec:
2595       return LowerToTLSExecModels(GA, DAG, model);
2596   }
2597   llvm_unreachable("bogus TLS model");
2598 }
2599
2600 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2601                                                  SelectionDAG &DAG) const {
2602   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2603   SDLoc dl(Op);
2604   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2605   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2606     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2607     ARMConstantPoolValue *CPV =
2608       ARMConstantPoolConstant::Create(GV,
2609                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2610     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2611     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2612     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2613                                  CPAddr,
2614                                  MachinePointerInfo::getConstantPool(),
2615                                  false, false, false, 0);
2616     SDValue Chain = Result.getValue(1);
2617     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2618     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2619     if (!UseGOTOFF)
2620       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2621                            MachinePointerInfo::getGOT(),
2622                            false, false, false, 0);
2623     return Result;
2624   }
2625
2626   // If we have T2 ops, we can materialize the address directly via movt/movw
2627   // pair. This is always cheaper.
2628   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2629     ++NumMovwMovt;
2630     // FIXME: Once remat is capable of dealing with instructions with register
2631     // operands, expand this into two nodes.
2632     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2633                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2634   } else {
2635     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2636     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2637     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2638                        MachinePointerInfo::getConstantPool(),
2639                        false, false, false, 0);
2640   }
2641 }
2642
2643 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2644                                                     SelectionDAG &DAG) const {
2645   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2646   SDLoc dl(Op);
2647   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2648   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2649
2650   if (Subtarget->useMovt(DAG.getMachineFunction()))
2651     ++NumMovwMovt;
2652
2653   // FIXME: Once remat is capable of dealing with instructions with register
2654   // operands, expand this into multiple nodes
2655   unsigned Wrapper =
2656       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2657
2658   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2659   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2660
2661   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2662     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2663                          MachinePointerInfo::getGOT(), false, false, false, 0);
2664   return Result;
2665 }
2666
2667 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2668                                                      SelectionDAG &DAG) const {
2669   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2670   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2671          "Windows on ARM expects to use movw/movt");
2672
2673   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2674   const ARMII::TOF TargetFlags =
2675     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2676   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2677   SDValue Result;
2678   SDLoc DL(Op);
2679
2680   ++NumMovwMovt;
2681
2682   // FIXME: Once remat is capable of dealing with instructions with register
2683   // operands, expand this into two nodes.
2684   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2685                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2686                                                   TargetFlags));
2687   if (GV->hasDLLImportStorageClass())
2688     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2689                          MachinePointerInfo::getGOT(), false, false, false, 0);
2690   return Result;
2691 }
2692
2693 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2694                                                     SelectionDAG &DAG) const {
2695   assert(Subtarget->isTargetELF() &&
2696          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2697   MachineFunction &MF = DAG.getMachineFunction();
2698   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2699   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2700   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2701   SDLoc dl(Op);
2702   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2703   ARMConstantPoolValue *CPV =
2704     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2705                                   ARMPCLabelIndex, PCAdj);
2706   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2707   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2708   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2709                                MachinePointerInfo::getConstantPool(),
2710                                false, false, false, 0);
2711   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2712   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2713 }
2714
2715 SDValue
2716 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2717   SDLoc dl(Op);
2718   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2719   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2720                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2721                      Op.getOperand(1), Val);
2722 }
2723
2724 SDValue
2725 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2726   SDLoc dl(Op);
2727   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2728                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2729 }
2730
2731 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2732                                                       SelectionDAG &DAG) const {
2733   SDLoc dl(Op);
2734   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2735                      Op.getOperand(0));
2736 }
2737
2738 SDValue
2739 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2740                                           const ARMSubtarget *Subtarget) const {
2741   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2742   SDLoc dl(Op);
2743   switch (IntNo) {
2744   default: return SDValue();    // Don't custom lower most intrinsics.
2745   case Intrinsic::arm_rbit: {
2746     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2747            "RBIT intrinsic must have i32 type!");
2748     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2749   }
2750   case Intrinsic::arm_thread_pointer: {
2751     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2752     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2753   }
2754   case Intrinsic::eh_sjlj_lsda: {
2755     MachineFunction &MF = DAG.getMachineFunction();
2756     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2757     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2758     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2759     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2760     SDValue CPAddr;
2761     unsigned PCAdj = (RelocM != Reloc::PIC_)
2762       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2763     ARMConstantPoolValue *CPV =
2764       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2765                                       ARMCP::CPLSDA, PCAdj);
2766     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2767     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2768     SDValue Result =
2769       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2770                   MachinePointerInfo::getConstantPool(),
2771                   false, false, false, 0);
2772
2773     if (RelocM == Reloc::PIC_) {
2774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2775       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2776     }
2777     return Result;
2778   }
2779   case Intrinsic::arm_neon_vmulls:
2780   case Intrinsic::arm_neon_vmullu: {
2781     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2782       ? ARMISD::VMULLs : ARMISD::VMULLu;
2783     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2784                        Op.getOperand(1), Op.getOperand(2));
2785   }
2786   }
2787 }
2788
2789 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2790                                  const ARMSubtarget *Subtarget) {
2791   // FIXME: handle "fence singlethread" more efficiently.
2792   SDLoc dl(Op);
2793   if (!Subtarget->hasDataBarrier()) {
2794     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2795     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2796     // here.
2797     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2798            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2799     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2800                        DAG.getConstant(0, dl, MVT::i32));
2801   }
2802
2803   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2804   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2805   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2806   if (Subtarget->isMClass()) {
2807     // Only a full system barrier exists in the M-class architectures.
2808     Domain = ARM_MB::SY;
2809   } else if (Subtarget->isSwift() && Ord == Release) {
2810     // Swift happens to implement ISHST barriers in a way that's compatible with
2811     // Release semantics but weaker than ISH so we'd be fools not to use
2812     // it. Beware: other processors probably don't!
2813     Domain = ARM_MB::ISHST;
2814   }
2815
2816   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2817                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2818                      DAG.getConstant(Domain, dl, MVT::i32));
2819 }
2820
2821 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2822                              const ARMSubtarget *Subtarget) {
2823   // ARM pre v5TE and Thumb1 does not have preload instructions.
2824   if (!(Subtarget->isThumb2() ||
2825         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2826     // Just preserve the chain.
2827     return Op.getOperand(0);
2828
2829   SDLoc dl(Op);
2830   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2831   if (!isRead &&
2832       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2833     // ARMv7 with MP extension has PLDW.
2834     return Op.getOperand(0);
2835
2836   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2837   if (Subtarget->isThumb()) {
2838     // Invert the bits.
2839     isRead = ~isRead & 1;
2840     isData = ~isData & 1;
2841   }
2842
2843   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2844                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2845                      DAG.getConstant(isData, dl, MVT::i32));
2846 }
2847
2848 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2849   MachineFunction &MF = DAG.getMachineFunction();
2850   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2851
2852   // vastart just stores the address of the VarArgsFrameIndex slot into the
2853   // memory location argument.
2854   SDLoc dl(Op);
2855   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2856   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2857   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2858   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2859                       MachinePointerInfo(SV), false, false, 0);
2860 }
2861
2862 SDValue
2863 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2864                                         SDValue &Root, SelectionDAG &DAG,
2865                                         SDLoc dl) const {
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2868
2869   const TargetRegisterClass *RC;
2870   if (AFI->isThumb1OnlyFunction())
2871     RC = &ARM::tGPRRegClass;
2872   else
2873     RC = &ARM::GPRRegClass;
2874
2875   // Transform the arguments stored in physical registers into virtual ones.
2876   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2877   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2878
2879   SDValue ArgValue2;
2880   if (NextVA.isMemLoc()) {
2881     MachineFrameInfo *MFI = MF.getFrameInfo();
2882     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2883
2884     // Create load node to retrieve arguments from the stack.
2885     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2886     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2887                             MachinePointerInfo::getFixedStack(FI),
2888                             false, false, false, 0);
2889   } else {
2890     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2891     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2892   }
2893   if (!Subtarget->isLittle())
2894     std::swap (ArgValue, ArgValue2);
2895   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2896 }
2897
2898 // The remaining GPRs hold either the beginning of variable-argument
2899 // data, or the beginning of an aggregate passed by value (usually
2900 // byval).  Either way, we allocate stack slots adjacent to the data
2901 // provided by our caller, and store the unallocated registers there.
2902 // If this is a variadic function, the va_list pointer will begin with
2903 // these values; otherwise, this reassembles a (byval) structure that
2904 // was split between registers and memory.
2905 // Return: The frame index registers were stored into.
2906 int
2907 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2908                                   SDLoc dl, SDValue &Chain,
2909                                   const Value *OrigArg,
2910                                   unsigned InRegsParamRecordIdx,
2911                                   int ArgOffset,
2912                                   unsigned ArgSize) const {
2913   // Currently, two use-cases possible:
2914   // Case #1. Non-var-args function, and we meet first byval parameter.
2915   //          Setup first unallocated register as first byval register;
2916   //          eat all remained registers
2917   //          (these two actions are performed by HandleByVal method).
2918   //          Then, here, we initialize stack frame with
2919   //          "store-reg" instructions.
2920   // Case #2. Var-args function, that doesn't contain byval parameters.
2921   //          The same: eat all remained unallocated registers,
2922   //          initialize stack frame.
2923
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   MachineFrameInfo *MFI = MF.getFrameInfo();
2926   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2927   unsigned RBegin, REnd;
2928   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2929     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2930   } else {
2931     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2932     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2933     REnd = ARM::R4;
2934   }
2935
2936   if (REnd != RBegin)
2937     ArgOffset = -4 * (ARM::R4 - RBegin);
2938
2939   auto PtrVT = getPointerTy(DAG.getDataLayout());
2940   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2941   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2942
2943   SmallVector<SDValue, 4> MemOps;
2944   const TargetRegisterClass *RC =
2945       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2946
2947   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2948     unsigned VReg = MF.addLiveIn(Reg, RC);
2949     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2950     SDValue Store =
2951         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2952                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2953     MemOps.push_back(Store);
2954     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2955   }
2956
2957   if (!MemOps.empty())
2958     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2959   return FrameIndex;
2960 }
2961
2962 // Setup stack frame, the va_list pointer will start from.
2963 void
2964 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2965                                         SDLoc dl, SDValue &Chain,
2966                                         unsigned ArgOffset,
2967                                         unsigned TotalArgRegsSaveSize,
2968                                         bool ForceMutable) const {
2969   MachineFunction &MF = DAG.getMachineFunction();
2970   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2971
2972   // Try to store any remaining integer argument regs
2973   // to their spots on the stack so that they may be loaded by deferencing
2974   // the result of va_next.
2975   // If there is no regs to be stored, just point address after last
2976   // argument passed via stack.
2977   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2978                                   CCInfo.getInRegsParamsCount(),
2979                                   CCInfo.getNextStackOffset(), 4);
2980   AFI->setVarArgsFrameIndex(FrameIndex);
2981 }
2982
2983 SDValue
2984 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2985                                         CallingConv::ID CallConv, bool isVarArg,
2986                                         const SmallVectorImpl<ISD::InputArg>
2987                                           &Ins,
2988                                         SDLoc dl, SelectionDAG &DAG,
2989                                         SmallVectorImpl<SDValue> &InVals)
2990                                           const {
2991   MachineFunction &MF = DAG.getMachineFunction();
2992   MachineFrameInfo *MFI = MF.getFrameInfo();
2993
2994   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2995
2996   // Assign locations to all of the incoming arguments.
2997   SmallVector<CCValAssign, 16> ArgLocs;
2998   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2999                     *DAG.getContext(), Prologue);
3000   CCInfo.AnalyzeFormalArguments(Ins,
3001                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3002                                                   isVarArg));
3003
3004   SmallVector<SDValue, 16> ArgValues;
3005   SDValue ArgValue;
3006   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3007   unsigned CurArgIdx = 0;
3008
3009   // Initially ArgRegsSaveSize is zero.
3010   // Then we increase this value each time we meet byval parameter.
3011   // We also increase this value in case of varargs function.
3012   AFI->setArgRegsSaveSize(0);
3013
3014   // Calculate the amount of stack space that we need to allocate to store
3015   // byval and variadic arguments that are passed in registers.
3016   // We need to know this before we allocate the first byval or variadic
3017   // argument, as they will be allocated a stack slot below the CFA (Canonical
3018   // Frame Address, the stack pointer at entry to the function).
3019   unsigned ArgRegBegin = ARM::R4;
3020   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3021     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3022       break;
3023
3024     CCValAssign &VA = ArgLocs[i];
3025     unsigned Index = VA.getValNo();
3026     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3027     if (!Flags.isByVal())
3028       continue;
3029
3030     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3031     unsigned RBegin, REnd;
3032     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3033     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3034
3035     CCInfo.nextInRegsParam();
3036   }
3037   CCInfo.rewindByValRegsInfo();
3038
3039   int lastInsIndex = -1;
3040   if (isVarArg && MFI->hasVAStart()) {
3041     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3042     if (RegIdx != array_lengthof(GPRArgRegs))
3043       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3044   }
3045
3046   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3047   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3048   auto PtrVT = getPointerTy(DAG.getDataLayout());
3049
3050   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051     CCValAssign &VA = ArgLocs[i];
3052     if (Ins[VA.getValNo()].isOrigArg()) {
3053       std::advance(CurOrigArg,
3054                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3055       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3056     }
3057     // Arguments stored in registers.
3058     if (VA.isRegLoc()) {
3059       EVT RegVT = VA.getLocVT();
3060
3061       if (VA.needsCustom()) {
3062         // f64 and vector types are split up into multiple registers or
3063         // combinations of registers and stack slots.
3064         if (VA.getLocVT() == MVT::v2f64) {
3065           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3066                                                    Chain, DAG, dl);
3067           VA = ArgLocs[++i]; // skip ahead to next loc
3068           SDValue ArgValue2;
3069           if (VA.isMemLoc()) {
3070             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3071             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3072             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3073                                     MachinePointerInfo::getFixedStack(FI),
3074                                     false, false, false, 0);
3075           } else {
3076             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3077                                              Chain, DAG, dl);
3078           }
3079           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3080           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3081                                  ArgValue, ArgValue1,
3082                                  DAG.getIntPtrConstant(0, dl));
3083           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3084                                  ArgValue, ArgValue2,
3085                                  DAG.getIntPtrConstant(1, dl));
3086         } else
3087           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3088
3089       } else {
3090         const TargetRegisterClass *RC;
3091
3092         if (RegVT == MVT::f32)
3093           RC = &ARM::SPRRegClass;
3094         else if (RegVT == MVT::f64)
3095           RC = &ARM::DPRRegClass;
3096         else if (RegVT == MVT::v2f64)
3097           RC = &ARM::QPRRegClass;
3098         else if (RegVT == MVT::i32)
3099           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3100                                            : &ARM::GPRRegClass;
3101         else
3102           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3103
3104         // Transform the arguments in physical registers into virtual ones.
3105         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3106         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3107       }
3108
3109       // If this is an 8 or 16-bit value, it is really passed promoted
3110       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3111       // truncate to the right size.
3112       switch (VA.getLocInfo()) {
3113       default: llvm_unreachable("Unknown loc info!");
3114       case CCValAssign::Full: break;
3115       case CCValAssign::BCvt:
3116         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3117         break;
3118       case CCValAssign::SExt:
3119         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3120                                DAG.getValueType(VA.getValVT()));
3121         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3122         break;
3123       case CCValAssign::ZExt:
3124         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3125                                DAG.getValueType(VA.getValVT()));
3126         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3127         break;
3128       }
3129
3130       InVals.push_back(ArgValue);
3131
3132     } else { // VA.isRegLoc()
3133
3134       // sanity check
3135       assert(VA.isMemLoc());
3136       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3137
3138       int index = VA.getValNo();
3139
3140       // Some Ins[] entries become multiple ArgLoc[] entries.
3141       // Process them only once.
3142       if (index != lastInsIndex)
3143         {
3144           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3145           // FIXME: For now, all byval parameter objects are marked mutable.
3146           // This can be changed with more analysis.
3147           // In case of tail call optimization mark all arguments mutable.
3148           // Since they could be overwritten by lowering of arguments in case of
3149           // a tail call.
3150           if (Flags.isByVal()) {
3151             assert(Ins[index].isOrigArg() &&
3152                    "Byval arguments cannot be implicit");
3153             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3154
3155             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3156                                             CurByValIndex, VA.getLocMemOffset(),
3157                                             Flags.getByValSize());
3158             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3159             CCInfo.nextInRegsParam();
3160           } else {
3161             unsigned FIOffset = VA.getLocMemOffset();
3162             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3163                                             FIOffset, true);
3164
3165             // Create load nodes to retrieve arguments from the stack.
3166             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3167             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3168                                          MachinePointerInfo::getFixedStack(FI),
3169                                          false, false, false, 0));
3170           }
3171           lastInsIndex = index;
3172         }
3173     }
3174   }
3175
3176   // varargs
3177   if (isVarArg && MFI->hasVAStart())
3178     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3179                          CCInfo.getNextStackOffset(),
3180                          TotalArgRegsSaveSize);
3181
3182   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3183
3184   return Chain;
3185 }
3186
3187 /// isFloatingPointZero - Return true if this is +0.0.
3188 static bool isFloatingPointZero(SDValue Op) {
3189   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3190     return CFP->getValueAPF().isPosZero();
3191   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3192     // Maybe this has already been legalized into the constant pool?
3193     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3194       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3195       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3196         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3197           return CFP->getValueAPF().isPosZero();
3198     }
3199   } else if (Op->getOpcode() == ISD::BITCAST &&
3200              Op->getValueType(0) == MVT::f64) {
3201     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3202     // created by LowerConstantFP().
3203     SDValue BitcastOp = Op->getOperand(0);
3204     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3205       SDValue MoveOp = BitcastOp->getOperand(0);
3206       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3207           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3208         return true;
3209       }
3210     }
3211   }
3212   return false;
3213 }
3214
3215 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3216 /// the given operands.
3217 SDValue
3218 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3219                              SDValue &ARMcc, SelectionDAG &DAG,
3220                              SDLoc dl) const {
3221   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3222     unsigned C = RHSC->getZExtValue();
3223     if (!isLegalICmpImmediate(C)) {
3224       // Constant does not fit, try adjusting it by one?
3225       switch (CC) {
3226       default: break;
3227       case ISD::SETLT:
3228       case ISD::SETGE:
3229         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3230           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3231           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3232         }
3233         break;
3234       case ISD::SETULT:
3235       case ISD::SETUGE:
3236         if (C != 0 && isLegalICmpImmediate(C-1)) {
3237           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3238           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3239         }
3240         break;
3241       case ISD::SETLE:
3242       case ISD::SETGT:
3243         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3244           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3245           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3246         }
3247         break;
3248       case ISD::SETULE:
3249       case ISD::SETUGT:
3250         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3251           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3252           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3253         }
3254         break;
3255       }
3256     }
3257   }
3258
3259   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3260   ARMISD::NodeType CompareType;
3261   switch (CondCode) {
3262   default:
3263     CompareType = ARMISD::CMP;
3264     break;
3265   case ARMCC::EQ:
3266   case ARMCC::NE:
3267     // Uses only Z Flag
3268     CompareType = ARMISD::CMPZ;
3269     break;
3270   }
3271   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3272   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3273 }
3274
3275 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3276 SDValue
3277 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3278                              SDLoc dl) const {
3279   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3280   SDValue Cmp;
3281   if (!isFloatingPointZero(RHS))
3282     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3283   else
3284     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3285   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3286 }
3287
3288 /// duplicateCmp - Glue values can have only one use, so this function
3289 /// duplicates a comparison node.
3290 SDValue
3291 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3292   unsigned Opc = Cmp.getOpcode();
3293   SDLoc DL(Cmp);
3294   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3295     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3296
3297   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3298   Cmp = Cmp.getOperand(0);
3299   Opc = Cmp.getOpcode();
3300   if (Opc == ARMISD::CMPFP)
3301     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3302   else {
3303     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3304     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3305   }
3306   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3307 }
3308
3309 std::pair<SDValue, SDValue>
3310 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3311                                  SDValue &ARMcc) const {
3312   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3313
3314   SDValue Value, OverflowCmp;
3315   SDValue LHS = Op.getOperand(0);
3316   SDValue RHS = Op.getOperand(1);
3317   SDLoc dl(Op);
3318
3319   // FIXME: We are currently always generating CMPs because we don't support
3320   // generating CMN through the backend. This is not as good as the natural
3321   // CMP case because it causes a register dependency and cannot be folded
3322   // later.
3323
3324   switch (Op.getOpcode()) {
3325   default:
3326     llvm_unreachable("Unknown overflow instruction!");
3327   case ISD::SADDO:
3328     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3329     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3330     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3331     break;
3332   case ISD::UADDO:
3333     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3334     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3335     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3336     break;
3337   case ISD::SSUBO:
3338     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3339     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3340     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3341     break;
3342   case ISD::USUBO:
3343     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3344     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3345     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3346     break;
3347   } // switch (...)
3348
3349   return std::make_pair(Value, OverflowCmp);
3350 }
3351
3352
3353 SDValue
3354 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3355   // Let legalize expand this if it isn't a legal type yet.
3356   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3357     return SDValue();
3358
3359   SDValue Value, OverflowCmp;
3360   SDValue ARMcc;
3361   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3362   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3363   SDLoc dl(Op);
3364   // We use 0 and 1 as false and true values.
3365   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3366   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3367   EVT VT = Op.getValueType();
3368
3369   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3370                                  ARMcc, CCR, OverflowCmp);
3371
3372   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3373   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3374 }
3375
3376
3377 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3378   SDValue Cond = Op.getOperand(0);
3379   SDValue SelectTrue = Op.getOperand(1);
3380   SDValue SelectFalse = Op.getOperand(2);
3381   SDLoc dl(Op);
3382   unsigned Opc = Cond.getOpcode();
3383
3384   if (Cond.getResNo() == 1 &&
3385       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3386        Opc == ISD::USUBO)) {
3387     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3388       return SDValue();
3389
3390     SDValue Value, OverflowCmp;
3391     SDValue ARMcc;
3392     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3393     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3394     EVT VT = Op.getValueType();
3395
3396     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3397                    OverflowCmp, DAG);
3398   }
3399
3400   // Convert:
3401   //
3402   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3403   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3404   //
3405   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3406     const ConstantSDNode *CMOVTrue =
3407       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3408     const ConstantSDNode *CMOVFalse =
3409       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3410
3411     if (CMOVTrue && CMOVFalse) {
3412       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3413       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3414
3415       SDValue True;
3416       SDValue False;
3417       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3418         True = SelectTrue;
3419         False = SelectFalse;
3420       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3421         True = SelectFalse;
3422         False = SelectTrue;
3423       }
3424
3425       if (True.getNode() && False.getNode()) {
3426         EVT VT = Op.getValueType();
3427         SDValue ARMcc = Cond.getOperand(2);
3428         SDValue CCR = Cond.getOperand(3);
3429         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3430         assert(True.getValueType() == VT);
3431         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3432       }
3433     }
3434   }
3435
3436   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3437   // undefined bits before doing a full-word comparison with zero.
3438   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3439                      DAG.getConstant(1, dl, Cond.getValueType()));
3440
3441   return DAG.getSelectCC(dl, Cond,
3442                          DAG.getConstant(0, dl, Cond.getValueType()),
3443                          SelectTrue, SelectFalse, ISD::SETNE);
3444 }
3445
3446 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3447                                  bool &swpCmpOps, bool &swpVselOps) {
3448   // Start by selecting the GE condition code for opcodes that return true for
3449   // 'equality'
3450   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3451       CC == ISD::SETULE)
3452     CondCode = ARMCC::GE;
3453
3454   // and GT for opcodes that return false for 'equality'.
3455   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3456            CC == ISD::SETULT)
3457     CondCode = ARMCC::GT;
3458
3459   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3460   // to swap the compare operands.
3461   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3462       CC == ISD::SETULT)
3463     swpCmpOps = true;
3464
3465   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3466   // If we have an unordered opcode, we need to swap the operands to the VSEL
3467   // instruction (effectively negating the condition).
3468   //
3469   // This also has the effect of swapping which one of 'less' or 'greater'
3470   // returns true, so we also swap the compare operands. It also switches
3471   // whether we return true for 'equality', so we compensate by picking the
3472   // opposite condition code to our original choice.
3473   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3474       CC == ISD::SETUGT) {
3475     swpCmpOps = !swpCmpOps;
3476     swpVselOps = !swpVselOps;
3477     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3478   }
3479
3480   // 'ordered' is 'anything but unordered', so use the VS condition code and
3481   // swap the VSEL operands.
3482   if (CC == ISD::SETO) {
3483     CondCode = ARMCC::VS;
3484     swpVselOps = true;
3485   }
3486
3487   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3488   // code and swap the VSEL operands.
3489   if (CC == ISD::SETUNE) {
3490     CondCode = ARMCC::EQ;
3491     swpVselOps = true;
3492   }
3493 }
3494
3495 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3496                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3497                                    SDValue Cmp, SelectionDAG &DAG) const {
3498   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3499     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3500                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3501     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3502                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3503
3504     SDValue TrueLow = TrueVal.getValue(0);
3505     SDValue TrueHigh = TrueVal.getValue(1);
3506     SDValue FalseLow = FalseVal.getValue(0);
3507     SDValue FalseHigh = FalseVal.getValue(1);
3508
3509     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3510                               ARMcc, CCR, Cmp);
3511     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3512                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3513
3514     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3515   } else {
3516     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3517                        Cmp);
3518   }
3519 }
3520
3521 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3522   EVT VT = Op.getValueType();
3523   SDValue LHS = Op.getOperand(0);
3524   SDValue RHS = Op.getOperand(1);
3525   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3526   SDValue TrueVal = Op.getOperand(2);
3527   SDValue FalseVal = Op.getOperand(3);
3528   SDLoc dl(Op);
3529
3530   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3531     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3532                                                     dl);
3533
3534     // If softenSetCCOperands only returned one value, we should compare it to
3535     // zero.
3536     if (!RHS.getNode()) {
3537       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3538       CC = ISD::SETNE;
3539     }
3540   }
3541
3542   if (LHS.getValueType() == MVT::i32) {
3543     // Try to generate VSEL on ARMv8.
3544     // The VSEL instruction can't use all the usual ARM condition
3545     // codes: it only has two bits to select the condition code, so it's
3546     // constrained to use only GE, GT, VS and EQ.
3547     //
3548     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3549     // swap the operands of the previous compare instruction (effectively
3550     // inverting the compare condition, swapping 'less' and 'greater') and
3551     // sometimes need to swap the operands to the VSEL (which inverts the
3552     // condition in the sense of firing whenever the previous condition didn't)
3553     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3554                                     TrueVal.getValueType() == MVT::f64)) {
3555       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3556       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3557           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3558         CC = ISD::getSetCCInverse(CC, true);
3559         std::swap(TrueVal, FalseVal);
3560       }
3561     }
3562
3563     SDValue ARMcc;
3564     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3565     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3566     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3567   }
3568
3569   ARMCC::CondCodes CondCode, CondCode2;
3570   FPCCToARMCC(CC, CondCode, CondCode2);
3571
3572   // Try to generate VMAXNM/VMINNM on ARMv8.
3573   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3574                                   TrueVal.getValueType() == MVT::f64)) {
3575     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3576     // same operands, as follows:
3577     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3578     //   select c, a, b
3579     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3580     bool swapSides = false;
3581     if (!getTargetMachine().Options.NoNaNsFPMath) {
3582       // transformability may depend on which way around we compare
3583       switch (CC) {
3584       default:
3585         break;
3586       case ISD::SETOGT:
3587       case ISD::SETOGE:
3588       case ISD::SETOLT:
3589       case ISD::SETOLE:
3590         // the non-NaN should be RHS
3591         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3592         break;
3593       case ISD::SETUGT:
3594       case ISD::SETUGE:
3595       case ISD::SETULT:
3596       case ISD::SETULE:
3597         // the non-NaN should be LHS
3598         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3599         break;
3600       }
3601     }
3602     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3603     if (swapSides) {
3604       CC = ISD::getSetCCSwappedOperands(CC);
3605       std::swap(LHS, RHS);
3606     }
3607     if (LHS == TrueVal && RHS == FalseVal) {
3608       bool canTransform = true;
3609       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3610       if (!getTargetMachine().Options.UnsafeFPMath &&
3611           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3612         const ConstantFPSDNode *Zero;
3613         switch (CC) {
3614         default:
3615           break;
3616         case ISD::SETOGT:
3617         case ISD::SETUGT:
3618         case ISD::SETGT:
3619           // RHS must not be -0
3620           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3621                          !Zero->isNegative();
3622           break;
3623         case ISD::SETOGE:
3624         case ISD::SETUGE:
3625         case ISD::SETGE:
3626           // LHS must not be -0
3627           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3628                          !Zero->isNegative();
3629           break;
3630         case ISD::SETOLT:
3631         case ISD::SETULT:
3632         case ISD::SETLT:
3633           // RHS must not be +0
3634           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3635                           Zero->isNegative();
3636           break;
3637         case ISD::SETOLE:
3638         case ISD::SETULE:
3639         case ISD::SETLE:
3640           // LHS must not be +0
3641           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3642                           Zero->isNegative();
3643           break;
3644         }
3645       }
3646       if (canTransform) {
3647         // Note: If one of the elements in a pair is a number and the other
3648         // element is NaN, the corresponding result element is the number.
3649         // This is consistent with the IEEE 754-2008 standard.
3650         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3651         switch (CC) {
3652         default:
3653           break;
3654         case ISD::SETOGT:
3655         case ISD::SETOGE:
3656           if (!DAG.isKnownNeverNaN(RHS))
3657             break;
3658           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3659         case ISD::SETUGT:
3660         case ISD::SETUGE:
3661           if (!DAG.isKnownNeverNaN(LHS))
3662             break;
3663         case ISD::SETGT:
3664         case ISD::SETGE:
3665           return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3666         case ISD::SETOLT:
3667         case ISD::SETOLE:
3668           if (!DAG.isKnownNeverNaN(RHS))
3669             break;
3670           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3671         case ISD::SETULT:
3672         case ISD::SETULE:
3673           if (!DAG.isKnownNeverNaN(LHS))
3674             break;
3675         case ISD::SETLT:
3676         case ISD::SETLE:
3677           return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3678         }
3679       }
3680     }
3681
3682     bool swpCmpOps = false;
3683     bool swpVselOps = false;
3684     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3685
3686     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3687         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3688       if (swpCmpOps)
3689         std::swap(LHS, RHS);
3690       if (swpVselOps)
3691         std::swap(TrueVal, FalseVal);
3692     }
3693   }
3694
3695   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3696   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3697   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3698   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3699   if (CondCode2 != ARMCC::AL) {
3700     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3701     // FIXME: Needs another CMP because flag can have but one use.
3702     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3703     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3704   }
3705   return Result;
3706 }
3707
3708 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3709 /// to morph to an integer compare sequence.
3710 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3711                            const ARMSubtarget *Subtarget) {
3712   SDNode *N = Op.getNode();
3713   if (!N->hasOneUse())
3714     // Otherwise it requires moving the value from fp to integer registers.
3715     return false;
3716   if (!N->getNumValues())
3717     return false;
3718   EVT VT = Op.getValueType();
3719   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3720     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3721     // vmrs are very slow, e.g. cortex-a8.
3722     return false;
3723
3724   if (isFloatingPointZero(Op)) {
3725     SeenZero = true;
3726     return true;
3727   }
3728   return ISD::isNormalLoad(N);
3729 }
3730
3731 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3732   if (isFloatingPointZero(Op))
3733     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3734
3735   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3736     return DAG.getLoad(MVT::i32, SDLoc(Op),
3737                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3738                        Ld->isVolatile(), Ld->isNonTemporal(),
3739                        Ld->isInvariant(), Ld->getAlignment());
3740
3741   llvm_unreachable("Unknown VFP cmp argument!");
3742 }
3743
3744 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3745                            SDValue &RetVal1, SDValue &RetVal2) {
3746   SDLoc dl(Op);
3747
3748   if (isFloatingPointZero(Op)) {
3749     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3750     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3751     return;
3752   }
3753
3754   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3755     SDValue Ptr = Ld->getBasePtr();
3756     RetVal1 = DAG.getLoad(MVT::i32, dl,
3757                           Ld->getChain(), Ptr,
3758                           Ld->getPointerInfo(),
3759                           Ld->isVolatile(), Ld->isNonTemporal(),
3760                           Ld->isInvariant(), Ld->getAlignment());
3761
3762     EVT PtrType = Ptr.getValueType();
3763     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3764     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3765                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3766     RetVal2 = DAG.getLoad(MVT::i32, dl,
3767                           Ld->getChain(), NewPtr,
3768                           Ld->getPointerInfo().getWithOffset(4),
3769                           Ld->isVolatile(), Ld->isNonTemporal(),
3770                           Ld->isInvariant(), NewAlign);
3771     return;
3772   }
3773
3774   llvm_unreachable("Unknown VFP cmp argument!");
3775 }
3776
3777 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3778 /// f32 and even f64 comparisons to integer ones.
3779 SDValue
3780 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3781   SDValue Chain = Op.getOperand(0);
3782   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3783   SDValue LHS = Op.getOperand(2);
3784   SDValue RHS = Op.getOperand(3);
3785   SDValue Dest = Op.getOperand(4);
3786   SDLoc dl(Op);
3787
3788   bool LHSSeenZero = false;
3789   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3790   bool RHSSeenZero = false;
3791   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3792   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3793     // If unsafe fp math optimization is enabled and there are no other uses of
3794     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3795     // to an integer comparison.
3796     if (CC == ISD::SETOEQ)
3797       CC = ISD::SETEQ;
3798     else if (CC == ISD::SETUNE)
3799       CC = ISD::SETNE;
3800
3801     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3802     SDValue ARMcc;
3803     if (LHS.getValueType() == MVT::f32) {
3804       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3805                         bitcastf32Toi32(LHS, DAG), Mask);
3806       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3807                         bitcastf32Toi32(RHS, DAG), Mask);
3808       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3809       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3810       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3811                          Chain, Dest, ARMcc, CCR, Cmp);
3812     }
3813
3814     SDValue LHS1, LHS2;
3815     SDValue RHS1, RHS2;
3816     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3817     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3818     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3819     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3820     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3821     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3822     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3823     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3824     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3825   }
3826
3827   return SDValue();
3828 }
3829
3830 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3831   SDValue Chain = Op.getOperand(0);
3832   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3833   SDValue LHS = Op.getOperand(2);
3834   SDValue RHS = Op.getOperand(3);
3835   SDValue Dest = Op.getOperand(4);
3836   SDLoc dl(Op);
3837
3838   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3839     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3840                                                     dl);
3841
3842     // If softenSetCCOperands only returned one value, we should compare it to
3843     // zero.
3844     if (!RHS.getNode()) {
3845       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3846       CC = ISD::SETNE;
3847     }
3848   }
3849
3850   if (LHS.getValueType() == MVT::i32) {
3851     SDValue ARMcc;
3852     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3853     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3854     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3855                        Chain, Dest, ARMcc, CCR, Cmp);
3856   }
3857
3858   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3859
3860   if (getTargetMachine().Options.UnsafeFPMath &&
3861       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3862        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3863     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3864     if (Result.getNode())
3865       return Result;
3866   }
3867
3868   ARMCC::CondCodes CondCode, CondCode2;
3869   FPCCToARMCC(CC, CondCode, CondCode2);
3870
3871   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3872   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3873   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3874   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3875   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3876   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3877   if (CondCode2 != ARMCC::AL) {
3878     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3879     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3880     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3881   }
3882   return Res;
3883 }
3884
3885 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3886   SDValue Chain = Op.getOperand(0);
3887   SDValue Table = Op.getOperand(1);
3888   SDValue Index = Op.getOperand(2);
3889   SDLoc dl(Op);
3890
3891   EVT PTy = getPointerTy(DAG.getDataLayout());
3892   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3893   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3894   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3895   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3896   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3897   if (Subtarget->isThumb2()) {
3898     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3899     // which does another jump to the destination. This also makes it easier
3900     // to translate it to TBB / TBH later.
3901     // FIXME: This might not work if the function is extremely large.
3902     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3903                        Addr, Op.getOperand(2), JTI);
3904   }
3905   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3906     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3907                        MachinePointerInfo::getJumpTable(),
3908                        false, false, false, 0);
3909     Chain = Addr.getValue(1);
3910     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3911     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3912   } else {
3913     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3914                        MachinePointerInfo::getJumpTable(),
3915                        false, false, false, 0);
3916     Chain = Addr.getValue(1);
3917     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3918   }
3919 }
3920
3921 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3922   EVT VT = Op.getValueType();
3923   SDLoc dl(Op);
3924
3925   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3926     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3927       return Op;
3928     return DAG.UnrollVectorOp(Op.getNode());
3929   }
3930
3931   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3932          "Invalid type for custom lowering!");
3933   if (VT != MVT::v4i16)
3934     return DAG.UnrollVectorOp(Op.getNode());
3935
3936   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3937   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3938 }
3939
3940 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3941   EVT VT = Op.getValueType();
3942   if (VT.isVector())
3943     return LowerVectorFP_TO_INT(Op, DAG);
3944   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3945     RTLIB::Libcall LC;
3946     if (Op.getOpcode() == ISD::FP_TO_SINT)
3947       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3948                               Op.getValueType());
3949     else
3950       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3951                               Op.getValueType());
3952     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3953                        /*isSigned*/ false, SDLoc(Op)).first;
3954   }
3955
3956   return Op;
3957 }
3958
3959 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3960   EVT VT = Op.getValueType();
3961   SDLoc dl(Op);
3962
3963   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3964     if (VT.getVectorElementType() == MVT::f32)
3965       return Op;
3966     return DAG.UnrollVectorOp(Op.getNode());
3967   }
3968
3969   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3970          "Invalid type for custom lowering!");
3971   if (VT != MVT::v4f32)
3972     return DAG.UnrollVectorOp(Op.getNode());
3973
3974   unsigned CastOpc;
3975   unsigned Opc;
3976   switch (Op.getOpcode()) {
3977   default: llvm_unreachable("Invalid opcode!");
3978   case ISD::SINT_TO_FP:
3979     CastOpc = ISD::SIGN_EXTEND;
3980     Opc = ISD::SINT_TO_FP;
3981     break;
3982   case ISD::UINT_TO_FP:
3983     CastOpc = ISD::ZERO_EXTEND;
3984     Opc = ISD::UINT_TO_FP;
3985     break;
3986   }
3987
3988   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3989   return DAG.getNode(Opc, dl, VT, Op);
3990 }
3991
3992 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3993   EVT VT = Op.getValueType();
3994   if (VT.isVector())
3995     return LowerVectorINT_TO_FP(Op, DAG);
3996   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3997     RTLIB::Libcall LC;
3998     if (Op.getOpcode() == ISD::SINT_TO_FP)
3999       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4000                               Op.getValueType());
4001     else
4002       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4003                               Op.getValueType());
4004     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4005                        /*isSigned*/ false, SDLoc(Op)).first;
4006   }
4007
4008   return Op;
4009 }
4010
4011 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4012   // Implement fcopysign with a fabs and a conditional fneg.
4013   SDValue Tmp0 = Op.getOperand(0);
4014   SDValue Tmp1 = Op.getOperand(1);
4015   SDLoc dl(Op);
4016   EVT VT = Op.getValueType();
4017   EVT SrcVT = Tmp1.getValueType();
4018   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4019     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4020   bool UseNEON = !InGPR && Subtarget->hasNEON();
4021
4022   if (UseNEON) {
4023     // Use VBSL to copy the sign bit.
4024     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4025     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4026                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4027     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4028     if (VT == MVT::f64)
4029       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4030                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4031                          DAG.getConstant(32, dl, MVT::i32));
4032     else /*if (VT == MVT::f32)*/
4033       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4034     if (SrcVT == MVT::f32) {
4035       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4036       if (VT == MVT::f64)
4037         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4038                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4039                            DAG.getConstant(32, dl, MVT::i32));
4040     } else if (VT == MVT::f32)
4041       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4042                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4043                          DAG.getConstant(32, dl, MVT::i32));
4044     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4045     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4046
4047     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4048                                             dl, MVT::i32);
4049     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4050     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4051                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4052
4053     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4054                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4055                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4056     if (VT == MVT::f32) {
4057       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4058       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4059                         DAG.getConstant(0, dl, MVT::i32));
4060     } else {
4061       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4062     }
4063
4064     return Res;
4065   }
4066
4067   // Bitcast operand 1 to i32.
4068   if (SrcVT == MVT::f64)
4069     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4070                        Tmp1).getValue(1);
4071   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4072
4073   // Or in the signbit with integer operations.
4074   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4075   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4076   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4077   if (VT == MVT::f32) {
4078     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4079                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4080     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4081                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4082   }
4083
4084   // f64: Or the high part with signbit and then combine two parts.
4085   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4086                      Tmp0);
4087   SDValue Lo = Tmp0.getValue(0);
4088   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4089   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4090   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4091 }
4092
4093 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4094   MachineFunction &MF = DAG.getMachineFunction();
4095   MachineFrameInfo *MFI = MF.getFrameInfo();
4096   MFI->setReturnAddressIsTaken(true);
4097
4098   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4099     return SDValue();
4100
4101   EVT VT = Op.getValueType();
4102   SDLoc dl(Op);
4103   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4104   if (Depth) {
4105     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4106     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4107     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4108                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4109                        MachinePointerInfo(), false, false, false, 0);
4110   }
4111
4112   // Return LR, which contains the return address. Mark it an implicit live-in.
4113   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4114   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4115 }
4116
4117 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4118   const ARMBaseRegisterInfo &ARI =
4119     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4120   MachineFunction &MF = DAG.getMachineFunction();
4121   MachineFrameInfo *MFI = MF.getFrameInfo();
4122   MFI->setFrameAddressIsTaken(true);
4123
4124   EVT VT = Op.getValueType();
4125   SDLoc dl(Op);  // FIXME probably not meaningful
4126   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4127   unsigned FrameReg = ARI.getFrameRegister(MF);
4128   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4129   while (Depth--)
4130     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4131                             MachinePointerInfo(),
4132                             false, false, false, 0);
4133   return FrameAddr;
4134 }
4135
4136 // FIXME? Maybe this could be a TableGen attribute on some registers and
4137 // this table could be generated automatically from RegInfo.
4138 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4139                                               SelectionDAG &DAG) const {
4140   unsigned Reg = StringSwitch<unsigned>(RegName)
4141                        .Case("sp", ARM::SP)
4142                        .Default(0);
4143   if (Reg)
4144     return Reg;
4145   report_fatal_error(Twine("Invalid register name \""
4146                               + StringRef(RegName)  + "\"."));
4147 }
4148
4149 // Result is 64 bit value so split into two 32 bit values and return as a
4150 // pair of values.
4151 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4152                                 SelectionDAG &DAG) {
4153   SDLoc DL(N);
4154
4155   // This function is only supposed to be called for i64 type destination.
4156   assert(N->getValueType(0) == MVT::i64
4157           && "ExpandREAD_REGISTER called for non-i64 type result.");
4158
4159   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4160                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4161                              N->getOperand(0),
4162                              N->getOperand(1));
4163
4164   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4165                     Read.getValue(1)));
4166   Results.push_back(Read.getOperand(0));
4167 }
4168
4169 /// ExpandBITCAST - If the target supports VFP, this function is called to
4170 /// expand a bit convert where either the source or destination type is i64 to
4171 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4172 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4173 /// vectors), since the legalizer won't know what to do with that.
4174 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4176   SDLoc dl(N);
4177   SDValue Op = N->getOperand(0);
4178
4179   // This function is only supposed to be called for i64 types, either as the
4180   // source or destination of the bit convert.
4181   EVT SrcVT = Op.getValueType();
4182   EVT DstVT = N->getValueType(0);
4183   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4184          "ExpandBITCAST called for non-i64 type");
4185
4186   // Turn i64->f64 into VMOVDRR.
4187   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4188     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4189                              DAG.getConstant(0, dl, MVT::i32));
4190     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4191                              DAG.getConstant(1, dl, MVT::i32));
4192     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4193                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4194   }
4195
4196   // Turn f64->i64 into VMOVRRD.
4197   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4198     SDValue Cvt;
4199     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4200         SrcVT.getVectorNumElements() > 1)
4201       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4202                         DAG.getVTList(MVT::i32, MVT::i32),
4203                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4204     else
4205       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4206                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4207     // Merge the pieces into a single i64 value.
4208     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4209   }
4210
4211   return SDValue();
4212 }
4213
4214 /// getZeroVector - Returns a vector of specified type with all zero elements.
4215 /// Zero vectors are used to represent vector negation and in those cases
4216 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4217 /// not support i64 elements, so sometimes the zero vectors will need to be
4218 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4219 /// zero vector.
4220 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4221   assert(VT.isVector() && "Expected a vector type");
4222   // The canonical modified immediate encoding of a zero vector is....0!
4223   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4224   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4225   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4226   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4227 }
4228
4229 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4230 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4231 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4232                                                 SelectionDAG &DAG) const {
4233   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4234   EVT VT = Op.getValueType();
4235   unsigned VTBits = VT.getSizeInBits();
4236   SDLoc dl(Op);
4237   SDValue ShOpLo = Op.getOperand(0);
4238   SDValue ShOpHi = Op.getOperand(1);
4239   SDValue ShAmt  = Op.getOperand(2);
4240   SDValue ARMcc;
4241   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4242
4243   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4244
4245   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4246                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4247   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4248   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4249                                    DAG.getConstant(VTBits, dl, MVT::i32));
4250   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4251   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4252   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4253
4254   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4255   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4256                           ISD::SETGE, ARMcc, DAG, dl);
4257   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4258   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4259                            CCR, Cmp);
4260
4261   SDValue Ops[2] = { Lo, Hi };
4262   return DAG.getMergeValues(Ops, dl);
4263 }
4264
4265 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4266 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4267 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4268                                                SelectionDAG &DAG) const {
4269   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4270   EVT VT = Op.getValueType();
4271   unsigned VTBits = VT.getSizeInBits();
4272   SDLoc dl(Op);
4273   SDValue ShOpLo = Op.getOperand(0);
4274   SDValue ShOpHi = Op.getOperand(1);
4275   SDValue ShAmt  = Op.getOperand(2);
4276   SDValue ARMcc;
4277
4278   assert(Op.getOpcode() == ISD::SHL_PARTS);
4279   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4280                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4281   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4282   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4283                                    DAG.getConstant(VTBits, dl, MVT::i32));
4284   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4285   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4286
4287   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4288   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4289   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4290                           ISD::SETGE, ARMcc, DAG, dl);
4291   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4292   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4293                            CCR, Cmp);
4294
4295   SDValue Ops[2] = { Lo, Hi };
4296   return DAG.getMergeValues(Ops, dl);
4297 }
4298
4299 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4300                                             SelectionDAG &DAG) const {
4301   // The rounding mode is in bits 23:22 of the FPSCR.
4302   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4303   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4304   // so that the shift + and get folded into a bitfield extract.
4305   SDLoc dl(Op);
4306   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4307                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4308                                               MVT::i32));
4309   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4310                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4311   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4312                               DAG.getConstant(22, dl, MVT::i32));
4313   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4314                      DAG.getConstant(3, dl, MVT::i32));
4315 }
4316
4317 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4318                          const ARMSubtarget *ST) {
4319   SDLoc dl(N);
4320   EVT VT = N->getValueType(0);
4321   if (VT.isVector()) {
4322     assert(ST->hasNEON());
4323
4324     // Compute the least significant set bit: LSB = X & -X
4325     SDValue X = N->getOperand(0);
4326     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4327     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4328
4329     EVT ElemTy = VT.getVectorElementType();
4330
4331     if (ElemTy == MVT::i8) {
4332       // Compute with: cttz(x) = ctpop(lsb - 1)
4333       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4334                                 DAG.getTargetConstant(1, dl, ElemTy));
4335       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4336       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4337     }
4338
4339     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4340         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4341       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4342       unsigned NumBits = ElemTy.getSizeInBits();
4343       SDValue WidthMinus1 =
4344           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4345                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4346       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4347       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4348     }
4349
4350     // Compute with: cttz(x) = ctpop(lsb - 1)
4351
4352     // Since we can only compute the number of bits in a byte with vcnt.8, we
4353     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4354     // and i64.
4355
4356     // Compute LSB - 1.
4357     SDValue Bits;
4358     if (ElemTy == MVT::i64) {
4359       // Load constant 0xffff'ffff'ffff'ffff to register.
4360       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4361                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4362       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4363     } else {
4364       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4365                                 DAG.getTargetConstant(1, dl, ElemTy));
4366       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4367     }
4368
4369     // Count #bits with vcnt.8.
4370     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4371     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4372     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4373
4374     // Gather the #bits with vpaddl (pairwise add.)
4375     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4376     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4377         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4378         Cnt8);
4379     if (ElemTy == MVT::i16)
4380       return Cnt16;
4381
4382     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4383     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4384         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4385         Cnt16);
4386     if (ElemTy == MVT::i32)
4387       return Cnt32;
4388
4389     assert(ElemTy == MVT::i64);
4390     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4391         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4392         Cnt32);
4393     return Cnt64;
4394   }
4395
4396   if (!ST->hasV6T2Ops())
4397     return SDValue();
4398
4399   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4400   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4401 }
4402
4403 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4404 /// for each 16-bit element from operand, repeated.  The basic idea is to
4405 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4406 ///
4407 /// Trace for v4i16:
4408 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4409 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4410 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4411 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4412 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4413 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4414 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4415 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4416 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4417   EVT VT = N->getValueType(0);
4418   SDLoc DL(N);
4419
4420   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4421   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4422   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4423   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4424   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4425   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4426 }
4427
4428 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4429 /// bit-count for each 16-bit element from the operand.  We need slightly
4430 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4431 /// 64/128-bit registers.
4432 ///
4433 /// Trace for v4i16:
4434 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4435 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4436 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4437 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4438 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4439   EVT VT = N->getValueType(0);
4440   SDLoc DL(N);
4441
4442   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4443   if (VT.is64BitVector()) {
4444     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4445     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4446                        DAG.getIntPtrConstant(0, DL));
4447   } else {
4448     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4449                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4450     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4451   }
4452 }
4453
4454 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4455 /// bit-count for each 32-bit element from the operand.  The idea here is
4456 /// to split the vector into 16-bit elements, leverage the 16-bit count
4457 /// routine, and then combine the results.
4458 ///
4459 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4460 /// input    = [v0    v1    ] (vi: 32-bit elements)
4461 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4462 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4463 /// vrev: N0 = [k1 k0 k3 k2 ]
4464 ///            [k0 k1 k2 k3 ]
4465 ///       N1 =+[k1 k0 k3 k2 ]
4466 ///            [k0 k2 k1 k3 ]
4467 ///       N2 =+[k1 k3 k0 k2 ]
4468 ///            [k0    k2    k1    k3    ]
4469 /// Extended =+[k1    k3    k0    k2    ]
4470 ///            [k0    k2    ]
4471 /// Extracted=+[k1    k3    ]
4472 ///
4473 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4474   EVT VT = N->getValueType(0);
4475   SDLoc DL(N);
4476
4477   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4478
4479   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4480   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4481   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4482   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4483   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4484
4485   if (VT.is64BitVector()) {
4486     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4487     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4488                        DAG.getIntPtrConstant(0, DL));
4489   } else {
4490     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4491                                     DAG.getIntPtrConstant(0, DL));
4492     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4493   }
4494 }
4495
4496 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4497                           const ARMSubtarget *ST) {
4498   EVT VT = N->getValueType(0);
4499
4500   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4501   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4502           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4503          "Unexpected type for custom ctpop lowering");
4504
4505   if (VT.getVectorElementType() == MVT::i32)
4506     return lowerCTPOP32BitElements(N, DAG);
4507   else
4508     return lowerCTPOP16BitElements(N, DAG);
4509 }
4510
4511 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4512                           const ARMSubtarget *ST) {
4513   EVT VT = N->getValueType(0);
4514   SDLoc dl(N);
4515
4516   if (!VT.isVector())
4517     return SDValue();
4518
4519   // Lower vector shifts on NEON to use VSHL.
4520   assert(ST->hasNEON() && "unexpected vector shift");
4521
4522   // Left shifts translate directly to the vshiftu intrinsic.
4523   if (N->getOpcode() == ISD::SHL)
4524     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4525                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4526                                        MVT::i32),
4527                        N->getOperand(0), N->getOperand(1));
4528
4529   assert((N->getOpcode() == ISD::SRA ||
4530           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4531
4532   // NEON uses the same intrinsics for both left and right shifts.  For
4533   // right shifts, the shift amounts are negative, so negate the vector of
4534   // shift amounts.
4535   EVT ShiftVT = N->getOperand(1).getValueType();
4536   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4537                                      getZeroVector(ShiftVT, DAG, dl),
4538                                      N->getOperand(1));
4539   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4540                              Intrinsic::arm_neon_vshifts :
4541                              Intrinsic::arm_neon_vshiftu);
4542   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4543                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4544                      N->getOperand(0), NegatedCount);
4545 }
4546
4547 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4548                                 const ARMSubtarget *ST) {
4549   EVT VT = N->getValueType(0);
4550   SDLoc dl(N);
4551
4552   // We can get here for a node like i32 = ISD::SHL i32, i64
4553   if (VT != MVT::i64)
4554     return SDValue();
4555
4556   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4557          "Unknown shift to lower!");
4558
4559   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4560   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4561       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4562     return SDValue();
4563
4564   // If we are in thumb mode, we don't have RRX.
4565   if (ST->isThumb1Only()) return SDValue();
4566
4567   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4568   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4569                            DAG.getConstant(0, dl, MVT::i32));
4570   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4571                            DAG.getConstant(1, dl, MVT::i32));
4572
4573   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4574   // captures the result into a carry flag.
4575   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4576   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4577
4578   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4579   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4580
4581   // Merge the pieces into a single i64 value.
4582  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4583 }
4584
4585 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4586   SDValue TmpOp0, TmpOp1;
4587   bool Invert = false;
4588   bool Swap = false;
4589   unsigned Opc = 0;
4590
4591   SDValue Op0 = Op.getOperand(0);
4592   SDValue Op1 = Op.getOperand(1);
4593   SDValue CC = Op.getOperand(2);
4594   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4595   EVT VT = Op.getValueType();
4596   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4597   SDLoc dl(Op);
4598
4599   if (Op1.getValueType().isFloatingPoint()) {
4600     switch (SetCCOpcode) {
4601     default: llvm_unreachable("Illegal FP comparison");
4602     case ISD::SETUNE:
4603     case ISD::SETNE:  Invert = true; // Fallthrough
4604     case ISD::SETOEQ:
4605     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4606     case ISD::SETOLT:
4607     case ISD::SETLT: Swap = true; // Fallthrough
4608     case ISD::SETOGT:
4609     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4610     case ISD::SETOLE:
4611     case ISD::SETLE:  Swap = true; // Fallthrough
4612     case ISD::SETOGE:
4613     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4614     case ISD::SETUGE: Swap = true; // Fallthrough
4615     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4616     case ISD::SETUGT: Swap = true; // Fallthrough
4617     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4618     case ISD::SETUEQ: Invert = true; // Fallthrough
4619     case ISD::SETONE:
4620       // Expand this to (OLT | OGT).
4621       TmpOp0 = Op0;
4622       TmpOp1 = Op1;
4623       Opc = ISD::OR;
4624       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4625       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4626       break;
4627     case ISD::SETUO: Invert = true; // Fallthrough
4628     case ISD::SETO:
4629       // Expand this to (OLT | OGE).
4630       TmpOp0 = Op0;
4631       TmpOp1 = Op1;
4632       Opc = ISD::OR;
4633       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4634       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4635       break;
4636     }
4637   } else {
4638     // Integer comparisons.
4639     switch (SetCCOpcode) {
4640     default: llvm_unreachable("Illegal integer comparison");
4641     case ISD::SETNE:  Invert = true;
4642     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4643     case ISD::SETLT:  Swap = true;
4644     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4645     case ISD::SETLE:  Swap = true;
4646     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4647     case ISD::SETULT: Swap = true;
4648     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4649     case ISD::SETULE: Swap = true;
4650     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4651     }
4652
4653     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4654     if (Opc == ARMISD::VCEQ) {
4655
4656       SDValue AndOp;
4657       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4658         AndOp = Op0;
4659       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4660         AndOp = Op1;
4661
4662       // Ignore bitconvert.
4663       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4664         AndOp = AndOp.getOperand(0);
4665
4666       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4667         Opc = ARMISD::VTST;
4668         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4669         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4670         Invert = !Invert;
4671       }
4672     }
4673   }
4674
4675   if (Swap)
4676     std::swap(Op0, Op1);
4677
4678   // If one of the operands is a constant vector zero, attempt to fold the
4679   // comparison to a specialized compare-against-zero form.
4680   SDValue SingleOp;
4681   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4682     SingleOp = Op0;
4683   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4684     if (Opc == ARMISD::VCGE)
4685       Opc = ARMISD::VCLEZ;
4686     else if (Opc == ARMISD::VCGT)
4687       Opc = ARMISD::VCLTZ;
4688     SingleOp = Op1;
4689   }
4690
4691   SDValue Result;
4692   if (SingleOp.getNode()) {
4693     switch (Opc) {
4694     case ARMISD::VCEQ:
4695       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4696     case ARMISD::VCGE:
4697       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4698     case ARMISD::VCLEZ:
4699       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4700     case ARMISD::VCGT:
4701       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4702     case ARMISD::VCLTZ:
4703       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4704     default:
4705       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4706     }
4707   } else {
4708      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4709   }
4710
4711   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4712
4713   if (Invert)
4714     Result = DAG.getNOT(dl, Result, VT);
4715
4716   return Result;
4717 }
4718
4719 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4720 /// valid vector constant for a NEON instruction with a "modified immediate"
4721 /// operand (e.g., VMOV).  If so, return the encoded value.
4722 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4723                                  unsigned SplatBitSize, SelectionDAG &DAG,
4724                                  SDLoc dl, EVT &VT, bool is128Bits,
4725                                  NEONModImmType type) {
4726   unsigned OpCmode, Imm;
4727
4728   // SplatBitSize is set to the smallest size that splats the vector, so a
4729   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4730   // immediate instructions others than VMOV do not support the 8-bit encoding
4731   // of a zero vector, and the default encoding of zero is supposed to be the
4732   // 32-bit version.
4733   if (SplatBits == 0)
4734     SplatBitSize = 32;
4735
4736   switch (SplatBitSize) {
4737   case 8:
4738     if (type != VMOVModImm)
4739       return SDValue();
4740     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4741     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4742     OpCmode = 0xe;
4743     Imm = SplatBits;
4744     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4745     break;
4746
4747   case 16:
4748     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4749     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4750     if ((SplatBits & ~0xff) == 0) {
4751       // Value = 0x00nn: Op=x, Cmode=100x.
4752       OpCmode = 0x8;
4753       Imm = SplatBits;
4754       break;
4755     }
4756     if ((SplatBits & ~0xff00) == 0) {
4757       // Value = 0xnn00: Op=x, Cmode=101x.
4758       OpCmode = 0xa;
4759       Imm = SplatBits >> 8;
4760       break;
4761     }
4762     return SDValue();
4763
4764   case 32:
4765     // NEON's 32-bit VMOV supports splat values where:
4766     // * only one byte is nonzero, or
4767     // * the least significant byte is 0xff and the second byte is nonzero, or
4768     // * the least significant 2 bytes are 0xff and the third is nonzero.
4769     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4770     if ((SplatBits & ~0xff) == 0) {
4771       // Value = 0x000000nn: Op=x, Cmode=000x.
4772       OpCmode = 0;
4773       Imm = SplatBits;
4774       break;
4775     }
4776     if ((SplatBits & ~0xff00) == 0) {
4777       // Value = 0x0000nn00: Op=x, Cmode=001x.
4778       OpCmode = 0x2;
4779       Imm = SplatBits >> 8;
4780       break;
4781     }
4782     if ((SplatBits & ~0xff0000) == 0) {
4783       // Value = 0x00nn0000: Op=x, Cmode=010x.
4784       OpCmode = 0x4;
4785       Imm = SplatBits >> 16;
4786       break;
4787     }
4788     if ((SplatBits & ~0xff000000) == 0) {
4789       // Value = 0xnn000000: Op=x, Cmode=011x.
4790       OpCmode = 0x6;
4791       Imm = SplatBits >> 24;
4792       break;
4793     }
4794
4795     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4796     if (type == OtherModImm) return SDValue();
4797
4798     if ((SplatBits & ~0xffff) == 0 &&
4799         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4800       // Value = 0x0000nnff: Op=x, Cmode=1100.
4801       OpCmode = 0xc;
4802       Imm = SplatBits >> 8;
4803       break;
4804     }
4805
4806     if ((SplatBits & ~0xffffff) == 0 &&
4807         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4808       // Value = 0x00nnffff: Op=x, Cmode=1101.
4809       OpCmode = 0xd;
4810       Imm = SplatBits >> 16;
4811       break;
4812     }
4813
4814     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4815     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4816     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4817     // and fall through here to test for a valid 64-bit splat.  But, then the
4818     // caller would also need to check and handle the change in size.
4819     return SDValue();
4820
4821   case 64: {
4822     if (type != VMOVModImm)
4823       return SDValue();
4824     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4825     uint64_t BitMask = 0xff;
4826     uint64_t Val = 0;
4827     unsigned ImmMask = 1;
4828     Imm = 0;
4829     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4830       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4831         Val |= BitMask;
4832         Imm |= ImmMask;
4833       } else if ((SplatBits & BitMask) != 0) {
4834         return SDValue();
4835       }
4836       BitMask <<= 8;
4837       ImmMask <<= 1;
4838     }
4839
4840     if (DAG.getDataLayout().isBigEndian())
4841       // swap higher and lower 32 bit word
4842       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4843
4844     // Op=1, Cmode=1110.
4845     OpCmode = 0x1e;
4846     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4847     break;
4848   }
4849
4850   default:
4851     llvm_unreachable("unexpected size for isNEONModifiedImm");
4852   }
4853
4854   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4855   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4856 }
4857
4858 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4859                                            const ARMSubtarget *ST) const {
4860   if (!ST->hasVFP3())
4861     return SDValue();
4862
4863   bool IsDouble = Op.getValueType() == MVT::f64;
4864   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4865
4866   // Use the default (constant pool) lowering for double constants when we have
4867   // an SP-only FPU
4868   if (IsDouble && Subtarget->isFPOnlySP())
4869     return SDValue();
4870
4871   // Try splatting with a VMOV.f32...
4872   APFloat FPVal = CFP->getValueAPF();
4873   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4874
4875   if (ImmVal != -1) {
4876     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4877       // We have code in place to select a valid ConstantFP already, no need to
4878       // do any mangling.
4879       return Op;
4880     }
4881
4882     // It's a float and we are trying to use NEON operations where
4883     // possible. Lower it to a splat followed by an extract.
4884     SDLoc DL(Op);
4885     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4886     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4887                                       NewVal);
4888     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4889                        DAG.getConstant(0, DL, MVT::i32));
4890   }
4891
4892   // The rest of our options are NEON only, make sure that's allowed before
4893   // proceeding..
4894   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4895     return SDValue();
4896
4897   EVT VMovVT;
4898   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4899
4900   // It wouldn't really be worth bothering for doubles except for one very
4901   // important value, which does happen to match: 0.0. So make sure we don't do
4902   // anything stupid.
4903   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4904     return SDValue();
4905
4906   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4907   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4908                                      VMovVT, false, VMOVModImm);
4909   if (NewVal != SDValue()) {
4910     SDLoc DL(Op);
4911     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4912                                       NewVal);
4913     if (IsDouble)
4914       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4915
4916     // It's a float: cast and extract a vector element.
4917     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4918                                        VecConstant);
4919     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4920                        DAG.getConstant(0, DL, MVT::i32));
4921   }
4922
4923   // Finally, try a VMVN.i32
4924   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4925                              false, VMVNModImm);
4926   if (NewVal != SDValue()) {
4927     SDLoc DL(Op);
4928     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4929
4930     if (IsDouble)
4931       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4932
4933     // It's a float: cast and extract a vector element.
4934     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4935                                        VecConstant);
4936     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4937                        DAG.getConstant(0, DL, MVT::i32));
4938   }
4939
4940   return SDValue();
4941 }
4942
4943 // check if an VEXT instruction can handle the shuffle mask when the
4944 // vector sources of the shuffle are the same.
4945 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4946   unsigned NumElts = VT.getVectorNumElements();
4947
4948   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4949   if (M[0] < 0)
4950     return false;
4951
4952   Imm = M[0];
4953
4954   // If this is a VEXT shuffle, the immediate value is the index of the first
4955   // element.  The other shuffle indices must be the successive elements after
4956   // the first one.
4957   unsigned ExpectedElt = Imm;
4958   for (unsigned i = 1; i < NumElts; ++i) {
4959     // Increment the expected index.  If it wraps around, just follow it
4960     // back to index zero and keep going.
4961     ++ExpectedElt;
4962     if (ExpectedElt == NumElts)
4963       ExpectedElt = 0;
4964
4965     if (M[i] < 0) continue; // ignore UNDEF indices
4966     if (ExpectedElt != static_cast<unsigned>(M[i]))
4967       return false;
4968   }
4969
4970   return true;
4971 }
4972
4973
4974 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4975                        bool &ReverseVEXT, unsigned &Imm) {
4976   unsigned NumElts = VT.getVectorNumElements();
4977   ReverseVEXT = false;
4978
4979   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4980   if (M[0] < 0)
4981     return false;
4982
4983   Imm = M[0];
4984
4985   // If this is a VEXT shuffle, the immediate value is the index of the first
4986   // element.  The other shuffle indices must be the successive elements after
4987   // the first one.
4988   unsigned ExpectedElt = Imm;
4989   for (unsigned i = 1; i < NumElts; ++i) {
4990     // Increment the expected index.  If it wraps around, it may still be
4991     // a VEXT but the source vectors must be swapped.
4992     ExpectedElt += 1;
4993     if (ExpectedElt == NumElts * 2) {
4994       ExpectedElt = 0;
4995       ReverseVEXT = true;
4996     }
4997
4998     if (M[i] < 0) continue; // ignore UNDEF indices
4999     if (ExpectedElt != static_cast<unsigned>(M[i]))
5000       return false;
5001   }
5002
5003   // Adjust the index value if the source operands will be swapped.
5004   if (ReverseVEXT)
5005     Imm -= NumElts;
5006
5007   return true;
5008 }
5009
5010 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5011 /// instruction with the specified blocksize.  (The order of the elements
5012 /// within each block of the vector is reversed.)
5013 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5014   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5015          "Only possible block sizes for VREV are: 16, 32, 64");
5016
5017   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5018   if (EltSz == 64)
5019     return false;
5020
5021   unsigned NumElts = VT.getVectorNumElements();
5022   unsigned BlockElts = M[0] + 1;
5023   // If the first shuffle index is UNDEF, be optimistic.
5024   if (M[0] < 0)
5025     BlockElts = BlockSize / EltSz;
5026
5027   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5028     return false;
5029
5030   for (unsigned i = 0; i < NumElts; ++i) {
5031     if (M[i] < 0) continue; // ignore UNDEF indices
5032     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5033       return false;
5034   }
5035
5036   return true;
5037 }
5038
5039 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5040   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5041   // range, then 0 is placed into the resulting vector. So pretty much any mask
5042   // of 8 elements can work here.
5043   return VT == MVT::v8i8 && M.size() == 8;
5044 }
5045
5046 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5047 // checking that pairs of elements in the shuffle mask represent the same index
5048 // in each vector, incrementing the expected index by 2 at each step.
5049 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5050 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5051 //  v2={e,f,g,h}
5052 // WhichResult gives the offset for each element in the mask based on which
5053 // of the two results it belongs to.
5054 //
5055 // The transpose can be represented either as:
5056 // result1 = shufflevector v1, v2, result1_shuffle_mask
5057 // result2 = shufflevector v1, v2, result2_shuffle_mask
5058 // where v1/v2 and the shuffle masks have the same number of elements
5059 // (here WhichResult (see below) indicates which result is being checked)
5060 //
5061 // or as:
5062 // results = shufflevector v1, v2, shuffle_mask
5063 // where both results are returned in one vector and the shuffle mask has twice
5064 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5065 // want to check the low half and high half of the shuffle mask as if it were
5066 // the other case
5067 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5068   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5069   if (EltSz == 64)
5070     return false;
5071
5072   unsigned NumElts = VT.getVectorNumElements();
5073   if (M.size() != NumElts && M.size() != NumElts*2)
5074     return false;
5075
5076   // If the mask is twice as long as the result then we need to check the upper
5077   // and lower parts of the mask
5078   for (unsigned i = 0; i < M.size(); i += NumElts) {
5079     WhichResult = M[i] == 0 ? 0 : 1;
5080     for (unsigned j = 0; j < NumElts; j += 2) {
5081       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5082           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5083         return false;
5084     }
5085   }
5086
5087   if (M.size() == NumElts*2)
5088     WhichResult = 0;
5089
5090   return true;
5091 }
5092
5093 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5094 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5095 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5096 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5097   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5098   if (EltSz == 64)
5099     return false;
5100
5101   unsigned NumElts = VT.getVectorNumElements();
5102   if (M.size() != NumElts && M.size() != NumElts*2)
5103     return false;
5104
5105   for (unsigned i = 0; i < M.size(); i += NumElts) {
5106     WhichResult = M[i] == 0 ? 0 : 1;
5107     for (unsigned j = 0; j < NumElts; j += 2) {
5108       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5109           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5110         return false;
5111     }
5112   }
5113
5114   if (M.size() == NumElts*2)
5115     WhichResult = 0;
5116
5117   return true;
5118 }
5119
5120 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5121 // that the mask elements are either all even and in steps of size 2 or all odd
5122 // and in steps of size 2.
5123 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5124 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5125 //  v2={e,f,g,h}
5126 // Requires similar checks to that of isVTRNMask with
5127 // respect the how results are returned.
5128 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5129   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5130   if (EltSz == 64)
5131     return false;
5132
5133   unsigned NumElts = VT.getVectorNumElements();
5134   if (M.size() != NumElts && M.size() != NumElts*2)
5135     return false;
5136
5137   for (unsigned i = 0; i < M.size(); i += NumElts) {
5138     WhichResult = M[i] == 0 ? 0 : 1;
5139     for (unsigned j = 0; j < NumElts; ++j) {
5140       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5141         return false;
5142     }
5143   }
5144
5145   if (M.size() == NumElts*2)
5146     WhichResult = 0;
5147
5148   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5149   if (VT.is64BitVector() && EltSz == 32)
5150     return false;
5151
5152   return true;
5153 }
5154
5155 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5156 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5157 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5158 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5159   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5160   if (EltSz == 64)
5161     return false;
5162
5163   unsigned NumElts = VT.getVectorNumElements();
5164   if (M.size() != NumElts && M.size() != NumElts*2)
5165     return false;
5166
5167   unsigned Half = NumElts / 2;
5168   for (unsigned i = 0; i < M.size(); i += NumElts) {
5169     WhichResult = M[i] == 0 ? 0 : 1;
5170     for (unsigned j = 0; j < NumElts; j += Half) {
5171       unsigned Idx = WhichResult;
5172       for (unsigned k = 0; k < Half; ++k) {
5173         int MIdx = M[i + j + k];
5174         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5175           return false;
5176         Idx += 2;
5177       }
5178     }
5179   }
5180
5181   if (M.size() == NumElts*2)
5182     WhichResult = 0;
5183
5184   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5185   if (VT.is64BitVector() && EltSz == 32)
5186     return false;
5187
5188   return true;
5189 }
5190
5191 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5192 // that pairs of elements of the shufflemask represent the same index in each
5193 // vector incrementing sequentially through the vectors.
5194 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5195 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5196 //  v2={e,f,g,h}
5197 // Requires similar checks to that of isVTRNMask with respect the how results
5198 // are returned.
5199 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5200   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5201   if (EltSz == 64)
5202     return false;
5203
5204   unsigned NumElts = VT.getVectorNumElements();
5205   if (M.size() != NumElts && M.size() != NumElts*2)
5206     return false;
5207
5208   for (unsigned i = 0; i < M.size(); i += NumElts) {
5209     WhichResult = M[i] == 0 ? 0 : 1;
5210     unsigned Idx = WhichResult * NumElts / 2;
5211     for (unsigned j = 0; j < NumElts; j += 2) {
5212       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5213           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5214         return false;
5215       Idx += 1;
5216     }
5217   }
5218
5219   if (M.size() == NumElts*2)
5220     WhichResult = 0;
5221
5222   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5223   if (VT.is64BitVector() && EltSz == 32)
5224     return false;
5225
5226   return true;
5227 }
5228
5229 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5230 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5231 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5232 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5233   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5234   if (EltSz == 64)
5235     return false;
5236
5237   unsigned NumElts = VT.getVectorNumElements();
5238   if (M.size() != NumElts && M.size() != NumElts*2)
5239     return false;
5240
5241   for (unsigned i = 0; i < M.size(); i += NumElts) {
5242     WhichResult = M[i] == 0 ? 0 : 1;
5243     unsigned Idx = WhichResult * NumElts / 2;
5244     for (unsigned j = 0; j < NumElts; j += 2) {
5245       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5246           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5247         return false;
5248       Idx += 1;
5249     }
5250   }
5251
5252   if (M.size() == NumElts*2)
5253     WhichResult = 0;
5254
5255   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5256   if (VT.is64BitVector() && EltSz == 32)
5257     return false;
5258
5259   return true;
5260 }
5261
5262 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5263 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5264 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5265                                            unsigned &WhichResult,
5266                                            bool &isV_UNDEF) {
5267   isV_UNDEF = false;
5268   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5269     return ARMISD::VTRN;
5270   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5271     return ARMISD::VUZP;
5272   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5273     return ARMISD::VZIP;
5274
5275   isV_UNDEF = true;
5276   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5277     return ARMISD::VTRN;
5278   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5279     return ARMISD::VUZP;
5280   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5281     return ARMISD::VZIP;
5282
5283   return 0;
5284 }
5285
5286 /// \return true if this is a reverse operation on an vector.
5287 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5288   unsigned NumElts = VT.getVectorNumElements();
5289   // Make sure the mask has the right size.
5290   if (NumElts != M.size())
5291       return false;
5292
5293   // Look for <15, ..., 3, -1, 1, 0>.
5294   for (unsigned i = 0; i != NumElts; ++i)
5295     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5296       return false;
5297
5298   return true;
5299 }
5300
5301 // If N is an integer constant that can be moved into a register in one
5302 // instruction, return an SDValue of such a constant (will become a MOV
5303 // instruction).  Otherwise return null.
5304 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5305                                      const ARMSubtarget *ST, SDLoc dl) {
5306   uint64_t Val;
5307   if (!isa<ConstantSDNode>(N))
5308     return SDValue();
5309   Val = cast<ConstantSDNode>(N)->getZExtValue();
5310
5311   if (ST->isThumb1Only()) {
5312     if (Val <= 255 || ~Val <= 255)
5313       return DAG.getConstant(Val, dl, MVT::i32);
5314   } else {
5315     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5316       return DAG.getConstant(Val, dl, MVT::i32);
5317   }
5318   return SDValue();
5319 }
5320
5321 // If this is a case we can't handle, return null and let the default
5322 // expansion code take care of it.
5323 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5324                                              const ARMSubtarget *ST) const {
5325   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5326   SDLoc dl(Op);
5327   EVT VT = Op.getValueType();
5328
5329   APInt SplatBits, SplatUndef;
5330   unsigned SplatBitSize;
5331   bool HasAnyUndefs;
5332   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5333     if (SplatBitSize <= 64) {
5334       // Check if an immediate VMOV works.
5335       EVT VmovVT;
5336       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5337                                       SplatUndef.getZExtValue(), SplatBitSize,
5338                                       DAG, dl, VmovVT, VT.is128BitVector(),
5339                                       VMOVModImm);
5340       if (Val.getNode()) {
5341         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5342         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5343       }
5344
5345       // Try an immediate VMVN.
5346       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5347       Val = isNEONModifiedImm(NegatedImm,
5348                                       SplatUndef.getZExtValue(), SplatBitSize,
5349                                       DAG, dl, VmovVT, VT.is128BitVector(),
5350                                       VMVNModImm);
5351       if (Val.getNode()) {
5352         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5353         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5354       }
5355
5356       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5357       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5358         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5359         if (ImmVal != -1) {
5360           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5361           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5362         }
5363       }
5364     }
5365   }
5366
5367   // Scan through the operands to see if only one value is used.
5368   //
5369   // As an optimisation, even if more than one value is used it may be more
5370   // profitable to splat with one value then change some lanes.
5371   //
5372   // Heuristically we decide to do this if the vector has a "dominant" value,
5373   // defined as splatted to more than half of the lanes.
5374   unsigned NumElts = VT.getVectorNumElements();
5375   bool isOnlyLowElement = true;
5376   bool usesOnlyOneValue = true;
5377   bool hasDominantValue = false;
5378   bool isConstant = true;
5379
5380   // Map of the number of times a particular SDValue appears in the
5381   // element list.
5382   DenseMap<SDValue, unsigned> ValueCounts;
5383   SDValue Value;
5384   for (unsigned i = 0; i < NumElts; ++i) {
5385     SDValue V = Op.getOperand(i);
5386     if (V.getOpcode() == ISD::UNDEF)
5387       continue;
5388     if (i > 0)
5389       isOnlyLowElement = false;
5390     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5391       isConstant = false;
5392
5393     ValueCounts.insert(std::make_pair(V, 0));
5394     unsigned &Count = ValueCounts[V];
5395
5396     // Is this value dominant? (takes up more than half of the lanes)
5397     if (++Count > (NumElts / 2)) {
5398       hasDominantValue = true;
5399       Value = V;
5400     }
5401   }
5402   if (ValueCounts.size() != 1)
5403     usesOnlyOneValue = false;
5404   if (!Value.getNode() && ValueCounts.size() > 0)
5405     Value = ValueCounts.begin()->first;
5406
5407   if (ValueCounts.size() == 0)
5408     return DAG.getUNDEF(VT);
5409
5410   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5411   // Keep going if we are hitting this case.
5412   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5413     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5414
5415   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5416
5417   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5418   // i32 and try again.
5419   if (hasDominantValue && EltSize <= 32) {
5420     if (!isConstant) {
5421       SDValue N;
5422
5423       // If we are VDUPing a value that comes directly from a vector, that will
5424       // cause an unnecessary move to and from a GPR, where instead we could
5425       // just use VDUPLANE. We can only do this if the lane being extracted
5426       // is at a constant index, as the VDUP from lane instructions only have
5427       // constant-index forms.
5428       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5429           isa<ConstantSDNode>(Value->getOperand(1))) {
5430         // We need to create a new undef vector to use for the VDUPLANE if the
5431         // size of the vector from which we get the value is different than the
5432         // size of the vector that we need to create. We will insert the element
5433         // such that the register coalescer will remove unnecessary copies.
5434         if (VT != Value->getOperand(0).getValueType()) {
5435           ConstantSDNode *constIndex;
5436           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5437           assert(constIndex && "The index is not a constant!");
5438           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5439                              VT.getVectorNumElements();
5440           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5441                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5442                         Value, DAG.getConstant(index, dl, MVT::i32)),
5443                            DAG.getConstant(index, dl, MVT::i32));
5444         } else
5445           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5446                         Value->getOperand(0), Value->getOperand(1));
5447       } else
5448         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5449
5450       if (!usesOnlyOneValue) {
5451         // The dominant value was splatted as 'N', but we now have to insert
5452         // all differing elements.
5453         for (unsigned I = 0; I < NumElts; ++I) {
5454           if (Op.getOperand(I) == Value)
5455             continue;
5456           SmallVector<SDValue, 3> Ops;
5457           Ops.push_back(N);
5458           Ops.push_back(Op.getOperand(I));
5459           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5460           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5461         }
5462       }
5463       return N;
5464     }
5465     if (VT.getVectorElementType().isFloatingPoint()) {
5466       SmallVector<SDValue, 8> Ops;
5467       for (unsigned i = 0; i < NumElts; ++i)
5468         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5469                                   Op.getOperand(i)));
5470       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5471       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5472       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5473       if (Val.getNode())
5474         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5475     }
5476     if (usesOnlyOneValue) {
5477       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5478       if (isConstant && Val.getNode())
5479         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5480     }
5481   }
5482
5483   // If all elements are constants and the case above didn't get hit, fall back
5484   // to the default expansion, which will generate a load from the constant
5485   // pool.
5486   if (isConstant)
5487     return SDValue();
5488
5489   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5490   if (NumElts >= 4) {
5491     SDValue shuffle = ReconstructShuffle(Op, DAG);
5492     if (shuffle != SDValue())
5493       return shuffle;
5494   }
5495
5496   // Vectors with 32- or 64-bit elements can be built by directly assigning
5497   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5498   // will be legalized.
5499   if (EltSize >= 32) {
5500     // Do the expansion with floating-point types, since that is what the VFP
5501     // registers are defined to use, and since i64 is not legal.
5502     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5503     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5504     SmallVector<SDValue, 8> Ops;
5505     for (unsigned i = 0; i < NumElts; ++i)
5506       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5507     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5508     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5509   }
5510
5511   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5512   // know the default expansion would otherwise fall back on something even
5513   // worse. For a vector with one or two non-undef values, that's
5514   // scalar_to_vector for the elements followed by a shuffle (provided the
5515   // shuffle is valid for the target) and materialization element by element
5516   // on the stack followed by a load for everything else.
5517   if (!isConstant && !usesOnlyOneValue) {
5518     SDValue Vec = DAG.getUNDEF(VT);
5519     for (unsigned i = 0 ; i < NumElts; ++i) {
5520       SDValue V = Op.getOperand(i);
5521       if (V.getOpcode() == ISD::UNDEF)
5522         continue;
5523       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5524       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5525     }
5526     return Vec;
5527   }
5528
5529   return SDValue();
5530 }
5531
5532 /// getExtFactor - Determine the adjustment factor for the position when
5533 /// generating an "extract from vector registers" instruction.
5534 static unsigned getExtFactor(SDValue &V) {
5535   EVT EltType = V.getValueType().getVectorElementType();
5536   return EltType.getSizeInBits() / 8;
5537 }
5538
5539 // Gather data to see if the operation can be modelled as a
5540 // shuffle in combination with VEXTs.
5541 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5542                                               SelectionDAG &DAG) const {
5543   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5544   SDLoc dl(Op);
5545   EVT VT = Op.getValueType();
5546   unsigned NumElts = VT.getVectorNumElements();
5547
5548   struct ShuffleSourceInfo {
5549     SDValue Vec;
5550     unsigned MinElt;
5551     unsigned MaxElt;
5552
5553     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5554     // be compatible with the shuffle we intend to construct. As a result
5555     // ShuffleVec will be some sliding window into the original Vec.
5556     SDValue ShuffleVec;
5557
5558     // Code should guarantee that element i in Vec starts at element "WindowBase
5559     // + i * WindowScale in ShuffleVec".
5560     int WindowBase;
5561     int WindowScale;
5562
5563     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5564     ShuffleSourceInfo(SDValue Vec)
5565         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5566           WindowScale(1) {}
5567   };
5568
5569   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5570   // node.
5571   SmallVector<ShuffleSourceInfo, 2> Sources;
5572   for (unsigned i = 0; i < NumElts; ++i) {
5573     SDValue V = Op.getOperand(i);
5574     if (V.getOpcode() == ISD::UNDEF)
5575       continue;
5576     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5577       // A shuffle can only come from building a vector from various
5578       // elements of other vectors.
5579       return SDValue();
5580     }
5581
5582     // Add this element source to the list if it's not already there.
5583     SDValue SourceVec = V.getOperand(0);
5584     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5585     if (Source == Sources.end())
5586       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5587
5588     // Update the minimum and maximum lane number seen.
5589     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5590     Source->MinElt = std::min(Source->MinElt, EltNo);
5591     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5592   }
5593
5594   // Currently only do something sane when at most two source vectors
5595   // are involved.
5596   if (Sources.size() > 2)
5597     return SDValue();
5598
5599   // Find out the smallest element size among result and two sources, and use
5600   // it as element size to build the shuffle_vector.
5601   EVT SmallestEltTy = VT.getVectorElementType();
5602   for (auto &Source : Sources) {
5603     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5604     if (SrcEltTy.bitsLT(SmallestEltTy))
5605       SmallestEltTy = SrcEltTy;
5606   }
5607   unsigned ResMultiplier =
5608       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5609   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5610   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5611
5612   // If the source vector is too wide or too narrow, we may nevertheless be able
5613   // to construct a compatible shuffle either by concatenating it with UNDEF or
5614   // extracting a suitable range of elements.
5615   for (auto &Src : Sources) {
5616     EVT SrcVT = Src.ShuffleVec.getValueType();
5617
5618     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5619       continue;
5620
5621     // This stage of the search produces a source with the same element type as
5622     // the original, but with a total width matching the BUILD_VECTOR output.
5623     EVT EltVT = SrcVT.getVectorElementType();
5624     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5625     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5626
5627     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5628       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5629         return SDValue();
5630       // We can pad out the smaller vector for free, so if it's part of a
5631       // shuffle...
5632       Src.ShuffleVec =
5633           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5634                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5635       continue;
5636     }
5637
5638     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5639       return SDValue();
5640
5641     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5642       // Span too large for a VEXT to cope
5643       return SDValue();
5644     }
5645
5646     if (Src.MinElt >= NumSrcElts) {
5647       // The extraction can just take the second half
5648       Src.ShuffleVec =
5649           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5650                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5651       Src.WindowBase = -NumSrcElts;
5652     } else if (Src.MaxElt < NumSrcElts) {
5653       // The extraction can just take the first half
5654       Src.ShuffleVec =
5655           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5656                       DAG.getConstant(0, dl, MVT::i32));
5657     } else {
5658       // An actual VEXT is needed
5659       SDValue VEXTSrc1 =
5660           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5661                       DAG.getConstant(0, dl, MVT::i32));
5662       SDValue VEXTSrc2 =
5663           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5664                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5665       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5666
5667       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5668                                    VEXTSrc2,
5669                                    DAG.getConstant(Imm, dl, MVT::i32));
5670       Src.WindowBase = -Src.MinElt;
5671     }
5672   }
5673
5674   // Another possible incompatibility occurs from the vector element types. We
5675   // can fix this by bitcasting the source vectors to the same type we intend
5676   // for the shuffle.
5677   for (auto &Src : Sources) {
5678     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5679     if (SrcEltTy == SmallestEltTy)
5680       continue;
5681     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5682     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5683     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5684     Src.WindowBase *= Src.WindowScale;
5685   }
5686
5687   // Final sanity check before we try to actually produce a shuffle.
5688   DEBUG(
5689     for (auto Src : Sources)
5690       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5691   );
5692
5693   // The stars all align, our next step is to produce the mask for the shuffle.
5694   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5695   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5696   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5697     SDValue Entry = Op.getOperand(i);
5698     if (Entry.getOpcode() == ISD::UNDEF)
5699       continue;
5700
5701     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5702     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5703
5704     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5705     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5706     // segment.
5707     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5708     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5709                                VT.getVectorElementType().getSizeInBits());
5710     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5711
5712     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5713     // starting at the appropriate offset.
5714     int *LaneMask = &Mask[i * ResMultiplier];
5715
5716     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5717     ExtractBase += NumElts * (Src - Sources.begin());
5718     for (int j = 0; j < LanesDefined; ++j)
5719       LaneMask[j] = ExtractBase + j;
5720   }
5721
5722   // Final check before we try to produce nonsense...
5723   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5724     return SDValue();
5725
5726   // We can't handle more than two sources. This should have already
5727   // been checked before this point.
5728   assert(Sources.size() <= 2 && "Too many sources!");
5729
5730   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5731   for (unsigned i = 0; i < Sources.size(); ++i)
5732     ShuffleOps[i] = Sources[i].ShuffleVec;
5733
5734   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5735                                          ShuffleOps[1], &Mask[0]);
5736   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5737 }
5738
5739 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5740 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5741 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5742 /// are assumed to be legal.
5743 bool
5744 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5745                                       EVT VT) const {
5746   if (VT.getVectorNumElements() == 4 &&
5747       (VT.is128BitVector() || VT.is64BitVector())) {
5748     unsigned PFIndexes[4];
5749     for (unsigned i = 0; i != 4; ++i) {
5750       if (M[i] < 0)
5751         PFIndexes[i] = 8;
5752       else
5753         PFIndexes[i] = M[i];
5754     }
5755
5756     // Compute the index in the perfect shuffle table.
5757     unsigned PFTableIndex =
5758       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5759     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5760     unsigned Cost = (PFEntry >> 30);
5761
5762     if (Cost <= 4)
5763       return true;
5764   }
5765
5766   bool ReverseVEXT, isV_UNDEF;
5767   unsigned Imm, WhichResult;
5768
5769   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5770   return (EltSize >= 32 ||
5771           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5772           isVREVMask(M, VT, 64) ||
5773           isVREVMask(M, VT, 32) ||
5774           isVREVMask(M, VT, 16) ||
5775           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5776           isVTBLMask(M, VT) ||
5777           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5778           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5779 }
5780
5781 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5782 /// the specified operations to build the shuffle.
5783 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5784                                       SDValue RHS, SelectionDAG &DAG,
5785                                       SDLoc dl) {
5786   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5787   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5788   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5789
5790   enum {
5791     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5792     OP_VREV,
5793     OP_VDUP0,
5794     OP_VDUP1,
5795     OP_VDUP2,
5796     OP_VDUP3,
5797     OP_VEXT1,
5798     OP_VEXT2,
5799     OP_VEXT3,
5800     OP_VUZPL, // VUZP, left result
5801     OP_VUZPR, // VUZP, right result
5802     OP_VZIPL, // VZIP, left result
5803     OP_VZIPR, // VZIP, right result
5804     OP_VTRNL, // VTRN, left result
5805     OP_VTRNR  // VTRN, right result
5806   };
5807
5808   if (OpNum == OP_COPY) {
5809     if (LHSID == (1*9+2)*9+3) return LHS;
5810     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5811     return RHS;
5812   }
5813
5814   SDValue OpLHS, OpRHS;
5815   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5816   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5817   EVT VT = OpLHS.getValueType();
5818
5819   switch (OpNum) {
5820   default: llvm_unreachable("Unknown shuffle opcode!");
5821   case OP_VREV:
5822     // VREV divides the vector in half and swaps within the half.
5823     if (VT.getVectorElementType() == MVT::i32 ||
5824         VT.getVectorElementType() == MVT::f32)
5825       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5826     // vrev <4 x i16> -> VREV32
5827     if (VT.getVectorElementType() == MVT::i16)
5828       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5829     // vrev <4 x i8> -> VREV16
5830     assert(VT.getVectorElementType() == MVT::i8);
5831     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5832   case OP_VDUP0:
5833   case OP_VDUP1:
5834   case OP_VDUP2:
5835   case OP_VDUP3:
5836     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5837                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5838   case OP_VEXT1:
5839   case OP_VEXT2:
5840   case OP_VEXT3:
5841     return DAG.getNode(ARMISD::VEXT, dl, VT,
5842                        OpLHS, OpRHS,
5843                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5844   case OP_VUZPL:
5845   case OP_VUZPR:
5846     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5847                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5848   case OP_VZIPL:
5849   case OP_VZIPR:
5850     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5851                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5852   case OP_VTRNL:
5853   case OP_VTRNR:
5854     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5855                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5856   }
5857 }
5858
5859 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5860                                        ArrayRef<int> ShuffleMask,
5861                                        SelectionDAG &DAG) {
5862   // Check to see if we can use the VTBL instruction.
5863   SDValue V1 = Op.getOperand(0);
5864   SDValue V2 = Op.getOperand(1);
5865   SDLoc DL(Op);
5866
5867   SmallVector<SDValue, 8> VTBLMask;
5868   for (ArrayRef<int>::iterator
5869          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5870     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5871
5872   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5873     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5874                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5875
5876   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5877                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5878 }
5879
5880 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5881                                                       SelectionDAG &DAG) {
5882   SDLoc DL(Op);
5883   SDValue OpLHS = Op.getOperand(0);
5884   EVT VT = OpLHS.getValueType();
5885
5886   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5887          "Expect an v8i16/v16i8 type");
5888   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5889   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5890   // extract the first 8 bytes into the top double word and the last 8 bytes
5891   // into the bottom double word. The v8i16 case is similar.
5892   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5893   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5894                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5895 }
5896
5897 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5898   SDValue V1 = Op.getOperand(0);
5899   SDValue V2 = Op.getOperand(1);
5900   SDLoc dl(Op);
5901   EVT VT = Op.getValueType();
5902   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5903
5904   // Convert shuffles that are directly supported on NEON to target-specific
5905   // DAG nodes, instead of keeping them as shuffles and matching them again
5906   // during code selection.  This is more efficient and avoids the possibility
5907   // of inconsistencies between legalization and selection.
5908   // FIXME: floating-point vectors should be canonicalized to integer vectors
5909   // of the same time so that they get CSEd properly.
5910   ArrayRef<int> ShuffleMask = SVN->getMask();
5911
5912   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5913   if (EltSize <= 32) {
5914     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5915       int Lane = SVN->getSplatIndex();
5916       // If this is undef splat, generate it via "just" vdup, if possible.
5917       if (Lane == -1) Lane = 0;
5918
5919       // Test if V1 is a SCALAR_TO_VECTOR.
5920       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5921         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5922       }
5923       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5924       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5925       // reaches it).
5926       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5927           !isa<ConstantSDNode>(V1.getOperand(0))) {
5928         bool IsScalarToVector = true;
5929         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5930           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5931             IsScalarToVector = false;
5932             break;
5933           }
5934         if (IsScalarToVector)
5935           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5936       }
5937       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5938                          DAG.getConstant(Lane, dl, MVT::i32));
5939     }
5940
5941     bool ReverseVEXT;
5942     unsigned Imm;
5943     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5944       if (ReverseVEXT)
5945         std::swap(V1, V2);
5946       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5947                          DAG.getConstant(Imm, dl, MVT::i32));
5948     }
5949
5950     if (isVREVMask(ShuffleMask, VT, 64))
5951       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5952     if (isVREVMask(ShuffleMask, VT, 32))
5953       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5954     if (isVREVMask(ShuffleMask, VT, 16))
5955       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5956
5957     if (V2->getOpcode() == ISD::UNDEF &&
5958         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5959       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5960                          DAG.getConstant(Imm, dl, MVT::i32));
5961     }
5962
5963     // Check for Neon shuffles that modify both input vectors in place.
5964     // If both results are used, i.e., if there are two shuffles with the same
5965     // source operands and with masks corresponding to both results of one of
5966     // these operations, DAG memoization will ensure that a single node is
5967     // used for both shuffles.
5968     unsigned WhichResult;
5969     bool isV_UNDEF;
5970     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5971             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5972       if (isV_UNDEF)
5973         V2 = V1;
5974       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5975           .getValue(WhichResult);
5976     }
5977
5978     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5979     // shuffles that produce a result larger than their operands with:
5980     //   shuffle(concat(v1, undef), concat(v2, undef))
5981     // ->
5982     //   shuffle(concat(v1, v2), undef)
5983     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5984     //
5985     // This is useful in the general case, but there are special cases where
5986     // native shuffles produce larger results: the two-result ops.
5987     //
5988     // Look through the concat when lowering them:
5989     //   shuffle(concat(v1, v2), undef)
5990     // ->
5991     //   concat(VZIP(v1, v2):0, :1)
5992     //
5993     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5994         V2->getOpcode() == ISD::UNDEF) {
5995       SDValue SubV1 = V1->getOperand(0);
5996       SDValue SubV2 = V1->getOperand(1);
5997       EVT SubVT = SubV1.getValueType();
5998
5999       // We expect these to have been canonicalized to -1.
6000       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6001         return i < (int)VT.getVectorNumElements();
6002       }) && "Unexpected shuffle index into UNDEF operand!");
6003
6004       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6005               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6006         if (isV_UNDEF)
6007           SubV2 = SubV1;
6008         assert((WhichResult == 0) &&
6009                "In-place shuffle of concat can only have one result!");
6010         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6011                                   SubV1, SubV2);
6012         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6013                            Res.getValue(1));
6014       }
6015     }
6016   }
6017
6018   // If the shuffle is not directly supported and it has 4 elements, use
6019   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6020   unsigned NumElts = VT.getVectorNumElements();
6021   if (NumElts == 4) {
6022     unsigned PFIndexes[4];
6023     for (unsigned i = 0; i != 4; ++i) {
6024       if (ShuffleMask[i] < 0)
6025         PFIndexes[i] = 8;
6026       else
6027         PFIndexes[i] = ShuffleMask[i];
6028     }
6029
6030     // Compute the index in the perfect shuffle table.
6031     unsigned PFTableIndex =
6032       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6033     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6034     unsigned Cost = (PFEntry >> 30);
6035
6036     if (Cost <= 4)
6037       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6038   }
6039
6040   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6041   if (EltSize >= 32) {
6042     // Do the expansion with floating-point types, since that is what the VFP
6043     // registers are defined to use, and since i64 is not legal.
6044     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6045     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6046     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6047     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6048     SmallVector<SDValue, 8> Ops;
6049     for (unsigned i = 0; i < NumElts; ++i) {
6050       if (ShuffleMask[i] < 0)
6051         Ops.push_back(DAG.getUNDEF(EltVT));
6052       else
6053         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6054                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6055                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6056                                                   dl, MVT::i32)));
6057     }
6058     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6059     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6060   }
6061
6062   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6063     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6064
6065   if (VT == MVT::v8i8) {
6066     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6067     if (NewOp.getNode())
6068       return NewOp;
6069   }
6070
6071   return SDValue();
6072 }
6073
6074 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6075   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6076   SDValue Lane = Op.getOperand(2);
6077   if (!isa<ConstantSDNode>(Lane))
6078     return SDValue();
6079
6080   return Op;
6081 }
6082
6083 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6084   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6085   SDValue Lane = Op.getOperand(1);
6086   if (!isa<ConstantSDNode>(Lane))
6087     return SDValue();
6088
6089   SDValue Vec = Op.getOperand(0);
6090   if (Op.getValueType() == MVT::i32 &&
6091       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6092     SDLoc dl(Op);
6093     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6094   }
6095
6096   return Op;
6097 }
6098
6099 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6100   // The only time a CONCAT_VECTORS operation can have legal types is when
6101   // two 64-bit vectors are concatenated to a 128-bit vector.
6102   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6103          "unexpected CONCAT_VECTORS");
6104   SDLoc dl(Op);
6105   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6106   SDValue Op0 = Op.getOperand(0);
6107   SDValue Op1 = Op.getOperand(1);
6108   if (Op0.getOpcode() != ISD::UNDEF)
6109     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6110                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6111                       DAG.getIntPtrConstant(0, dl));
6112   if (Op1.getOpcode() != ISD::UNDEF)
6113     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6114                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6115                       DAG.getIntPtrConstant(1, dl));
6116   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6117 }
6118
6119 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6120 /// element has been zero/sign-extended, depending on the isSigned parameter,
6121 /// from an integer type half its size.
6122 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6123                                    bool isSigned) {
6124   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6125   EVT VT = N->getValueType(0);
6126   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6127     SDNode *BVN = N->getOperand(0).getNode();
6128     if (BVN->getValueType(0) != MVT::v4i32 ||
6129         BVN->getOpcode() != ISD::BUILD_VECTOR)
6130       return false;
6131     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6132     unsigned HiElt = 1 - LoElt;
6133     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6134     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6135     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6136     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6137     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6138       return false;
6139     if (isSigned) {
6140       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6141           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6142         return true;
6143     } else {
6144       if (Hi0->isNullValue() && Hi1->isNullValue())
6145         return true;
6146     }
6147     return false;
6148   }
6149
6150   if (N->getOpcode() != ISD::BUILD_VECTOR)
6151     return false;
6152
6153   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6154     SDNode *Elt = N->getOperand(i).getNode();
6155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6156       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6157       unsigned HalfSize = EltSize / 2;
6158       if (isSigned) {
6159         if (!isIntN(HalfSize, C->getSExtValue()))
6160           return false;
6161       } else {
6162         if (!isUIntN(HalfSize, C->getZExtValue()))
6163           return false;
6164       }
6165       continue;
6166     }
6167     return false;
6168   }
6169
6170   return true;
6171 }
6172
6173 /// isSignExtended - Check if a node is a vector value that is sign-extended
6174 /// or a constant BUILD_VECTOR with sign-extended elements.
6175 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6176   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6177     return true;
6178   if (isExtendedBUILD_VECTOR(N, DAG, true))
6179     return true;
6180   return false;
6181 }
6182
6183 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6184 /// or a constant BUILD_VECTOR with zero-extended elements.
6185 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6186   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6187     return true;
6188   if (isExtendedBUILD_VECTOR(N, DAG, false))
6189     return true;
6190   return false;
6191 }
6192
6193 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6194   if (OrigVT.getSizeInBits() >= 64)
6195     return OrigVT;
6196
6197   assert(OrigVT.isSimple() && "Expecting a simple value type");
6198
6199   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6200   switch (OrigSimpleTy) {
6201   default: llvm_unreachable("Unexpected Vector Type");
6202   case MVT::v2i8:
6203   case MVT::v2i16:
6204      return MVT::v2i32;
6205   case MVT::v4i8:
6206     return  MVT::v4i16;
6207   }
6208 }
6209
6210 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6211 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6212 /// We insert the required extension here to get the vector to fill a D register.
6213 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6214                                             const EVT &OrigTy,
6215                                             const EVT &ExtTy,
6216                                             unsigned ExtOpcode) {
6217   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6218   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6219   // 64-bits we need to insert a new extension so that it will be 64-bits.
6220   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6221   if (OrigTy.getSizeInBits() >= 64)
6222     return N;
6223
6224   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6225   EVT NewVT = getExtensionTo64Bits(OrigTy);
6226
6227   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6228 }
6229
6230 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6231 /// does not do any sign/zero extension. If the original vector is less
6232 /// than 64 bits, an appropriate extension will be added after the load to
6233 /// reach a total size of 64 bits. We have to add the extension separately
6234 /// because ARM does not have a sign/zero extending load for vectors.
6235 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6236   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6237
6238   // The load already has the right type.
6239   if (ExtendedTy == LD->getMemoryVT())
6240     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6241                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6242                 LD->isNonTemporal(), LD->isInvariant(),
6243                 LD->getAlignment());
6244
6245   // We need to create a zextload/sextload. We cannot just create a load
6246   // followed by a zext/zext node because LowerMUL is also run during normal
6247   // operation legalization where we can't create illegal types.
6248   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6249                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6250                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6251                         LD->isNonTemporal(), LD->getAlignment());
6252 }
6253
6254 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6255 /// extending load, or BUILD_VECTOR with extended elements, return the
6256 /// unextended value. The unextended vector should be 64 bits so that it can
6257 /// be used as an operand to a VMULL instruction. If the original vector size
6258 /// before extension is less than 64 bits we add a an extension to resize
6259 /// the vector to 64 bits.
6260 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6261   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6262     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6263                                         N->getOperand(0)->getValueType(0),
6264                                         N->getValueType(0),
6265                                         N->getOpcode());
6266
6267   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6268     return SkipLoadExtensionForVMULL(LD, DAG);
6269
6270   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6271   // have been legalized as a BITCAST from v4i32.
6272   if (N->getOpcode() == ISD::BITCAST) {
6273     SDNode *BVN = N->getOperand(0).getNode();
6274     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6275            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6276     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6277     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6278                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6279   }
6280   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6281   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6282   EVT VT = N->getValueType(0);
6283   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6284   unsigned NumElts = VT.getVectorNumElements();
6285   MVT TruncVT = MVT::getIntegerVT(EltSize);
6286   SmallVector<SDValue, 8> Ops;
6287   SDLoc dl(N);
6288   for (unsigned i = 0; i != NumElts; ++i) {
6289     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6290     const APInt &CInt = C->getAPIntValue();
6291     // Element types smaller than 32 bits are not legal, so use i32 elements.
6292     // The values are implicitly truncated so sext vs. zext doesn't matter.
6293     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6294   }
6295   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6296                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6297 }
6298
6299 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6300   unsigned Opcode = N->getOpcode();
6301   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6302     SDNode *N0 = N->getOperand(0).getNode();
6303     SDNode *N1 = N->getOperand(1).getNode();
6304     return N0->hasOneUse() && N1->hasOneUse() &&
6305       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6306   }
6307   return false;
6308 }
6309
6310 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6311   unsigned Opcode = N->getOpcode();
6312   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6313     SDNode *N0 = N->getOperand(0).getNode();
6314     SDNode *N1 = N->getOperand(1).getNode();
6315     return N0->hasOneUse() && N1->hasOneUse() &&
6316       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6317   }
6318   return false;
6319 }
6320
6321 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6322   // Multiplications are only custom-lowered for 128-bit vectors so that
6323   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6324   EVT VT = Op.getValueType();
6325   assert(VT.is128BitVector() && VT.isInteger() &&
6326          "unexpected type for custom-lowering ISD::MUL");
6327   SDNode *N0 = Op.getOperand(0).getNode();
6328   SDNode *N1 = Op.getOperand(1).getNode();
6329   unsigned NewOpc = 0;
6330   bool isMLA = false;
6331   bool isN0SExt = isSignExtended(N0, DAG);
6332   bool isN1SExt = isSignExtended(N1, DAG);
6333   if (isN0SExt && isN1SExt)
6334     NewOpc = ARMISD::VMULLs;
6335   else {
6336     bool isN0ZExt = isZeroExtended(N0, DAG);
6337     bool isN1ZExt = isZeroExtended(N1, DAG);
6338     if (isN0ZExt && isN1ZExt)
6339       NewOpc = ARMISD::VMULLu;
6340     else if (isN1SExt || isN1ZExt) {
6341       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6342       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6343       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6344         NewOpc = ARMISD::VMULLs;
6345         isMLA = true;
6346       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6347         NewOpc = ARMISD::VMULLu;
6348         isMLA = true;
6349       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6350         std::swap(N0, N1);
6351         NewOpc = ARMISD::VMULLu;
6352         isMLA = true;
6353       }
6354     }
6355
6356     if (!NewOpc) {
6357       if (VT == MVT::v2i64)
6358         // Fall through to expand this.  It is not legal.
6359         return SDValue();
6360       else
6361         // Other vector multiplications are legal.
6362         return Op;
6363     }
6364   }
6365
6366   // Legalize to a VMULL instruction.
6367   SDLoc DL(Op);
6368   SDValue Op0;
6369   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6370   if (!isMLA) {
6371     Op0 = SkipExtensionForVMULL(N0, DAG);
6372     assert(Op0.getValueType().is64BitVector() &&
6373            Op1.getValueType().is64BitVector() &&
6374            "unexpected types for extended operands to VMULL");
6375     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6376   }
6377
6378   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6379   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6380   //   vmull q0, d4, d6
6381   //   vmlal q0, d5, d6
6382   // is faster than
6383   //   vaddl q0, d4, d5
6384   //   vmovl q1, d6
6385   //   vmul  q0, q0, q1
6386   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6387   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6388   EVT Op1VT = Op1.getValueType();
6389   return DAG.getNode(N0->getOpcode(), DL, VT,
6390                      DAG.getNode(NewOpc, DL, VT,
6391                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6392                      DAG.getNode(NewOpc, DL, VT,
6393                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6394 }
6395
6396 static SDValue
6397 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6398   // Convert to float
6399   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6400   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6401   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6402   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6403   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6404   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6405   // Get reciprocal estimate.
6406   // float4 recip = vrecpeq_f32(yf);
6407   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6408                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6409                    Y);
6410   // Because char has a smaller range than uchar, we can actually get away
6411   // without any newton steps.  This requires that we use a weird bias
6412   // of 0xb000, however (again, this has been exhaustively tested).
6413   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6414   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6415   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6416   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6417   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6418   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6419   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6420   // Convert back to short.
6421   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6422   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6423   return X;
6424 }
6425
6426 static SDValue
6427 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6428   SDValue N2;
6429   // Convert to float.
6430   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6431   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6432   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6433   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6434   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6435   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6436
6437   // Use reciprocal estimate and one refinement step.
6438   // float4 recip = vrecpeq_f32(yf);
6439   // recip *= vrecpsq_f32(yf, recip);
6440   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6441                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6442                    N1);
6443   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6444                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6445                    N1, N2);
6446   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6447   // Because short has a smaller range than ushort, we can actually get away
6448   // with only a single newton step.  This requires that we use a weird bias
6449   // of 89, however (again, this has been exhaustively tested).
6450   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6451   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6452   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6453   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6454   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6455   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6456   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6457   // Convert back to integer and return.
6458   // return vmovn_s32(vcvt_s32_f32(result));
6459   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6460   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6461   return N0;
6462 }
6463
6464 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6465   EVT VT = Op.getValueType();
6466   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6467          "unexpected type for custom-lowering ISD::SDIV");
6468
6469   SDLoc dl(Op);
6470   SDValue N0 = Op.getOperand(0);
6471   SDValue N1 = Op.getOperand(1);
6472   SDValue N2, N3;
6473
6474   if (VT == MVT::v8i8) {
6475     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6476     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6477
6478     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6479                      DAG.getIntPtrConstant(4, dl));
6480     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6481                      DAG.getIntPtrConstant(4, dl));
6482     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6483                      DAG.getIntPtrConstant(0, dl));
6484     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6485                      DAG.getIntPtrConstant(0, dl));
6486
6487     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6488     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6489
6490     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6491     N0 = LowerCONCAT_VECTORS(N0, DAG);
6492
6493     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6494     return N0;
6495   }
6496   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6497 }
6498
6499 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6500   EVT VT = Op.getValueType();
6501   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6502          "unexpected type for custom-lowering ISD::UDIV");
6503
6504   SDLoc dl(Op);
6505   SDValue N0 = Op.getOperand(0);
6506   SDValue N1 = Op.getOperand(1);
6507   SDValue N2, N3;
6508
6509   if (VT == MVT::v8i8) {
6510     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6511     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6512
6513     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6514                      DAG.getIntPtrConstant(4, dl));
6515     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6516                      DAG.getIntPtrConstant(4, dl));
6517     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6518                      DAG.getIntPtrConstant(0, dl));
6519     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6520                      DAG.getIntPtrConstant(0, dl));
6521
6522     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6523     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6524
6525     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6526     N0 = LowerCONCAT_VECTORS(N0, DAG);
6527
6528     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6529                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6530                                      MVT::i32),
6531                      N0);
6532     return N0;
6533   }
6534
6535   // v4i16 sdiv ... Convert to float.
6536   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6537   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6538   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6539   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6540   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6541   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6542
6543   // Use reciprocal estimate and two refinement steps.
6544   // float4 recip = vrecpeq_f32(yf);
6545   // recip *= vrecpsq_f32(yf, recip);
6546   // recip *= vrecpsq_f32(yf, recip);
6547   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6548                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6549                    BN1);
6550   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6551                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6552                    BN1, N2);
6553   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6554   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6555                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6556                    BN1, N2);
6557   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6558   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6559   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6560   // and that it will never cause us to return an answer too large).
6561   // float4 result = as_float4(as_int4(xf*recip) + 2);
6562   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6563   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6564   N1 = DAG.getConstant(2, dl, MVT::i32);
6565   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6566   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6567   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6568   // Convert back to integer and return.
6569   // return vmovn_u32(vcvt_s32_f32(result));
6570   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6571   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6572   return N0;
6573 }
6574
6575 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6576   EVT VT = Op.getNode()->getValueType(0);
6577   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6578
6579   unsigned Opc;
6580   bool ExtraOp = false;
6581   switch (Op.getOpcode()) {
6582   default: llvm_unreachable("Invalid code");
6583   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6584   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6585   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6586   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6587   }
6588
6589   if (!ExtraOp)
6590     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6591                        Op.getOperand(1));
6592   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6593                      Op.getOperand(1), Op.getOperand(2));
6594 }
6595
6596 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6597   assert(Subtarget->isTargetDarwin());
6598
6599   // For iOS, we want to call an alternative entry point: __sincos_stret,
6600   // return values are passed via sret.
6601   SDLoc dl(Op);
6602   SDValue Arg = Op.getOperand(0);
6603   EVT ArgVT = Arg.getValueType();
6604   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6605   auto PtrVT = getPointerTy(DAG.getDataLayout());
6606
6607   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6608
6609   // Pair of floats / doubles used to pass the result.
6610   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6611
6612   // Create stack object for sret.
6613   auto &DL = DAG.getDataLayout();
6614   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6615   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6616   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6617   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6618
6619   ArgListTy Args;
6620   ArgListEntry Entry;
6621
6622   Entry.Node = SRet;
6623   Entry.Ty = RetTy->getPointerTo();
6624   Entry.isSExt = false;
6625   Entry.isZExt = false;
6626   Entry.isSRet = true;
6627   Args.push_back(Entry);
6628
6629   Entry.Node = Arg;
6630   Entry.Ty = ArgTy;
6631   Entry.isSExt = false;
6632   Entry.isZExt = false;
6633   Args.push_back(Entry);
6634
6635   const char *LibcallName  = (ArgVT == MVT::f64)
6636   ? "__sincos_stret" : "__sincosf_stret";
6637   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6638
6639   TargetLowering::CallLoweringInfo CLI(DAG);
6640   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6641     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6642                std::move(Args), 0)
6643     .setDiscardResult();
6644
6645   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6646
6647   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6648                                 MachinePointerInfo(), false, false, false, 0);
6649
6650   // Address of cos field.
6651   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6652                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6653   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6654                                 MachinePointerInfo(), false, false, false, 0);
6655
6656   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6657   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6658                      LoadSin.getValue(0), LoadCos.getValue(0));
6659 }
6660
6661 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6662   // Monotonic load/store is legal for all targets
6663   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6664     return Op;
6665
6666   // Acquire/Release load/store is not legal for targets without a
6667   // dmb or equivalent available.
6668   return SDValue();
6669 }
6670
6671 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6672                                     SmallVectorImpl<SDValue> &Results,
6673                                     SelectionDAG &DAG,
6674                                     const ARMSubtarget *Subtarget) {
6675   SDLoc DL(N);
6676   SDValue Cycles32, OutChain;
6677
6678   if (Subtarget->hasPerfMon()) {
6679     // Under Power Management extensions, the cycle-count is:
6680     //    mrc p15, #0, <Rt>, c9, c13, #0
6681     SDValue Ops[] = { N->getOperand(0), // Chain
6682                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6683                       DAG.getConstant(15, DL, MVT::i32),
6684                       DAG.getConstant(0, DL, MVT::i32),
6685                       DAG.getConstant(9, DL, MVT::i32),
6686                       DAG.getConstant(13, DL, MVT::i32),
6687                       DAG.getConstant(0, DL, MVT::i32)
6688     };
6689
6690     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6691                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6692     OutChain = Cycles32.getValue(1);
6693   } else {
6694     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6695     // there are older ARM CPUs that have implementation-specific ways of
6696     // obtaining this information (FIXME!).
6697     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6698     OutChain = DAG.getEntryNode();
6699   }
6700
6701
6702   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6703                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6704   Results.push_back(Cycles64);
6705   Results.push_back(OutChain);
6706 }
6707
6708 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6709   switch (Op.getOpcode()) {
6710   default: llvm_unreachable("Don't know how to custom lower this!");
6711   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6712   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6713   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6714   case ISD::GlobalAddress:
6715     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6716     default: llvm_unreachable("unknown object format");
6717     case Triple::COFF:
6718       return LowerGlobalAddressWindows(Op, DAG);
6719     case Triple::ELF:
6720       return LowerGlobalAddressELF(Op, DAG);
6721     case Triple::MachO:
6722       return LowerGlobalAddressDarwin(Op, DAG);
6723     }
6724   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6725   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6726   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6727   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6728   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6729   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6730   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6731   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6732   case ISD::SINT_TO_FP:
6733   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6734   case ISD::FP_TO_SINT:
6735   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6736   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6737   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6738   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6739   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6740   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6741   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6742   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6743   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6744                                                                Subtarget);
6745   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6746   case ISD::SHL:
6747   case ISD::SRL:
6748   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6749   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6750   case ISD::SRL_PARTS:
6751   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6752   case ISD::CTTZ:
6753   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6754   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6755   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6756   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6757   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6758   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6759   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6760   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6761   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6762   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6763   case ISD::MUL:           return LowerMUL(Op, DAG);
6764   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6765   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6766   case ISD::ADDC:
6767   case ISD::ADDE:
6768   case ISD::SUBC:
6769   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6770   case ISD::SADDO:
6771   case ISD::UADDO:
6772   case ISD::SSUBO:
6773   case ISD::USUBO:
6774     return LowerXALUO(Op, DAG);
6775   case ISD::ATOMIC_LOAD:
6776   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6777   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6778   case ISD::SDIVREM:
6779   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6780   case ISD::DYNAMIC_STACKALLOC:
6781     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6782       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6783     llvm_unreachable("Don't know how to custom lower this!");
6784   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6785   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6786   }
6787 }
6788
6789 /// ReplaceNodeResults - Replace the results of node with an illegal result
6790 /// type with new values built out of custom code.
6791 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6792                                            SmallVectorImpl<SDValue>&Results,
6793                                            SelectionDAG &DAG) const {
6794   SDValue Res;
6795   switch (N->getOpcode()) {
6796   default:
6797     llvm_unreachable("Don't know how to custom expand this!");
6798   case ISD::READ_REGISTER:
6799     ExpandREAD_REGISTER(N, Results, DAG);
6800     break;
6801   case ISD::BITCAST:
6802     Res = ExpandBITCAST(N, DAG);
6803     break;
6804   case ISD::SRL:
6805   case ISD::SRA:
6806     Res = Expand64BitShift(N, DAG, Subtarget);
6807     break;
6808   case ISD::READCYCLECOUNTER:
6809     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6810     return;
6811   }
6812   if (Res.getNode())
6813     Results.push_back(Res);
6814 }
6815
6816 //===----------------------------------------------------------------------===//
6817 //                           ARM Scheduler Hooks
6818 //===----------------------------------------------------------------------===//
6819
6820 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6821 /// registers the function context.
6822 void ARMTargetLowering::
6823 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6824                        MachineBasicBlock *DispatchBB, int FI) const {
6825   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6826   DebugLoc dl = MI->getDebugLoc();
6827   MachineFunction *MF = MBB->getParent();
6828   MachineRegisterInfo *MRI = &MF->getRegInfo();
6829   MachineConstantPool *MCP = MF->getConstantPool();
6830   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6831   const Function *F = MF->getFunction();
6832
6833   bool isThumb = Subtarget->isThumb();
6834   bool isThumb2 = Subtarget->isThumb2();
6835
6836   unsigned PCLabelId = AFI->createPICLabelUId();
6837   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6838   ARMConstantPoolValue *CPV =
6839     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6840   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6841
6842   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6843                                            : &ARM::GPRRegClass;
6844
6845   // Grab constant pool and fixed stack memory operands.
6846   MachineMemOperand *CPMMO =
6847     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6848                              MachineMemOperand::MOLoad, 4, 4);
6849
6850   MachineMemOperand *FIMMOSt =
6851     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6852                              MachineMemOperand::MOStore, 4, 4);
6853
6854   // Load the address of the dispatch MBB into the jump buffer.
6855   if (isThumb2) {
6856     // Incoming value: jbuf
6857     //   ldr.n  r5, LCPI1_1
6858     //   orr    r5, r5, #1
6859     //   add    r5, pc
6860     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6861     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6862     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6863                    .addConstantPoolIndex(CPI)
6864                    .addMemOperand(CPMMO));
6865     // Set the low bit because of thumb mode.
6866     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6867     AddDefaultCC(
6868       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6869                      .addReg(NewVReg1, RegState::Kill)
6870                      .addImm(0x01)));
6871     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6872     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6873       .addReg(NewVReg2, RegState::Kill)
6874       .addImm(PCLabelId);
6875     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6876                    .addReg(NewVReg3, RegState::Kill)
6877                    .addFrameIndex(FI)
6878                    .addImm(36)  // &jbuf[1] :: pc
6879                    .addMemOperand(FIMMOSt));
6880   } else if (isThumb) {
6881     // Incoming value: jbuf
6882     //   ldr.n  r1, LCPI1_4
6883     //   add    r1, pc
6884     //   mov    r2, #1
6885     //   orrs   r1, r2
6886     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6887     //   str    r1, [r2]
6888     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6889     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6890                    .addConstantPoolIndex(CPI)
6891                    .addMemOperand(CPMMO));
6892     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6893     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6894       .addReg(NewVReg1, RegState::Kill)
6895       .addImm(PCLabelId);
6896     // Set the low bit because of thumb mode.
6897     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6898     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6899                    .addReg(ARM::CPSR, RegState::Define)
6900                    .addImm(1));
6901     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6902     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6903                    .addReg(ARM::CPSR, RegState::Define)
6904                    .addReg(NewVReg2, RegState::Kill)
6905                    .addReg(NewVReg3, RegState::Kill));
6906     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6907     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6908             .addFrameIndex(FI)
6909             .addImm(36); // &jbuf[1] :: pc
6910     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6911                    .addReg(NewVReg4, RegState::Kill)
6912                    .addReg(NewVReg5, RegState::Kill)
6913                    .addImm(0)
6914                    .addMemOperand(FIMMOSt));
6915   } else {
6916     // Incoming value: jbuf
6917     //   ldr  r1, LCPI1_1
6918     //   add  r1, pc, r1
6919     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6920     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6921     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6922                    .addConstantPoolIndex(CPI)
6923                    .addImm(0)
6924                    .addMemOperand(CPMMO));
6925     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6926     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6927                    .addReg(NewVReg1, RegState::Kill)
6928                    .addImm(PCLabelId));
6929     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6930                    .addReg(NewVReg2, RegState::Kill)
6931                    .addFrameIndex(FI)
6932                    .addImm(36)  // &jbuf[1] :: pc
6933                    .addMemOperand(FIMMOSt));
6934   }
6935 }
6936
6937 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6938                                               MachineBasicBlock *MBB) const {
6939   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6940   DebugLoc dl = MI->getDebugLoc();
6941   MachineFunction *MF = MBB->getParent();
6942   MachineRegisterInfo *MRI = &MF->getRegInfo();
6943   MachineFrameInfo *MFI = MF->getFrameInfo();
6944   int FI = MFI->getFunctionContextIndex();
6945
6946   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6947                                                         : &ARM::GPRnopcRegClass;
6948
6949   // Get a mapping of the call site numbers to all of the landing pads they're
6950   // associated with.
6951   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6952   unsigned MaxCSNum = 0;
6953   MachineModuleInfo &MMI = MF->getMMI();
6954   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6955        ++BB) {
6956     if (!BB->isLandingPad()) continue;
6957
6958     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6959     // pad.
6960     for (MachineBasicBlock::iterator
6961            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6962       if (!II->isEHLabel()) continue;
6963
6964       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6965       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6966
6967       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6968       for (SmallVectorImpl<unsigned>::iterator
6969              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6970            CSI != CSE; ++CSI) {
6971         CallSiteNumToLPad[*CSI].push_back(BB);
6972         MaxCSNum = std::max(MaxCSNum, *CSI);
6973       }
6974       break;
6975     }
6976   }
6977
6978   // Get an ordered list of the machine basic blocks for the jump table.
6979   std::vector<MachineBasicBlock*> LPadList;
6980   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6981   LPadList.reserve(CallSiteNumToLPad.size());
6982   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6983     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6984     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6985            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6986       LPadList.push_back(*II);
6987       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6988     }
6989   }
6990
6991   assert(!LPadList.empty() &&
6992          "No landing pad destinations for the dispatch jump table!");
6993
6994   // Create the jump table and associated information.
6995   MachineJumpTableInfo *JTI =
6996     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6997   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6998   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6999
7000   // Create the MBBs for the dispatch code.
7001
7002   // Shove the dispatch's address into the return slot in the function context.
7003   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7004   DispatchBB->setIsLandingPad();
7005
7006   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7007   unsigned trap_opcode;
7008   if (Subtarget->isThumb())
7009     trap_opcode = ARM::tTRAP;
7010   else
7011     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7012
7013   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7014   DispatchBB->addSuccessor(TrapBB);
7015
7016   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7017   DispatchBB->addSuccessor(DispContBB);
7018
7019   // Insert and MBBs.
7020   MF->insert(MF->end(), DispatchBB);
7021   MF->insert(MF->end(), DispContBB);
7022   MF->insert(MF->end(), TrapBB);
7023
7024   // Insert code into the entry block that creates and registers the function
7025   // context.
7026   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7027
7028   MachineMemOperand *FIMMOLd =
7029     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
7030                              MachineMemOperand::MOLoad |
7031                              MachineMemOperand::MOVolatile, 4, 4);
7032
7033   MachineInstrBuilder MIB;
7034   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7035
7036   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7037   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7038
7039   // Add a register mask with no preserved registers.  This results in all
7040   // registers being marked as clobbered.
7041   MIB.addRegMask(RI.getNoPreservedMask());
7042
7043   unsigned NumLPads = LPadList.size();
7044   if (Subtarget->isThumb2()) {
7045     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7046     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7047                    .addFrameIndex(FI)
7048                    .addImm(4)
7049                    .addMemOperand(FIMMOLd));
7050
7051     if (NumLPads < 256) {
7052       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7053                      .addReg(NewVReg1)
7054                      .addImm(LPadList.size()));
7055     } else {
7056       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7057       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7058                      .addImm(NumLPads & 0xFFFF));
7059
7060       unsigned VReg2 = VReg1;
7061       if ((NumLPads & 0xFFFF0000) != 0) {
7062         VReg2 = MRI->createVirtualRegister(TRC);
7063         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7064                        .addReg(VReg1)
7065                        .addImm(NumLPads >> 16));
7066       }
7067
7068       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7069                      .addReg(NewVReg1)
7070                      .addReg(VReg2));
7071     }
7072
7073     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7074       .addMBB(TrapBB)
7075       .addImm(ARMCC::HI)
7076       .addReg(ARM::CPSR);
7077
7078     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7079     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7080                    .addJumpTableIndex(MJTI));
7081
7082     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7083     AddDefaultCC(
7084       AddDefaultPred(
7085         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7086         .addReg(NewVReg3, RegState::Kill)
7087         .addReg(NewVReg1)
7088         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7089
7090     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7091       .addReg(NewVReg4, RegState::Kill)
7092       .addReg(NewVReg1)
7093       .addJumpTableIndex(MJTI);
7094   } else if (Subtarget->isThumb()) {
7095     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7096     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7097                    .addFrameIndex(FI)
7098                    .addImm(1)
7099                    .addMemOperand(FIMMOLd));
7100
7101     if (NumLPads < 256) {
7102       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7103                      .addReg(NewVReg1)
7104                      .addImm(NumLPads));
7105     } else {
7106       MachineConstantPool *ConstantPool = MF->getConstantPool();
7107       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7108       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7109
7110       // MachineConstantPool wants an explicit alignment.
7111       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7112       if (Align == 0)
7113         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7114       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7115
7116       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7117       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7118                      .addReg(VReg1, RegState::Define)
7119                      .addConstantPoolIndex(Idx));
7120       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7121                      .addReg(NewVReg1)
7122                      .addReg(VReg1));
7123     }
7124
7125     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7126       .addMBB(TrapBB)
7127       .addImm(ARMCC::HI)
7128       .addReg(ARM::CPSR);
7129
7130     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7131     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7132                    .addReg(ARM::CPSR, RegState::Define)
7133                    .addReg(NewVReg1)
7134                    .addImm(2));
7135
7136     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7137     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7138                    .addJumpTableIndex(MJTI));
7139
7140     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7141     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7142                    .addReg(ARM::CPSR, RegState::Define)
7143                    .addReg(NewVReg2, RegState::Kill)
7144                    .addReg(NewVReg3));
7145
7146     MachineMemOperand *JTMMOLd =
7147       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7148                                MachineMemOperand::MOLoad, 4, 4);
7149
7150     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7151     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7152                    .addReg(NewVReg4, RegState::Kill)
7153                    .addImm(0)
7154                    .addMemOperand(JTMMOLd));
7155
7156     unsigned NewVReg6 = NewVReg5;
7157     if (RelocM == Reloc::PIC_) {
7158       NewVReg6 = MRI->createVirtualRegister(TRC);
7159       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7160                      .addReg(ARM::CPSR, RegState::Define)
7161                      .addReg(NewVReg5, RegState::Kill)
7162                      .addReg(NewVReg3));
7163     }
7164
7165     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7166       .addReg(NewVReg6, RegState::Kill)
7167       .addJumpTableIndex(MJTI);
7168   } else {
7169     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7170     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7171                    .addFrameIndex(FI)
7172                    .addImm(4)
7173                    .addMemOperand(FIMMOLd));
7174
7175     if (NumLPads < 256) {
7176       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7177                      .addReg(NewVReg1)
7178                      .addImm(NumLPads));
7179     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7180       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7181       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7182                      .addImm(NumLPads & 0xFFFF));
7183
7184       unsigned VReg2 = VReg1;
7185       if ((NumLPads & 0xFFFF0000) != 0) {
7186         VReg2 = MRI->createVirtualRegister(TRC);
7187         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7188                        .addReg(VReg1)
7189                        .addImm(NumLPads >> 16));
7190       }
7191
7192       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7193                      .addReg(NewVReg1)
7194                      .addReg(VReg2));
7195     } else {
7196       MachineConstantPool *ConstantPool = MF->getConstantPool();
7197       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7198       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7199
7200       // MachineConstantPool wants an explicit alignment.
7201       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7202       if (Align == 0)
7203         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7204       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7205
7206       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7207       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7208                      .addReg(VReg1, RegState::Define)
7209                      .addConstantPoolIndex(Idx)
7210                      .addImm(0));
7211       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7212                      .addReg(NewVReg1)
7213                      .addReg(VReg1, RegState::Kill));
7214     }
7215
7216     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7217       .addMBB(TrapBB)
7218       .addImm(ARMCC::HI)
7219       .addReg(ARM::CPSR);
7220
7221     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7222     AddDefaultCC(
7223       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7224                      .addReg(NewVReg1)
7225                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7226     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7227     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7228                    .addJumpTableIndex(MJTI));
7229
7230     MachineMemOperand *JTMMOLd =
7231       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7232                                MachineMemOperand::MOLoad, 4, 4);
7233     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7234     AddDefaultPred(
7235       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7236       .addReg(NewVReg3, RegState::Kill)
7237       .addReg(NewVReg4)
7238       .addImm(0)
7239       .addMemOperand(JTMMOLd));
7240
7241     if (RelocM == Reloc::PIC_) {
7242       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7243         .addReg(NewVReg5, RegState::Kill)
7244         .addReg(NewVReg4)
7245         .addJumpTableIndex(MJTI);
7246     } else {
7247       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7248         .addReg(NewVReg5, RegState::Kill)
7249         .addJumpTableIndex(MJTI);
7250     }
7251   }
7252
7253   // Add the jump table entries as successors to the MBB.
7254   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7255   for (std::vector<MachineBasicBlock*>::iterator
7256          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7257     MachineBasicBlock *CurMBB = *I;
7258     if (SeenMBBs.insert(CurMBB).second)
7259       DispContBB->addSuccessor(CurMBB);
7260   }
7261
7262   // N.B. the order the invoke BBs are processed in doesn't matter here.
7263   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7264   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7265   for (MachineBasicBlock *BB : InvokeBBs) {
7266
7267     // Remove the landing pad successor from the invoke block and replace it
7268     // with the new dispatch block.
7269     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7270                                                   BB->succ_end());
7271     while (!Successors.empty()) {
7272       MachineBasicBlock *SMBB = Successors.pop_back_val();
7273       if (SMBB->isLandingPad()) {
7274         BB->removeSuccessor(SMBB);
7275         MBBLPads.push_back(SMBB);
7276       }
7277     }
7278
7279     BB->addSuccessor(DispatchBB);
7280
7281     // Find the invoke call and mark all of the callee-saved registers as
7282     // 'implicit defined' so that they're spilled. This prevents code from
7283     // moving instructions to before the EH block, where they will never be
7284     // executed.
7285     for (MachineBasicBlock::reverse_iterator
7286            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7287       if (!II->isCall()) continue;
7288
7289       DenseMap<unsigned, bool> DefRegs;
7290       for (MachineInstr::mop_iterator
7291              OI = II->operands_begin(), OE = II->operands_end();
7292            OI != OE; ++OI) {
7293         if (!OI->isReg()) continue;
7294         DefRegs[OI->getReg()] = true;
7295       }
7296
7297       MachineInstrBuilder MIB(*MF, &*II);
7298
7299       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7300         unsigned Reg = SavedRegs[i];
7301         if (Subtarget->isThumb2() &&
7302             !ARM::tGPRRegClass.contains(Reg) &&
7303             !ARM::hGPRRegClass.contains(Reg))
7304           continue;
7305         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7306           continue;
7307         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7308           continue;
7309         if (!DefRegs[Reg])
7310           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7311       }
7312
7313       break;
7314     }
7315   }
7316
7317   // Mark all former landing pads as non-landing pads. The dispatch is the only
7318   // landing pad now.
7319   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7320          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7321     (*I)->setIsLandingPad(false);
7322
7323   // The instruction is gone now.
7324   MI->eraseFromParent();
7325 }
7326
7327 static
7328 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7329   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7330        E = MBB->succ_end(); I != E; ++I)
7331     if (*I != Succ)
7332       return *I;
7333   llvm_unreachable("Expecting a BB with two successors!");
7334 }
7335
7336 /// Return the load opcode for a given load size. If load size >= 8,
7337 /// neon opcode will be returned.
7338 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7339   if (LdSize >= 8)
7340     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7341                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7342   if (IsThumb1)
7343     return LdSize == 4 ? ARM::tLDRi
7344                        : LdSize == 2 ? ARM::tLDRHi
7345                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7346   if (IsThumb2)
7347     return LdSize == 4 ? ARM::t2LDR_POST
7348                        : LdSize == 2 ? ARM::t2LDRH_POST
7349                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7350   return LdSize == 4 ? ARM::LDR_POST_IMM
7351                      : LdSize == 2 ? ARM::LDRH_POST
7352                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7353 }
7354
7355 /// Return the store opcode for a given store size. If store size >= 8,
7356 /// neon opcode will be returned.
7357 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7358   if (StSize >= 8)
7359     return StSize == 16 ? ARM::VST1q32wb_fixed
7360                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7361   if (IsThumb1)
7362     return StSize == 4 ? ARM::tSTRi
7363                        : StSize == 2 ? ARM::tSTRHi
7364                                      : StSize == 1 ? ARM::tSTRBi : 0;
7365   if (IsThumb2)
7366     return StSize == 4 ? ARM::t2STR_POST
7367                        : StSize == 2 ? ARM::t2STRH_POST
7368                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7369   return StSize == 4 ? ARM::STR_POST_IMM
7370                      : StSize == 2 ? ARM::STRH_POST
7371                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7372 }
7373
7374 /// Emit a post-increment load operation with given size. The instructions
7375 /// will be added to BB at Pos.
7376 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7377                        const TargetInstrInfo *TII, DebugLoc dl,
7378                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7379                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7380   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7381   assert(LdOpc != 0 && "Should have a load opcode");
7382   if (LdSize >= 8) {
7383     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7384                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7385                        .addImm(0));
7386   } else if (IsThumb1) {
7387     // load + update AddrIn
7388     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7389                        .addReg(AddrIn).addImm(0));
7390     MachineInstrBuilder MIB =
7391         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7392     MIB = AddDefaultT1CC(MIB);
7393     MIB.addReg(AddrIn).addImm(LdSize);
7394     AddDefaultPred(MIB);
7395   } else if (IsThumb2) {
7396     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7397                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7398                        .addImm(LdSize));
7399   } else { // arm
7400     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7401                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7402                        .addReg(0).addImm(LdSize));
7403   }
7404 }
7405
7406 /// Emit a post-increment store operation with given size. The instructions
7407 /// will be added to BB at Pos.
7408 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7409                        const TargetInstrInfo *TII, DebugLoc dl,
7410                        unsigned StSize, unsigned Data, unsigned AddrIn,
7411                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7412   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7413   assert(StOpc != 0 && "Should have a store opcode");
7414   if (StSize >= 8) {
7415     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7416                        .addReg(AddrIn).addImm(0).addReg(Data));
7417   } else if (IsThumb1) {
7418     // store + update AddrIn
7419     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7420                        .addReg(AddrIn).addImm(0));
7421     MachineInstrBuilder MIB =
7422         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7423     MIB = AddDefaultT1CC(MIB);
7424     MIB.addReg(AddrIn).addImm(StSize);
7425     AddDefaultPred(MIB);
7426   } else if (IsThumb2) {
7427     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7428                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7429   } else { // arm
7430     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7431                        .addReg(Data).addReg(AddrIn).addReg(0)
7432                        .addImm(StSize));
7433   }
7434 }
7435
7436 MachineBasicBlock *
7437 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7438                                    MachineBasicBlock *BB) const {
7439   // This pseudo instruction has 3 operands: dst, src, size
7440   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7441   // Otherwise, we will generate unrolled scalar copies.
7442   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7443   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7444   MachineFunction::iterator It = BB;
7445   ++It;
7446
7447   unsigned dest = MI->getOperand(0).getReg();
7448   unsigned src = MI->getOperand(1).getReg();
7449   unsigned SizeVal = MI->getOperand(2).getImm();
7450   unsigned Align = MI->getOperand(3).getImm();
7451   DebugLoc dl = MI->getDebugLoc();
7452
7453   MachineFunction *MF = BB->getParent();
7454   MachineRegisterInfo &MRI = MF->getRegInfo();
7455   unsigned UnitSize = 0;
7456   const TargetRegisterClass *TRC = nullptr;
7457   const TargetRegisterClass *VecTRC = nullptr;
7458
7459   bool IsThumb1 = Subtarget->isThumb1Only();
7460   bool IsThumb2 = Subtarget->isThumb2();
7461
7462   if (Align & 1) {
7463     UnitSize = 1;
7464   } else if (Align & 2) {
7465     UnitSize = 2;
7466   } else {
7467     // Check whether we can use NEON instructions.
7468     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7469         Subtarget->hasNEON()) {
7470       if ((Align % 16 == 0) && SizeVal >= 16)
7471         UnitSize = 16;
7472       else if ((Align % 8 == 0) && SizeVal >= 8)
7473         UnitSize = 8;
7474     }
7475     // Can't use NEON instructions.
7476     if (UnitSize == 0)
7477       UnitSize = 4;
7478   }
7479
7480   // Select the correct opcode and register class for unit size load/store
7481   bool IsNeon = UnitSize >= 8;
7482   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7483   if (IsNeon)
7484     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7485                             : UnitSize == 8 ? &ARM::DPRRegClass
7486                                             : nullptr;
7487
7488   unsigned BytesLeft = SizeVal % UnitSize;
7489   unsigned LoopSize = SizeVal - BytesLeft;
7490
7491   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7492     // Use LDR and STR to copy.
7493     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7494     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7495     unsigned srcIn = src;
7496     unsigned destIn = dest;
7497     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7498       unsigned srcOut = MRI.createVirtualRegister(TRC);
7499       unsigned destOut = MRI.createVirtualRegister(TRC);
7500       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7501       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7502                  IsThumb1, IsThumb2);
7503       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7504                  IsThumb1, IsThumb2);
7505       srcIn = srcOut;
7506       destIn = destOut;
7507     }
7508
7509     // Handle the leftover bytes with LDRB and STRB.
7510     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7511     // [destOut] = STRB_POST(scratch, destIn, 1)
7512     for (unsigned i = 0; i < BytesLeft; i++) {
7513       unsigned srcOut = MRI.createVirtualRegister(TRC);
7514       unsigned destOut = MRI.createVirtualRegister(TRC);
7515       unsigned scratch = MRI.createVirtualRegister(TRC);
7516       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7517                  IsThumb1, IsThumb2);
7518       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7519                  IsThumb1, IsThumb2);
7520       srcIn = srcOut;
7521       destIn = destOut;
7522     }
7523     MI->eraseFromParent();   // The instruction is gone now.
7524     return BB;
7525   }
7526
7527   // Expand the pseudo op to a loop.
7528   // thisMBB:
7529   //   ...
7530   //   movw varEnd, # --> with thumb2
7531   //   movt varEnd, #
7532   //   ldrcp varEnd, idx --> without thumb2
7533   //   fallthrough --> loopMBB
7534   // loopMBB:
7535   //   PHI varPhi, varEnd, varLoop
7536   //   PHI srcPhi, src, srcLoop
7537   //   PHI destPhi, dst, destLoop
7538   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7539   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7540   //   subs varLoop, varPhi, #UnitSize
7541   //   bne loopMBB
7542   //   fallthrough --> exitMBB
7543   // exitMBB:
7544   //   epilogue to handle left-over bytes
7545   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7546   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7547   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7548   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7549   MF->insert(It, loopMBB);
7550   MF->insert(It, exitMBB);
7551
7552   // Transfer the remainder of BB and its successor edges to exitMBB.
7553   exitMBB->splice(exitMBB->begin(), BB,
7554                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7555   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7556
7557   // Load an immediate to varEnd.
7558   unsigned varEnd = MRI.createVirtualRegister(TRC);
7559   if (Subtarget->useMovt(*MF)) {
7560     unsigned Vtmp = varEnd;
7561     if ((LoopSize & 0xFFFF0000) != 0)
7562       Vtmp = MRI.createVirtualRegister(TRC);
7563     AddDefaultPred(BuildMI(BB, dl,
7564                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7565                            Vtmp).addImm(LoopSize & 0xFFFF));
7566
7567     if ((LoopSize & 0xFFFF0000) != 0)
7568       AddDefaultPred(BuildMI(BB, dl,
7569                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7570                              varEnd)
7571                          .addReg(Vtmp)
7572                          .addImm(LoopSize >> 16));
7573   } else {
7574     MachineConstantPool *ConstantPool = MF->getConstantPool();
7575     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7576     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7577
7578     // MachineConstantPool wants an explicit alignment.
7579     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7580     if (Align == 0)
7581       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7582     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7583
7584     if (IsThumb1)
7585       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7586           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7587     else
7588       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7589           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7590   }
7591   BB->addSuccessor(loopMBB);
7592
7593   // Generate the loop body:
7594   //   varPhi = PHI(varLoop, varEnd)
7595   //   srcPhi = PHI(srcLoop, src)
7596   //   destPhi = PHI(destLoop, dst)
7597   MachineBasicBlock *entryBB = BB;
7598   BB = loopMBB;
7599   unsigned varLoop = MRI.createVirtualRegister(TRC);
7600   unsigned varPhi = MRI.createVirtualRegister(TRC);
7601   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7602   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7603   unsigned destLoop = MRI.createVirtualRegister(TRC);
7604   unsigned destPhi = MRI.createVirtualRegister(TRC);
7605
7606   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7607     .addReg(varLoop).addMBB(loopMBB)
7608     .addReg(varEnd).addMBB(entryBB);
7609   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7610     .addReg(srcLoop).addMBB(loopMBB)
7611     .addReg(src).addMBB(entryBB);
7612   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7613     .addReg(destLoop).addMBB(loopMBB)
7614     .addReg(dest).addMBB(entryBB);
7615
7616   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7617   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7618   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7619   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7620              IsThumb1, IsThumb2);
7621   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7622              IsThumb1, IsThumb2);
7623
7624   // Decrement loop variable by UnitSize.
7625   if (IsThumb1) {
7626     MachineInstrBuilder MIB =
7627         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7628     MIB = AddDefaultT1CC(MIB);
7629     MIB.addReg(varPhi).addImm(UnitSize);
7630     AddDefaultPred(MIB);
7631   } else {
7632     MachineInstrBuilder MIB =
7633         BuildMI(*BB, BB->end(), dl,
7634                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7635     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7636     MIB->getOperand(5).setReg(ARM::CPSR);
7637     MIB->getOperand(5).setIsDef(true);
7638   }
7639   BuildMI(*BB, BB->end(), dl,
7640           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7641       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7642
7643   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7644   BB->addSuccessor(loopMBB);
7645   BB->addSuccessor(exitMBB);
7646
7647   // Add epilogue to handle BytesLeft.
7648   BB = exitMBB;
7649   MachineInstr *StartOfExit = exitMBB->begin();
7650
7651   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7652   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7653   unsigned srcIn = srcLoop;
7654   unsigned destIn = destLoop;
7655   for (unsigned i = 0; i < BytesLeft; i++) {
7656     unsigned srcOut = MRI.createVirtualRegister(TRC);
7657     unsigned destOut = MRI.createVirtualRegister(TRC);
7658     unsigned scratch = MRI.createVirtualRegister(TRC);
7659     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7660                IsThumb1, IsThumb2);
7661     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7662                IsThumb1, IsThumb2);
7663     srcIn = srcOut;
7664     destIn = destOut;
7665   }
7666
7667   MI->eraseFromParent();   // The instruction is gone now.
7668   return BB;
7669 }
7670
7671 MachineBasicBlock *
7672 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7673                                        MachineBasicBlock *MBB) const {
7674   const TargetMachine &TM = getTargetMachine();
7675   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7676   DebugLoc DL = MI->getDebugLoc();
7677
7678   assert(Subtarget->isTargetWindows() &&
7679          "__chkstk is only supported on Windows");
7680   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7681
7682   // __chkstk takes the number of words to allocate on the stack in R4, and
7683   // returns the stack adjustment in number of bytes in R4.  This will not
7684   // clober any other registers (other than the obvious lr).
7685   //
7686   // Although, technically, IP should be considered a register which may be
7687   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7688   // thumb-2 environment, so there is no interworking required.  As a result, we
7689   // do not expect a veneer to be emitted by the linker, clobbering IP.
7690   //
7691   // Each module receives its own copy of __chkstk, so no import thunk is
7692   // required, again, ensuring that IP is not clobbered.
7693   //
7694   // Finally, although some linkers may theoretically provide a trampoline for
7695   // out of range calls (which is quite common due to a 32M range limitation of
7696   // branches for Thumb), we can generate the long-call version via
7697   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7698   // IP.
7699
7700   switch (TM.getCodeModel()) {
7701   case CodeModel::Small:
7702   case CodeModel::Medium:
7703   case CodeModel::Default:
7704   case CodeModel::Kernel:
7705     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7706       .addImm((unsigned)ARMCC::AL).addReg(0)
7707       .addExternalSymbol("__chkstk")
7708       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7709       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7710       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7711     break;
7712   case CodeModel::Large:
7713   case CodeModel::JITDefault: {
7714     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7715     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7716
7717     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7718       .addExternalSymbol("__chkstk");
7719     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7720       .addImm((unsigned)ARMCC::AL).addReg(0)
7721       .addReg(Reg, RegState::Kill)
7722       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7723       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7724       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7725     break;
7726   }
7727   }
7728
7729   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7730                                       ARM::SP)
7731                               .addReg(ARM::SP).addReg(ARM::R4)));
7732
7733   MI->eraseFromParent();
7734   return MBB;
7735 }
7736
7737 MachineBasicBlock *
7738 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7739                                                MachineBasicBlock *BB) const {
7740   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7741   DebugLoc dl = MI->getDebugLoc();
7742   bool isThumb2 = Subtarget->isThumb2();
7743   switch (MI->getOpcode()) {
7744   default: {
7745     MI->dump();
7746     llvm_unreachable("Unexpected instr type to insert");
7747   }
7748   // The Thumb2 pre-indexed stores have the same MI operands, they just
7749   // define them differently in the .td files from the isel patterns, so
7750   // they need pseudos.
7751   case ARM::t2STR_preidx:
7752     MI->setDesc(TII->get(ARM::t2STR_PRE));
7753     return BB;
7754   case ARM::t2STRB_preidx:
7755     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7756     return BB;
7757   case ARM::t2STRH_preidx:
7758     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7759     return BB;
7760
7761   case ARM::STRi_preidx:
7762   case ARM::STRBi_preidx: {
7763     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7764       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7765     // Decode the offset.
7766     unsigned Offset = MI->getOperand(4).getImm();
7767     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7768     Offset = ARM_AM::getAM2Offset(Offset);
7769     if (isSub)
7770       Offset = -Offset;
7771
7772     MachineMemOperand *MMO = *MI->memoperands_begin();
7773     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7774       .addOperand(MI->getOperand(0))  // Rn_wb
7775       .addOperand(MI->getOperand(1))  // Rt
7776       .addOperand(MI->getOperand(2))  // Rn
7777       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7778       .addOperand(MI->getOperand(5))  // pred
7779       .addOperand(MI->getOperand(6))
7780       .addMemOperand(MMO);
7781     MI->eraseFromParent();
7782     return BB;
7783   }
7784   case ARM::STRr_preidx:
7785   case ARM::STRBr_preidx:
7786   case ARM::STRH_preidx: {
7787     unsigned NewOpc;
7788     switch (MI->getOpcode()) {
7789     default: llvm_unreachable("unexpected opcode!");
7790     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7791     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7792     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7793     }
7794     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7795     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7796       MIB.addOperand(MI->getOperand(i));
7797     MI->eraseFromParent();
7798     return BB;
7799   }
7800
7801   case ARM::tMOVCCr_pseudo: {
7802     // To "insert" a SELECT_CC instruction, we actually have to insert the
7803     // diamond control-flow pattern.  The incoming instruction knows the
7804     // destination vreg to set, the condition code register to branch on, the
7805     // true/false values to select between, and a branch opcode to use.
7806     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7807     MachineFunction::iterator It = BB;
7808     ++It;
7809
7810     //  thisMBB:
7811     //  ...
7812     //   TrueVal = ...
7813     //   cmpTY ccX, r1, r2
7814     //   bCC copy1MBB
7815     //   fallthrough --> copy0MBB
7816     MachineBasicBlock *thisMBB  = BB;
7817     MachineFunction *F = BB->getParent();
7818     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7819     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7820     F->insert(It, copy0MBB);
7821     F->insert(It, sinkMBB);
7822
7823     // Transfer the remainder of BB and its successor edges to sinkMBB.
7824     sinkMBB->splice(sinkMBB->begin(), BB,
7825                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7826     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7827
7828     BB->addSuccessor(copy0MBB);
7829     BB->addSuccessor(sinkMBB);
7830
7831     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7832       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7833
7834     //  copy0MBB:
7835     //   %FalseValue = ...
7836     //   # fallthrough to sinkMBB
7837     BB = copy0MBB;
7838
7839     // Update machine-CFG edges
7840     BB->addSuccessor(sinkMBB);
7841
7842     //  sinkMBB:
7843     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7844     //  ...
7845     BB = sinkMBB;
7846     BuildMI(*BB, BB->begin(), dl,
7847             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7848       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7849       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7850
7851     MI->eraseFromParent();   // The pseudo instruction is gone now.
7852     return BB;
7853   }
7854
7855   case ARM::BCCi64:
7856   case ARM::BCCZi64: {
7857     // If there is an unconditional branch to the other successor, remove it.
7858     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7859
7860     // Compare both parts that make up the double comparison separately for
7861     // equality.
7862     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7863
7864     unsigned LHS1 = MI->getOperand(1).getReg();
7865     unsigned LHS2 = MI->getOperand(2).getReg();
7866     if (RHSisZero) {
7867       AddDefaultPred(BuildMI(BB, dl,
7868                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7869                      .addReg(LHS1).addImm(0));
7870       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7871         .addReg(LHS2).addImm(0)
7872         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7873     } else {
7874       unsigned RHS1 = MI->getOperand(3).getReg();
7875       unsigned RHS2 = MI->getOperand(4).getReg();
7876       AddDefaultPred(BuildMI(BB, dl,
7877                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7878                      .addReg(LHS1).addReg(RHS1));
7879       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7880         .addReg(LHS2).addReg(RHS2)
7881         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7882     }
7883
7884     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7885     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7886     if (MI->getOperand(0).getImm() == ARMCC::NE)
7887       std::swap(destMBB, exitMBB);
7888
7889     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7890       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7891     if (isThumb2)
7892       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7893     else
7894       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7895
7896     MI->eraseFromParent();   // The pseudo instruction is gone now.
7897     return BB;
7898   }
7899
7900   case ARM::Int_eh_sjlj_setjmp:
7901   case ARM::Int_eh_sjlj_setjmp_nofp:
7902   case ARM::tInt_eh_sjlj_setjmp:
7903   case ARM::t2Int_eh_sjlj_setjmp:
7904   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7905     return BB;
7906
7907   case ARM::Int_eh_sjlj_setup_dispatch:
7908     EmitSjLjDispatchBlock(MI, BB);
7909     return BB;
7910
7911   case ARM::ABS:
7912   case ARM::t2ABS: {
7913     // To insert an ABS instruction, we have to insert the
7914     // diamond control-flow pattern.  The incoming instruction knows the
7915     // source vreg to test against 0, the destination vreg to set,
7916     // the condition code register to branch on, the
7917     // true/false values to select between, and a branch opcode to use.
7918     // It transforms
7919     //     V1 = ABS V0
7920     // into
7921     //     V2 = MOVS V0
7922     //     BCC                      (branch to SinkBB if V0 >= 0)
7923     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7924     //     SinkBB: V1 = PHI(V2, V3)
7925     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7926     MachineFunction::iterator BBI = BB;
7927     ++BBI;
7928     MachineFunction *Fn = BB->getParent();
7929     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7930     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7931     Fn->insert(BBI, RSBBB);
7932     Fn->insert(BBI, SinkBB);
7933
7934     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7935     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7936     bool ABSSrcKIll = MI->getOperand(1).isKill();
7937     bool isThumb2 = Subtarget->isThumb2();
7938     MachineRegisterInfo &MRI = Fn->getRegInfo();
7939     // In Thumb mode S must not be specified if source register is the SP or
7940     // PC and if destination register is the SP, so restrict register class
7941     unsigned NewRsbDstReg =
7942       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7943
7944     // Transfer the remainder of BB and its successor edges to sinkMBB.
7945     SinkBB->splice(SinkBB->begin(), BB,
7946                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7947     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7948
7949     BB->addSuccessor(RSBBB);
7950     BB->addSuccessor(SinkBB);
7951
7952     // fall through to SinkMBB
7953     RSBBB->addSuccessor(SinkBB);
7954
7955     // insert a cmp at the end of BB
7956     AddDefaultPred(BuildMI(BB, dl,
7957                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7958                    .addReg(ABSSrcReg).addImm(0));
7959
7960     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7961     BuildMI(BB, dl,
7962       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7963       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7964
7965     // insert rsbri in RSBBB
7966     // Note: BCC and rsbri will be converted into predicated rsbmi
7967     // by if-conversion pass
7968     BuildMI(*RSBBB, RSBBB->begin(), dl,
7969       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7970       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7971       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7972
7973     // insert PHI in SinkBB,
7974     // reuse ABSDstReg to not change uses of ABS instruction
7975     BuildMI(*SinkBB, SinkBB->begin(), dl,
7976       TII->get(ARM::PHI), ABSDstReg)
7977       .addReg(NewRsbDstReg).addMBB(RSBBB)
7978       .addReg(ABSSrcReg).addMBB(BB);
7979
7980     // remove ABS instruction
7981     MI->eraseFromParent();
7982
7983     // return last added BB
7984     return SinkBB;
7985   }
7986   case ARM::COPY_STRUCT_BYVAL_I32:
7987     ++NumLoopByVals;
7988     return EmitStructByval(MI, BB);
7989   case ARM::WIN__CHKSTK:
7990     return EmitLowered__chkstk(MI, BB);
7991   }
7992 }
7993
7994 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7995                                                       SDNode *Node) const {
7996   const MCInstrDesc *MCID = &MI->getDesc();
7997   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7998   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7999   // operand is still set to noreg. If needed, set the optional operand's
8000   // register to CPSR, and remove the redundant implicit def.
8001   //
8002   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8003
8004   // Rename pseudo opcodes.
8005   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8006   if (NewOpc) {
8007     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8008     MCID = &TII->get(NewOpc);
8009
8010     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8011            "converted opcode should be the same except for cc_out");
8012
8013     MI->setDesc(*MCID);
8014
8015     // Add the optional cc_out operand
8016     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8017   }
8018   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8019
8020   // Any ARM instruction that sets the 's' bit should specify an optional
8021   // "cc_out" operand in the last operand position.
8022   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8023     assert(!NewOpc && "Optional cc_out operand required");
8024     return;
8025   }
8026   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8027   // since we already have an optional CPSR def.
8028   bool definesCPSR = false;
8029   bool deadCPSR = false;
8030   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8031        i != e; ++i) {
8032     const MachineOperand &MO = MI->getOperand(i);
8033     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8034       definesCPSR = true;
8035       if (MO.isDead())
8036         deadCPSR = true;
8037       MI->RemoveOperand(i);
8038       break;
8039     }
8040   }
8041   if (!definesCPSR) {
8042     assert(!NewOpc && "Optional cc_out operand required");
8043     return;
8044   }
8045   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8046   if (deadCPSR) {
8047     assert(!MI->getOperand(ccOutIdx).getReg() &&
8048            "expect uninitialized optional cc_out operand");
8049     return;
8050   }
8051
8052   // If this instruction was defined with an optional CPSR def and its dag node
8053   // had a live implicit CPSR def, then activate the optional CPSR def.
8054   MachineOperand &MO = MI->getOperand(ccOutIdx);
8055   MO.setReg(ARM::CPSR);
8056   MO.setIsDef(true);
8057 }
8058
8059 //===----------------------------------------------------------------------===//
8060 //                           ARM Optimization Hooks
8061 //===----------------------------------------------------------------------===//
8062
8063 // Helper function that checks if N is a null or all ones constant.
8064 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8065   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8066   if (!C)
8067     return false;
8068   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8069 }
8070
8071 // Return true if N is conditionally 0 or all ones.
8072 // Detects these expressions where cc is an i1 value:
8073 //
8074 //   (select cc 0, y)   [AllOnes=0]
8075 //   (select cc y, 0)   [AllOnes=0]
8076 //   (zext cc)          [AllOnes=0]
8077 //   (sext cc)          [AllOnes=0/1]
8078 //   (select cc -1, y)  [AllOnes=1]
8079 //   (select cc y, -1)  [AllOnes=1]
8080 //
8081 // Invert is set when N is the null/all ones constant when CC is false.
8082 // OtherOp is set to the alternative value of N.
8083 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8084                                        SDValue &CC, bool &Invert,
8085                                        SDValue &OtherOp,
8086                                        SelectionDAG &DAG) {
8087   switch (N->getOpcode()) {
8088   default: return false;
8089   case ISD::SELECT: {
8090     CC = N->getOperand(0);
8091     SDValue N1 = N->getOperand(1);
8092     SDValue N2 = N->getOperand(2);
8093     if (isZeroOrAllOnes(N1, AllOnes)) {
8094       Invert = false;
8095       OtherOp = N2;
8096       return true;
8097     }
8098     if (isZeroOrAllOnes(N2, AllOnes)) {
8099       Invert = true;
8100       OtherOp = N1;
8101       return true;
8102     }
8103     return false;
8104   }
8105   case ISD::ZERO_EXTEND:
8106     // (zext cc) can never be the all ones value.
8107     if (AllOnes)
8108       return false;
8109     // Fall through.
8110   case ISD::SIGN_EXTEND: {
8111     SDLoc dl(N);
8112     EVT VT = N->getValueType(0);
8113     CC = N->getOperand(0);
8114     if (CC.getValueType() != MVT::i1)
8115       return false;
8116     Invert = !AllOnes;
8117     if (AllOnes)
8118       // When looking for an AllOnes constant, N is an sext, and the 'other'
8119       // value is 0.
8120       OtherOp = DAG.getConstant(0, dl, VT);
8121     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8122       // When looking for a 0 constant, N can be zext or sext.
8123       OtherOp = DAG.getConstant(1, dl, VT);
8124     else
8125       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8126                                 VT);
8127     return true;
8128   }
8129   }
8130 }
8131
8132 // Combine a constant select operand into its use:
8133 //
8134 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8135 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8136 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8137 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8138 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8139 //
8140 // The transform is rejected if the select doesn't have a constant operand that
8141 // is null, or all ones when AllOnes is set.
8142 //
8143 // Also recognize sext/zext from i1:
8144 //
8145 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8146 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8147 //
8148 // These transformations eventually create predicated instructions.
8149 //
8150 // @param N       The node to transform.
8151 // @param Slct    The N operand that is a select.
8152 // @param OtherOp The other N operand (x above).
8153 // @param DCI     Context.
8154 // @param AllOnes Require the select constant to be all ones instead of null.
8155 // @returns The new node, or SDValue() on failure.
8156 static
8157 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8158                             TargetLowering::DAGCombinerInfo &DCI,
8159                             bool AllOnes = false) {
8160   SelectionDAG &DAG = DCI.DAG;
8161   EVT VT = N->getValueType(0);
8162   SDValue NonConstantVal;
8163   SDValue CCOp;
8164   bool SwapSelectOps;
8165   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8166                                   NonConstantVal, DAG))
8167     return SDValue();
8168
8169   // Slct is now know to be the desired identity constant when CC is true.
8170   SDValue TrueVal = OtherOp;
8171   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8172                                  OtherOp, NonConstantVal);
8173   // Unless SwapSelectOps says CC should be false.
8174   if (SwapSelectOps)
8175     std::swap(TrueVal, FalseVal);
8176
8177   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8178                      CCOp, TrueVal, FalseVal);
8179 }
8180
8181 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8182 static
8183 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8184                                        TargetLowering::DAGCombinerInfo &DCI) {
8185   SDValue N0 = N->getOperand(0);
8186   SDValue N1 = N->getOperand(1);
8187   if (N0.getNode()->hasOneUse()) {
8188     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8189     if (Result.getNode())
8190       return Result;
8191   }
8192   if (N1.getNode()->hasOneUse()) {
8193     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8194     if (Result.getNode())
8195       return Result;
8196   }
8197   return SDValue();
8198 }
8199
8200 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8201 // (only after legalization).
8202 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8203                                  TargetLowering::DAGCombinerInfo &DCI,
8204                                  const ARMSubtarget *Subtarget) {
8205
8206   // Only perform optimization if after legalize, and if NEON is available. We
8207   // also expected both operands to be BUILD_VECTORs.
8208   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8209       || N0.getOpcode() != ISD::BUILD_VECTOR
8210       || N1.getOpcode() != ISD::BUILD_VECTOR)
8211     return SDValue();
8212
8213   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8214   EVT VT = N->getValueType(0);
8215   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8216     return SDValue();
8217
8218   // Check that the vector operands are of the right form.
8219   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8220   // operands, where N is the size of the formed vector.
8221   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8222   // index such that we have a pair wise add pattern.
8223
8224   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8225   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8226     return SDValue();
8227   SDValue Vec = N0->getOperand(0)->getOperand(0);
8228   SDNode *V = Vec.getNode();
8229   unsigned nextIndex = 0;
8230
8231   // For each operands to the ADD which are BUILD_VECTORs,
8232   // check to see if each of their operands are an EXTRACT_VECTOR with
8233   // the same vector and appropriate index.
8234   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8235     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8236         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8237
8238       SDValue ExtVec0 = N0->getOperand(i);
8239       SDValue ExtVec1 = N1->getOperand(i);
8240
8241       // First operand is the vector, verify its the same.
8242       if (V != ExtVec0->getOperand(0).getNode() ||
8243           V != ExtVec1->getOperand(0).getNode())
8244         return SDValue();
8245
8246       // Second is the constant, verify its correct.
8247       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8248       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8249
8250       // For the constant, we want to see all the even or all the odd.
8251       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8252           || C1->getZExtValue() != nextIndex+1)
8253         return SDValue();
8254
8255       // Increment index.
8256       nextIndex+=2;
8257     } else
8258       return SDValue();
8259   }
8260
8261   // Create VPADDL node.
8262   SelectionDAG &DAG = DCI.DAG;
8263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8264
8265   SDLoc dl(N);
8266
8267   // Build operand list.
8268   SmallVector<SDValue, 8> Ops;
8269   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8270                                 TLI.getPointerTy(DAG.getDataLayout())));
8271
8272   // Input is the vector.
8273   Ops.push_back(Vec);
8274
8275   // Get widened type and narrowed type.
8276   MVT widenType;
8277   unsigned numElem = VT.getVectorNumElements();
8278   
8279   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8280   switch (inputLaneType.getSimpleVT().SimpleTy) {
8281     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8282     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8283     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8284     default:
8285       llvm_unreachable("Invalid vector element type for padd optimization.");
8286   }
8287
8288   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8289   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8290   return DAG.getNode(ExtOp, dl, VT, tmp);
8291 }
8292
8293 static SDValue findMUL_LOHI(SDValue V) {
8294   if (V->getOpcode() == ISD::UMUL_LOHI ||
8295       V->getOpcode() == ISD::SMUL_LOHI)
8296     return V;
8297   return SDValue();
8298 }
8299
8300 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8301                                      TargetLowering::DAGCombinerInfo &DCI,
8302                                      const ARMSubtarget *Subtarget) {
8303
8304   if (Subtarget->isThumb1Only()) return SDValue();
8305
8306   // Only perform the checks after legalize when the pattern is available.
8307   if (DCI.isBeforeLegalize()) return SDValue();
8308
8309   // Look for multiply add opportunities.
8310   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8311   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8312   // a glue link from the first add to the second add.
8313   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8314   // a S/UMLAL instruction.
8315   //                  UMUL_LOHI
8316   //                 / :lo    \ :hi
8317   //                /          \          [no multiline comment]
8318   //    loAdd ->  ADDE         |
8319   //                 \ :glue  /
8320   //                  \      /
8321   //                    ADDC   <- hiAdd
8322   //
8323   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8324   SDValue AddcOp0 = AddcNode->getOperand(0);
8325   SDValue AddcOp1 = AddcNode->getOperand(1);
8326
8327   // Check if the two operands are from the same mul_lohi node.
8328   if (AddcOp0.getNode() == AddcOp1.getNode())
8329     return SDValue();
8330
8331   assert(AddcNode->getNumValues() == 2 &&
8332          AddcNode->getValueType(0) == MVT::i32 &&
8333          "Expect ADDC with two result values. First: i32");
8334
8335   // Check that we have a glued ADDC node.
8336   if (AddcNode->getValueType(1) != MVT::Glue)
8337     return SDValue();
8338
8339   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8340   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8341       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8342       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8343       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8344     return SDValue();
8345
8346   // Look for the glued ADDE.
8347   SDNode* AddeNode = AddcNode->getGluedUser();
8348   if (!AddeNode)
8349     return SDValue();
8350
8351   // Make sure it is really an ADDE.
8352   if (AddeNode->getOpcode() != ISD::ADDE)
8353     return SDValue();
8354
8355   assert(AddeNode->getNumOperands() == 3 &&
8356          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8357          "ADDE node has the wrong inputs");
8358
8359   // Check for the triangle shape.
8360   SDValue AddeOp0 = AddeNode->getOperand(0);
8361   SDValue AddeOp1 = AddeNode->getOperand(1);
8362
8363   // Make sure that the ADDE operands are not coming from the same node.
8364   if (AddeOp0.getNode() == AddeOp1.getNode())
8365     return SDValue();
8366
8367   // Find the MUL_LOHI node walking up ADDE's operands.
8368   bool IsLeftOperandMUL = false;
8369   SDValue MULOp = findMUL_LOHI(AddeOp0);
8370   if (MULOp == SDValue())
8371    MULOp = findMUL_LOHI(AddeOp1);
8372   else
8373     IsLeftOperandMUL = true;
8374   if (MULOp == SDValue())
8375     return SDValue();
8376
8377   // Figure out the right opcode.
8378   unsigned Opc = MULOp->getOpcode();
8379   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8380
8381   // Figure out the high and low input values to the MLAL node.
8382   SDValue* HiAdd = nullptr;
8383   SDValue* LoMul = nullptr;
8384   SDValue* LowAdd = nullptr;
8385
8386   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8387   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8388     return SDValue();
8389
8390   if (IsLeftOperandMUL)
8391     HiAdd = &AddeOp1;
8392   else
8393     HiAdd = &AddeOp0;
8394
8395
8396   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8397   // whose low result is fed to the ADDC we are checking.
8398
8399   if (AddcOp0 == MULOp.getValue(0)) {
8400     LoMul = &AddcOp0;
8401     LowAdd = &AddcOp1;
8402   }
8403   if (AddcOp1 == MULOp.getValue(0)) {
8404     LoMul = &AddcOp1;
8405     LowAdd = &AddcOp0;
8406   }
8407
8408   if (!LoMul)
8409     return SDValue();
8410
8411   // Create the merged node.
8412   SelectionDAG &DAG = DCI.DAG;
8413
8414   // Build operand list.
8415   SmallVector<SDValue, 8> Ops;
8416   Ops.push_back(LoMul->getOperand(0));
8417   Ops.push_back(LoMul->getOperand(1));
8418   Ops.push_back(*LowAdd);
8419   Ops.push_back(*HiAdd);
8420
8421   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8422                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8423
8424   // Replace the ADDs' nodes uses by the MLA node's values.
8425   SDValue HiMLALResult(MLALNode.getNode(), 1);
8426   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8427
8428   SDValue LoMLALResult(MLALNode.getNode(), 0);
8429   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8430
8431   // Return original node to notify the driver to stop replacing.
8432   SDValue resNode(AddcNode, 0);
8433   return resNode;
8434 }
8435
8436 /// PerformADDCCombine - Target-specific dag combine transform from
8437 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8438 static SDValue PerformADDCCombine(SDNode *N,
8439                                  TargetLowering::DAGCombinerInfo &DCI,
8440                                  const ARMSubtarget *Subtarget) {
8441
8442   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8443
8444 }
8445
8446 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8447 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8448 /// called with the default operands, and if that fails, with commuted
8449 /// operands.
8450 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8451                                           TargetLowering::DAGCombinerInfo &DCI,
8452                                           const ARMSubtarget *Subtarget){
8453
8454   // Attempt to create vpaddl for this add.
8455   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8456   if (Result.getNode())
8457     return Result;
8458
8459   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8460   if (N0.getNode()->hasOneUse()) {
8461     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8462     if (Result.getNode()) return Result;
8463   }
8464   return SDValue();
8465 }
8466
8467 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8468 ///
8469 static SDValue PerformADDCombine(SDNode *N,
8470                                  TargetLowering::DAGCombinerInfo &DCI,
8471                                  const ARMSubtarget *Subtarget) {
8472   SDValue N0 = N->getOperand(0);
8473   SDValue N1 = N->getOperand(1);
8474
8475   // First try with the default operand order.
8476   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8477   if (Result.getNode())
8478     return Result;
8479
8480   // If that didn't work, try again with the operands commuted.
8481   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8482 }
8483
8484 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8485 ///
8486 static SDValue PerformSUBCombine(SDNode *N,
8487                                  TargetLowering::DAGCombinerInfo &DCI) {
8488   SDValue N0 = N->getOperand(0);
8489   SDValue N1 = N->getOperand(1);
8490
8491   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8492   if (N1.getNode()->hasOneUse()) {
8493     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8494     if (Result.getNode()) return Result;
8495   }
8496
8497   return SDValue();
8498 }
8499
8500 /// PerformVMULCombine
8501 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8502 /// special multiplier accumulator forwarding.
8503 ///   vmul d3, d0, d2
8504 ///   vmla d3, d1, d2
8505 /// is faster than
8506 ///   vadd d3, d0, d1
8507 ///   vmul d3, d3, d2
8508 //  However, for (A + B) * (A + B),
8509 //    vadd d2, d0, d1
8510 //    vmul d3, d0, d2
8511 //    vmla d3, d1, d2
8512 //  is slower than
8513 //    vadd d2, d0, d1
8514 //    vmul d3, d2, d2
8515 static SDValue PerformVMULCombine(SDNode *N,
8516                                   TargetLowering::DAGCombinerInfo &DCI,
8517                                   const ARMSubtarget *Subtarget) {
8518   if (!Subtarget->hasVMLxForwarding())
8519     return SDValue();
8520
8521   SelectionDAG &DAG = DCI.DAG;
8522   SDValue N0 = N->getOperand(0);
8523   SDValue N1 = N->getOperand(1);
8524   unsigned Opcode = N0.getOpcode();
8525   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8526       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8527     Opcode = N1.getOpcode();
8528     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8529         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8530       return SDValue();
8531     std::swap(N0, N1);
8532   }
8533
8534   if (N0 == N1)
8535     return SDValue();
8536
8537   EVT VT = N->getValueType(0);
8538   SDLoc DL(N);
8539   SDValue N00 = N0->getOperand(0);
8540   SDValue N01 = N0->getOperand(1);
8541   return DAG.getNode(Opcode, DL, VT,
8542                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8543                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8544 }
8545
8546 static SDValue PerformMULCombine(SDNode *N,
8547                                  TargetLowering::DAGCombinerInfo &DCI,
8548                                  const ARMSubtarget *Subtarget) {
8549   SelectionDAG &DAG = DCI.DAG;
8550
8551   if (Subtarget->isThumb1Only())
8552     return SDValue();
8553
8554   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8555     return SDValue();
8556
8557   EVT VT = N->getValueType(0);
8558   if (VT.is64BitVector() || VT.is128BitVector())
8559     return PerformVMULCombine(N, DCI, Subtarget);
8560   if (VT != MVT::i32)
8561     return SDValue();
8562
8563   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8564   if (!C)
8565     return SDValue();
8566
8567   int64_t MulAmt = C->getSExtValue();
8568   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8569
8570   ShiftAmt = ShiftAmt & (32 - 1);
8571   SDValue V = N->getOperand(0);
8572   SDLoc DL(N);
8573
8574   SDValue Res;
8575   MulAmt >>= ShiftAmt;
8576
8577   if (MulAmt >= 0) {
8578     if (isPowerOf2_32(MulAmt - 1)) {
8579       // (mul x, 2^N + 1) => (add (shl x, N), x)
8580       Res = DAG.getNode(ISD::ADD, DL, VT,
8581                         V,
8582                         DAG.getNode(ISD::SHL, DL, VT,
8583                                     V,
8584                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8585                                                     MVT::i32)));
8586     } else if (isPowerOf2_32(MulAmt + 1)) {
8587       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8588       Res = DAG.getNode(ISD::SUB, DL, VT,
8589                         DAG.getNode(ISD::SHL, DL, VT,
8590                                     V,
8591                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8592                                                     MVT::i32)),
8593                         V);
8594     } else
8595       return SDValue();
8596   } else {
8597     uint64_t MulAmtAbs = -MulAmt;
8598     if (isPowerOf2_32(MulAmtAbs + 1)) {
8599       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8600       Res = DAG.getNode(ISD::SUB, DL, VT,
8601                         V,
8602                         DAG.getNode(ISD::SHL, DL, VT,
8603                                     V,
8604                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8605                                                     MVT::i32)));
8606     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8607       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8608       Res = DAG.getNode(ISD::ADD, DL, VT,
8609                         V,
8610                         DAG.getNode(ISD::SHL, DL, VT,
8611                                     V,
8612                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8613                                                     MVT::i32)));
8614       Res = DAG.getNode(ISD::SUB, DL, VT,
8615                         DAG.getConstant(0, DL, MVT::i32), Res);
8616
8617     } else
8618       return SDValue();
8619   }
8620
8621   if (ShiftAmt != 0)
8622     Res = DAG.getNode(ISD::SHL, DL, VT,
8623                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8624
8625   // Do not add new nodes to DAG combiner worklist.
8626   DCI.CombineTo(N, Res, false);
8627   return SDValue();
8628 }
8629
8630 static SDValue PerformANDCombine(SDNode *N,
8631                                  TargetLowering::DAGCombinerInfo &DCI,
8632                                  const ARMSubtarget *Subtarget) {
8633
8634   // Attempt to use immediate-form VBIC
8635   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8636   SDLoc dl(N);
8637   EVT VT = N->getValueType(0);
8638   SelectionDAG &DAG = DCI.DAG;
8639
8640   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8641     return SDValue();
8642
8643   APInt SplatBits, SplatUndef;
8644   unsigned SplatBitSize;
8645   bool HasAnyUndefs;
8646   if (BVN &&
8647       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8648     if (SplatBitSize <= 64) {
8649       EVT VbicVT;
8650       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8651                                       SplatUndef.getZExtValue(), SplatBitSize,
8652                                       DAG, dl, VbicVT, VT.is128BitVector(),
8653                                       OtherModImm);
8654       if (Val.getNode()) {
8655         SDValue Input =
8656           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8657         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8658         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8659       }
8660     }
8661   }
8662
8663   if (!Subtarget->isThumb1Only()) {
8664     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8665     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8666     if (Result.getNode())
8667       return Result;
8668   }
8669
8670   return SDValue();
8671 }
8672
8673 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8674 static SDValue PerformORCombine(SDNode *N,
8675                                 TargetLowering::DAGCombinerInfo &DCI,
8676                                 const ARMSubtarget *Subtarget) {
8677   // Attempt to use immediate-form VORR
8678   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8679   SDLoc dl(N);
8680   EVT VT = N->getValueType(0);
8681   SelectionDAG &DAG = DCI.DAG;
8682
8683   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8684     return SDValue();
8685
8686   APInt SplatBits, SplatUndef;
8687   unsigned SplatBitSize;
8688   bool HasAnyUndefs;
8689   if (BVN && Subtarget->hasNEON() &&
8690       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8691     if (SplatBitSize <= 64) {
8692       EVT VorrVT;
8693       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8694                                       SplatUndef.getZExtValue(), SplatBitSize,
8695                                       DAG, dl, VorrVT, VT.is128BitVector(),
8696                                       OtherModImm);
8697       if (Val.getNode()) {
8698         SDValue Input =
8699           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8700         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8701         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8702       }
8703     }
8704   }
8705
8706   if (!Subtarget->isThumb1Only()) {
8707     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8708     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8709     if (Result.getNode())
8710       return Result;
8711   }
8712
8713   // The code below optimizes (or (and X, Y), Z).
8714   // The AND operand needs to have a single user to make these optimizations
8715   // profitable.
8716   SDValue N0 = N->getOperand(0);
8717   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8718     return SDValue();
8719   SDValue N1 = N->getOperand(1);
8720
8721   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8722   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8723       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8724     APInt SplatUndef;
8725     unsigned SplatBitSize;
8726     bool HasAnyUndefs;
8727
8728     APInt SplatBits0, SplatBits1;
8729     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8730     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8731     // Ensure that the second operand of both ands are constants
8732     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8733                                       HasAnyUndefs) && !HasAnyUndefs) {
8734         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8735                                           HasAnyUndefs) && !HasAnyUndefs) {
8736             // Ensure that the bit width of the constants are the same and that
8737             // the splat arguments are logical inverses as per the pattern we
8738             // are trying to simplify.
8739             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8740                 SplatBits0 == ~SplatBits1) {
8741                 // Canonicalize the vector type to make instruction selection
8742                 // simpler.
8743                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8744                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8745                                              N0->getOperand(1),
8746                                              N0->getOperand(0),
8747                                              N1->getOperand(0));
8748                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8749             }
8750         }
8751     }
8752   }
8753
8754   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8755   // reasonable.
8756
8757   // BFI is only available on V6T2+
8758   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8759     return SDValue();
8760
8761   SDLoc DL(N);
8762   // 1) or (and A, mask), val => ARMbfi A, val, mask
8763   //      iff (val & mask) == val
8764   //
8765   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8766   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8767   //          && mask == ~mask2
8768   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8769   //          && ~mask == mask2
8770   //  (i.e., copy a bitfield value into another bitfield of the same width)
8771
8772   if (VT != MVT::i32)
8773     return SDValue();
8774
8775   SDValue N00 = N0.getOperand(0);
8776
8777   // The value and the mask need to be constants so we can verify this is
8778   // actually a bitfield set. If the mask is 0xffff, we can do better
8779   // via a movt instruction, so don't use BFI in that case.
8780   SDValue MaskOp = N0.getOperand(1);
8781   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8782   if (!MaskC)
8783     return SDValue();
8784   unsigned Mask = MaskC->getZExtValue();
8785   if (Mask == 0xffff)
8786     return SDValue();
8787   SDValue Res;
8788   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8789   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8790   if (N1C) {
8791     unsigned Val = N1C->getZExtValue();
8792     if ((Val & ~Mask) != Val)
8793       return SDValue();
8794
8795     if (ARM::isBitFieldInvertedMask(Mask)) {
8796       Val >>= countTrailingZeros(~Mask);
8797
8798       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8799                         DAG.getConstant(Val, DL, MVT::i32),
8800                         DAG.getConstant(Mask, DL, MVT::i32));
8801
8802       // Do not add new nodes to DAG combiner worklist.
8803       DCI.CombineTo(N, Res, false);
8804       return SDValue();
8805     }
8806   } else if (N1.getOpcode() == ISD::AND) {
8807     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8808     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8809     if (!N11C)
8810       return SDValue();
8811     unsigned Mask2 = N11C->getZExtValue();
8812
8813     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8814     // as is to match.
8815     if (ARM::isBitFieldInvertedMask(Mask) &&
8816         (Mask == ~Mask2)) {
8817       // The pack halfword instruction works better for masks that fit it,
8818       // so use that when it's available.
8819       if (Subtarget->hasT2ExtractPack() &&
8820           (Mask == 0xffff || Mask == 0xffff0000))
8821         return SDValue();
8822       // 2a
8823       unsigned amt = countTrailingZeros(Mask2);
8824       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8825                         DAG.getConstant(amt, DL, MVT::i32));
8826       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8827                         DAG.getConstant(Mask, DL, MVT::i32));
8828       // Do not add new nodes to DAG combiner worklist.
8829       DCI.CombineTo(N, Res, false);
8830       return SDValue();
8831     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8832                (~Mask == Mask2)) {
8833       // The pack halfword instruction works better for masks that fit it,
8834       // so use that when it's available.
8835       if (Subtarget->hasT2ExtractPack() &&
8836           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8837         return SDValue();
8838       // 2b
8839       unsigned lsb = countTrailingZeros(Mask);
8840       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8841                         DAG.getConstant(lsb, DL, MVT::i32));
8842       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8843                         DAG.getConstant(Mask2, DL, MVT::i32));
8844       // Do not add new nodes to DAG combiner worklist.
8845       DCI.CombineTo(N, Res, false);
8846       return SDValue();
8847     }
8848   }
8849
8850   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8851       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8852       ARM::isBitFieldInvertedMask(~Mask)) {
8853     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8854     // where lsb(mask) == #shamt and masked bits of B are known zero.
8855     SDValue ShAmt = N00.getOperand(1);
8856     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8857     unsigned LSB = countTrailingZeros(Mask);
8858     if (ShAmtC != LSB)
8859       return SDValue();
8860
8861     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8862                       DAG.getConstant(~Mask, DL, MVT::i32));
8863
8864     // Do not add new nodes to DAG combiner worklist.
8865     DCI.CombineTo(N, Res, false);
8866   }
8867
8868   return SDValue();
8869 }
8870
8871 static SDValue PerformXORCombine(SDNode *N,
8872                                  TargetLowering::DAGCombinerInfo &DCI,
8873                                  const ARMSubtarget *Subtarget) {
8874   EVT VT = N->getValueType(0);
8875   SelectionDAG &DAG = DCI.DAG;
8876
8877   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8878     return SDValue();
8879
8880   if (!Subtarget->isThumb1Only()) {
8881     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8882     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8883     if (Result.getNode())
8884       return Result;
8885   }
8886
8887   return SDValue();
8888 }
8889
8890 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8891 /// the bits being cleared by the AND are not demanded by the BFI.
8892 static SDValue PerformBFICombine(SDNode *N,
8893                                  TargetLowering::DAGCombinerInfo &DCI) {
8894   SDValue N1 = N->getOperand(1);
8895   if (N1.getOpcode() == ISD::AND) {
8896     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8897     if (!N11C)
8898       return SDValue();
8899     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8900     unsigned LSB = countTrailingZeros(~InvMask);
8901     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8902     assert(Width <
8903                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8904            "undefined behavior");
8905     unsigned Mask = (1u << Width) - 1;
8906     unsigned Mask2 = N11C->getZExtValue();
8907     if ((Mask & (~Mask2)) == 0)
8908       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8909                              N->getOperand(0), N1.getOperand(0),
8910                              N->getOperand(2));
8911   }
8912   return SDValue();
8913 }
8914
8915 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8916 /// ARMISD::VMOVRRD.
8917 static SDValue PerformVMOVRRDCombine(SDNode *N,
8918                                      TargetLowering::DAGCombinerInfo &DCI,
8919                                      const ARMSubtarget *Subtarget) {
8920   // vmovrrd(vmovdrr x, y) -> x,y
8921   SDValue InDouble = N->getOperand(0);
8922   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8923     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8924
8925   // vmovrrd(load f64) -> (load i32), (load i32)
8926   SDNode *InNode = InDouble.getNode();
8927   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8928       InNode->getValueType(0) == MVT::f64 &&
8929       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8930       !cast<LoadSDNode>(InNode)->isVolatile()) {
8931     // TODO: Should this be done for non-FrameIndex operands?
8932     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8933
8934     SelectionDAG &DAG = DCI.DAG;
8935     SDLoc DL(LD);
8936     SDValue BasePtr = LD->getBasePtr();
8937     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8938                                  LD->getPointerInfo(), LD->isVolatile(),
8939                                  LD->isNonTemporal(), LD->isInvariant(),
8940                                  LD->getAlignment());
8941
8942     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8943                                     DAG.getConstant(4, DL, MVT::i32));
8944     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8945                                  LD->getPointerInfo(), LD->isVolatile(),
8946                                  LD->isNonTemporal(), LD->isInvariant(),
8947                                  std::min(4U, LD->getAlignment() / 2));
8948
8949     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8950     if (DCI.DAG.getDataLayout().isBigEndian())
8951       std::swap (NewLD1, NewLD2);
8952     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8953     return Result;
8954   }
8955
8956   return SDValue();
8957 }
8958
8959 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8960 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8961 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8962   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8963   SDValue Op0 = N->getOperand(0);
8964   SDValue Op1 = N->getOperand(1);
8965   if (Op0.getOpcode() == ISD::BITCAST)
8966     Op0 = Op0.getOperand(0);
8967   if (Op1.getOpcode() == ISD::BITCAST)
8968     Op1 = Op1.getOperand(0);
8969   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8970       Op0.getNode() == Op1.getNode() &&
8971       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8972     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8973                        N->getValueType(0), Op0.getOperand(0));
8974   return SDValue();
8975 }
8976
8977 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8978 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8979 /// i64 vector to have f64 elements, since the value can then be loaded
8980 /// directly into a VFP register.
8981 static bool hasNormalLoadOperand(SDNode *N) {
8982   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8983   for (unsigned i = 0; i < NumElts; ++i) {
8984     SDNode *Elt = N->getOperand(i).getNode();
8985     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8986       return true;
8987   }
8988   return false;
8989 }
8990
8991 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8992 /// ISD::BUILD_VECTOR.
8993 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8994                                           TargetLowering::DAGCombinerInfo &DCI,
8995                                           const ARMSubtarget *Subtarget) {
8996   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8997   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8998   // into a pair of GPRs, which is fine when the value is used as a scalar,
8999   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9000   SelectionDAG &DAG = DCI.DAG;
9001   if (N->getNumOperands() == 2) {
9002     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9003     if (RV.getNode())
9004       return RV;
9005   }
9006
9007   // Load i64 elements as f64 values so that type legalization does not split
9008   // them up into i32 values.
9009   EVT VT = N->getValueType(0);
9010   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9011     return SDValue();
9012   SDLoc dl(N);
9013   SmallVector<SDValue, 8> Ops;
9014   unsigned NumElts = VT.getVectorNumElements();
9015   for (unsigned i = 0; i < NumElts; ++i) {
9016     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9017     Ops.push_back(V);
9018     // Make the DAGCombiner fold the bitcast.
9019     DCI.AddToWorklist(V.getNode());
9020   }
9021   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9022   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9023   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9024 }
9025
9026 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9027 static SDValue
9028 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9029   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9030   // At that time, we may have inserted bitcasts from integer to float.
9031   // If these bitcasts have survived DAGCombine, change the lowering of this
9032   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9033   // force to use floating point types.
9034
9035   // Make sure we can change the type of the vector.
9036   // This is possible iff:
9037   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9038   //    1.1. Vector is used only once.
9039   //    1.2. Use is a bit convert to an integer type.
9040   // 2. The size of its operands are 32-bits (64-bits are not legal).
9041   EVT VT = N->getValueType(0);
9042   EVT EltVT = VT.getVectorElementType();
9043
9044   // Check 1.1. and 2.
9045   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9046     return SDValue();
9047
9048   // By construction, the input type must be float.
9049   assert(EltVT == MVT::f32 && "Unexpected type!");
9050
9051   // Check 1.2.
9052   SDNode *Use = *N->use_begin();
9053   if (Use->getOpcode() != ISD::BITCAST ||
9054       Use->getValueType(0).isFloatingPoint())
9055     return SDValue();
9056
9057   // Check profitability.
9058   // Model is, if more than half of the relevant operands are bitcast from
9059   // i32, turn the build_vector into a sequence of insert_vector_elt.
9060   // Relevant operands are everything that is not statically
9061   // (i.e., at compile time) bitcasted.
9062   unsigned NumOfBitCastedElts = 0;
9063   unsigned NumElts = VT.getVectorNumElements();
9064   unsigned NumOfRelevantElts = NumElts;
9065   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9066     SDValue Elt = N->getOperand(Idx);
9067     if (Elt->getOpcode() == ISD::BITCAST) {
9068       // Assume only bit cast to i32 will go away.
9069       if (Elt->getOperand(0).getValueType() == MVT::i32)
9070         ++NumOfBitCastedElts;
9071     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9072       // Constants are statically casted, thus do not count them as
9073       // relevant operands.
9074       --NumOfRelevantElts;
9075   }
9076
9077   // Check if more than half of the elements require a non-free bitcast.
9078   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9079     return SDValue();
9080
9081   SelectionDAG &DAG = DCI.DAG;
9082   // Create the new vector type.
9083   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9084   // Check if the type is legal.
9085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9086   if (!TLI.isTypeLegal(VecVT))
9087     return SDValue();
9088
9089   // Combine:
9090   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9091   // => BITCAST INSERT_VECTOR_ELT
9092   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9093   //                      (BITCAST EN), N.
9094   SDValue Vec = DAG.getUNDEF(VecVT);
9095   SDLoc dl(N);
9096   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9097     SDValue V = N->getOperand(Idx);
9098     if (V.getOpcode() == ISD::UNDEF)
9099       continue;
9100     if (V.getOpcode() == ISD::BITCAST &&
9101         V->getOperand(0).getValueType() == MVT::i32)
9102       // Fold obvious case.
9103       V = V.getOperand(0);
9104     else {
9105       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9106       // Make the DAGCombiner fold the bitcasts.
9107       DCI.AddToWorklist(V.getNode());
9108     }
9109     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9110     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9111   }
9112   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9113   // Make the DAGCombiner fold the bitcasts.
9114   DCI.AddToWorklist(Vec.getNode());
9115   return Vec;
9116 }
9117
9118 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9119 /// ISD::INSERT_VECTOR_ELT.
9120 static SDValue PerformInsertEltCombine(SDNode *N,
9121                                        TargetLowering::DAGCombinerInfo &DCI) {
9122   // Bitcast an i64 load inserted into a vector to f64.
9123   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9124   EVT VT = N->getValueType(0);
9125   SDNode *Elt = N->getOperand(1).getNode();
9126   if (VT.getVectorElementType() != MVT::i64 ||
9127       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9128     return SDValue();
9129
9130   SelectionDAG &DAG = DCI.DAG;
9131   SDLoc dl(N);
9132   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9133                                  VT.getVectorNumElements());
9134   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9135   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9136   // Make the DAGCombiner fold the bitcasts.
9137   DCI.AddToWorklist(Vec.getNode());
9138   DCI.AddToWorklist(V.getNode());
9139   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9140                                Vec, V, N->getOperand(2));
9141   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9142 }
9143
9144 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9145 /// ISD::VECTOR_SHUFFLE.
9146 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9147   // The LLVM shufflevector instruction does not require the shuffle mask
9148   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9149   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9150   // operands do not match the mask length, they are extended by concatenating
9151   // them with undef vectors.  That is probably the right thing for other
9152   // targets, but for NEON it is better to concatenate two double-register
9153   // size vector operands into a single quad-register size vector.  Do that
9154   // transformation here:
9155   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9156   //   shuffle(concat(v1, v2), undef)
9157   SDValue Op0 = N->getOperand(0);
9158   SDValue Op1 = N->getOperand(1);
9159   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9160       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9161       Op0.getNumOperands() != 2 ||
9162       Op1.getNumOperands() != 2)
9163     return SDValue();
9164   SDValue Concat0Op1 = Op0.getOperand(1);
9165   SDValue Concat1Op1 = Op1.getOperand(1);
9166   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9167       Concat1Op1.getOpcode() != ISD::UNDEF)
9168     return SDValue();
9169   // Skip the transformation if any of the types are illegal.
9170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9171   EVT VT = N->getValueType(0);
9172   if (!TLI.isTypeLegal(VT) ||
9173       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9174       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9175     return SDValue();
9176
9177   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9178                                   Op0.getOperand(0), Op1.getOperand(0));
9179   // Translate the shuffle mask.
9180   SmallVector<int, 16> NewMask;
9181   unsigned NumElts = VT.getVectorNumElements();
9182   unsigned HalfElts = NumElts/2;
9183   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9184   for (unsigned n = 0; n < NumElts; ++n) {
9185     int MaskElt = SVN->getMaskElt(n);
9186     int NewElt = -1;
9187     if (MaskElt < (int)HalfElts)
9188       NewElt = MaskElt;
9189     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9190       NewElt = HalfElts + MaskElt - NumElts;
9191     NewMask.push_back(NewElt);
9192   }
9193   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9194                               DAG.getUNDEF(VT), NewMask.data());
9195 }
9196
9197 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9198 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9199 /// base address updates.
9200 /// For generic load/stores, the memory type is assumed to be a vector.
9201 /// The caller is assumed to have checked legality.
9202 static SDValue CombineBaseUpdate(SDNode *N,
9203                                  TargetLowering::DAGCombinerInfo &DCI) {
9204   SelectionDAG &DAG = DCI.DAG;
9205   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9206                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9207   const bool isStore = N->getOpcode() == ISD::STORE;
9208   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9209   SDValue Addr = N->getOperand(AddrOpIdx);
9210   MemSDNode *MemN = cast<MemSDNode>(N);
9211   SDLoc dl(N);
9212
9213   // Search for a use of the address operand that is an increment.
9214   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9215          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9216     SDNode *User = *UI;
9217     if (User->getOpcode() != ISD::ADD ||
9218         UI.getUse().getResNo() != Addr.getResNo())
9219       continue;
9220
9221     // Check that the add is independent of the load/store.  Otherwise, folding
9222     // it would create a cycle.
9223     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9224       continue;
9225
9226     // Find the new opcode for the updating load/store.
9227     bool isLoadOp = true;
9228     bool isLaneOp = false;
9229     unsigned NewOpc = 0;
9230     unsigned NumVecs = 0;
9231     if (isIntrinsic) {
9232       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9233       switch (IntNo) {
9234       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9235       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9236         NumVecs = 1; break;
9237       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9238         NumVecs = 2; break;
9239       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9240         NumVecs = 3; break;
9241       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9242         NumVecs = 4; break;
9243       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9244         NumVecs = 2; isLaneOp = true; break;
9245       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9246         NumVecs = 3; isLaneOp = true; break;
9247       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9248         NumVecs = 4; isLaneOp = true; break;
9249       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9250         NumVecs = 1; isLoadOp = false; break;
9251       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9252         NumVecs = 2; isLoadOp = false; break;
9253       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9254         NumVecs = 3; isLoadOp = false; break;
9255       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9256         NumVecs = 4; isLoadOp = false; break;
9257       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9258         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9259       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9260         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9261       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9262         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9263       }
9264     } else {
9265       isLaneOp = true;
9266       switch (N->getOpcode()) {
9267       default: llvm_unreachable("unexpected opcode for Neon base update");
9268       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9269       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9270       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9271       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9272         NumVecs = 1; isLaneOp = false; break;
9273       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9274         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9275       }
9276     }
9277
9278     // Find the size of memory referenced by the load/store.
9279     EVT VecTy;
9280     if (isLoadOp) {
9281       VecTy = N->getValueType(0);
9282     } else if (isIntrinsic) {
9283       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9284     } else {
9285       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9286       VecTy = N->getOperand(1).getValueType();
9287     }
9288
9289     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9290     if (isLaneOp)
9291       NumBytes /= VecTy.getVectorNumElements();
9292
9293     // If the increment is a constant, it must match the memory ref size.
9294     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9295     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9296       uint64_t IncVal = CInc->getZExtValue();
9297       if (IncVal != NumBytes)
9298         continue;
9299     } else if (NumBytes >= 3 * 16) {
9300       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9301       // separate instructions that make it harder to use a non-constant update.
9302       continue;
9303     }
9304
9305     // OK, we found an ADD we can fold into the base update.
9306     // Now, create a _UPD node, taking care of not breaking alignment.
9307
9308     EVT AlignedVecTy = VecTy;
9309     unsigned Alignment = MemN->getAlignment();
9310
9311     // If this is a less-than-standard-aligned load/store, change the type to
9312     // match the standard alignment.
9313     // The alignment is overlooked when selecting _UPD variants; and it's
9314     // easier to introduce bitcasts here than fix that.
9315     // There are 3 ways to get to this base-update combine:
9316     // - intrinsics: they are assumed to be properly aligned (to the standard
9317     //   alignment of the memory type), so we don't need to do anything.
9318     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9319     //   intrinsics, so, likewise, there's nothing to do.
9320     // - generic load/store instructions: the alignment is specified as an
9321     //   explicit operand, rather than implicitly as the standard alignment
9322     //   of the memory type (like the intrisics).  We need to change the
9323     //   memory type to match the explicit alignment.  That way, we don't
9324     //   generate non-standard-aligned ARMISD::VLDx nodes.
9325     if (isa<LSBaseSDNode>(N)) {
9326       if (Alignment == 0)
9327         Alignment = 1;
9328       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9329         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9330         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9331         assert(!isLaneOp && "Unexpected generic load/store lane.");
9332         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9333         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9334       }
9335       // Don't set an explicit alignment on regular load/stores that we want
9336       // to transform to VLD/VST 1_UPD nodes.
9337       // This matches the behavior of regular load/stores, which only get an
9338       // explicit alignment if the MMO alignment is larger than the standard
9339       // alignment of the memory type.
9340       // Intrinsics, however, always get an explicit alignment, set to the
9341       // alignment of the MMO.
9342       Alignment = 1;
9343     }
9344
9345     // Create the new updating load/store node.
9346     // First, create an SDVTList for the new updating node's results.
9347     EVT Tys[6];
9348     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9349     unsigned n;
9350     for (n = 0; n < NumResultVecs; ++n)
9351       Tys[n] = AlignedVecTy;
9352     Tys[n++] = MVT::i32;
9353     Tys[n] = MVT::Other;
9354     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9355
9356     // Then, gather the new node's operands.
9357     SmallVector<SDValue, 8> Ops;
9358     Ops.push_back(N->getOperand(0)); // incoming chain
9359     Ops.push_back(N->getOperand(AddrOpIdx));
9360     Ops.push_back(Inc);
9361
9362     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9363       // Try to match the intrinsic's signature
9364       Ops.push_back(StN->getValue());
9365     } else {
9366       // Loads (and of course intrinsics) match the intrinsics' signature,
9367       // so just add all but the alignment operand.
9368       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9369         Ops.push_back(N->getOperand(i));
9370     }
9371
9372     // For all node types, the alignment operand is always the last one.
9373     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9374
9375     // If this is a non-standard-aligned STORE, the penultimate operand is the
9376     // stored value.  Bitcast it to the aligned type.
9377     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9378       SDValue &StVal = Ops[Ops.size()-2];
9379       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9380     }
9381
9382     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9383                                            Ops, AlignedVecTy,
9384                                            MemN->getMemOperand());
9385
9386     // Update the uses.
9387     SmallVector<SDValue, 5> NewResults;
9388     for (unsigned i = 0; i < NumResultVecs; ++i)
9389       NewResults.push_back(SDValue(UpdN.getNode(), i));
9390
9391     // If this is an non-standard-aligned LOAD, the first result is the loaded
9392     // value.  Bitcast it to the expected result type.
9393     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9394       SDValue &LdVal = NewResults[0];
9395       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9396     }
9397
9398     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9399     DCI.CombineTo(N, NewResults);
9400     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9401
9402     break;
9403   }
9404   return SDValue();
9405 }
9406
9407 static SDValue PerformVLDCombine(SDNode *N,
9408                                  TargetLowering::DAGCombinerInfo &DCI) {
9409   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9410     return SDValue();
9411
9412   return CombineBaseUpdate(N, DCI);
9413 }
9414
9415 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9416 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9417 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9418 /// return true.
9419 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9420   SelectionDAG &DAG = DCI.DAG;
9421   EVT VT = N->getValueType(0);
9422   // vldN-dup instructions only support 64-bit vectors for N > 1.
9423   if (!VT.is64BitVector())
9424     return false;
9425
9426   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9427   SDNode *VLD = N->getOperand(0).getNode();
9428   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9429     return false;
9430   unsigned NumVecs = 0;
9431   unsigned NewOpc = 0;
9432   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9433   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9434     NumVecs = 2;
9435     NewOpc = ARMISD::VLD2DUP;
9436   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9437     NumVecs = 3;
9438     NewOpc = ARMISD::VLD3DUP;
9439   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9440     NumVecs = 4;
9441     NewOpc = ARMISD::VLD4DUP;
9442   } else {
9443     return false;
9444   }
9445
9446   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9447   // numbers match the load.
9448   unsigned VLDLaneNo =
9449     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9450   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9451        UI != UE; ++UI) {
9452     // Ignore uses of the chain result.
9453     if (UI.getUse().getResNo() == NumVecs)
9454       continue;
9455     SDNode *User = *UI;
9456     if (User->getOpcode() != ARMISD::VDUPLANE ||
9457         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9458       return false;
9459   }
9460
9461   // Create the vldN-dup node.
9462   EVT Tys[5];
9463   unsigned n;
9464   for (n = 0; n < NumVecs; ++n)
9465     Tys[n] = VT;
9466   Tys[n] = MVT::Other;
9467   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9468   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9469   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9470   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9471                                            Ops, VLDMemInt->getMemoryVT(),
9472                                            VLDMemInt->getMemOperand());
9473
9474   // Update the uses.
9475   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9476        UI != UE; ++UI) {
9477     unsigned ResNo = UI.getUse().getResNo();
9478     // Ignore uses of the chain result.
9479     if (ResNo == NumVecs)
9480       continue;
9481     SDNode *User = *UI;
9482     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9483   }
9484
9485   // Now the vldN-lane intrinsic is dead except for its chain result.
9486   // Update uses of the chain.
9487   std::vector<SDValue> VLDDupResults;
9488   for (unsigned n = 0; n < NumVecs; ++n)
9489     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9490   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9491   DCI.CombineTo(VLD, VLDDupResults);
9492
9493   return true;
9494 }
9495
9496 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9497 /// ARMISD::VDUPLANE.
9498 static SDValue PerformVDUPLANECombine(SDNode *N,
9499                                       TargetLowering::DAGCombinerInfo &DCI) {
9500   SDValue Op = N->getOperand(0);
9501
9502   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9503   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9504   if (CombineVLDDUP(N, DCI))
9505     return SDValue(N, 0);
9506
9507   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9508   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9509   while (Op.getOpcode() == ISD::BITCAST)
9510     Op = Op.getOperand(0);
9511   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9512     return SDValue();
9513
9514   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9515   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9516   // The canonical VMOV for a zero vector uses a 32-bit element size.
9517   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9518   unsigned EltBits;
9519   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9520     EltSize = 8;
9521   EVT VT = N->getValueType(0);
9522   if (EltSize > VT.getVectorElementType().getSizeInBits())
9523     return SDValue();
9524
9525   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9526 }
9527
9528 static SDValue PerformLOADCombine(SDNode *N,
9529                                   TargetLowering::DAGCombinerInfo &DCI) {
9530   EVT VT = N->getValueType(0);
9531
9532   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9533   if (ISD::isNormalLoad(N) && VT.isVector() &&
9534       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9535     return CombineBaseUpdate(N, DCI);
9536
9537   return SDValue();
9538 }
9539
9540 /// PerformSTORECombine - Target-specific dag combine xforms for
9541 /// ISD::STORE.
9542 static SDValue PerformSTORECombine(SDNode *N,
9543                                    TargetLowering::DAGCombinerInfo &DCI) {
9544   StoreSDNode *St = cast<StoreSDNode>(N);
9545   if (St->isVolatile())
9546     return SDValue();
9547
9548   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9549   // pack all of the elements in one place.  Next, store to memory in fewer
9550   // chunks.
9551   SDValue StVal = St->getValue();
9552   EVT VT = StVal.getValueType();
9553   if (St->isTruncatingStore() && VT.isVector()) {
9554     SelectionDAG &DAG = DCI.DAG;
9555     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9556     EVT StVT = St->getMemoryVT();
9557     unsigned NumElems = VT.getVectorNumElements();
9558     assert(StVT != VT && "Cannot truncate to the same type");
9559     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9560     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9561
9562     // From, To sizes and ElemCount must be pow of two
9563     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9564
9565     // We are going to use the original vector elt for storing.
9566     // Accumulated smaller vector elements must be a multiple of the store size.
9567     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9568
9569     unsigned SizeRatio  = FromEltSz / ToEltSz;
9570     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9571
9572     // Create a type on which we perform the shuffle.
9573     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9574                                      NumElems*SizeRatio);
9575     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9576
9577     SDLoc DL(St);
9578     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9579     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9580     for (unsigned i = 0; i < NumElems; ++i)
9581       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9582                           ? (i + 1) * SizeRatio - 1
9583                           : i * SizeRatio;
9584
9585     // Can't shuffle using an illegal type.
9586     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9587
9588     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9589                                 DAG.getUNDEF(WideVec.getValueType()),
9590                                 ShuffleVec.data());
9591     // At this point all of the data is stored at the bottom of the
9592     // register. We now need to save it to mem.
9593
9594     // Find the largest store unit
9595     MVT StoreType = MVT::i8;
9596     for (MVT Tp : MVT::integer_valuetypes()) {
9597       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9598         StoreType = Tp;
9599     }
9600     // Didn't find a legal store type.
9601     if (!TLI.isTypeLegal(StoreType))
9602       return SDValue();
9603
9604     // Bitcast the original vector into a vector of store-size units
9605     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9606             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9607     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9608     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9609     SmallVector<SDValue, 8> Chains;
9610     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9611                                         TLI.getPointerTy(DAG.getDataLayout()));
9612     SDValue BasePtr = St->getBasePtr();
9613
9614     // Perform one or more big stores into memory.
9615     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9616     for (unsigned I = 0; I < E; I++) {
9617       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9618                                    StoreType, ShuffWide,
9619                                    DAG.getIntPtrConstant(I, DL));
9620       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9621                                 St->getPointerInfo(), St->isVolatile(),
9622                                 St->isNonTemporal(), St->getAlignment());
9623       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9624                             Increment);
9625       Chains.push_back(Ch);
9626     }
9627     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9628   }
9629
9630   if (!ISD::isNormalStore(St))
9631     return SDValue();
9632
9633   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9634   // ARM stores of arguments in the same cache line.
9635   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9636       StVal.getNode()->hasOneUse()) {
9637     SelectionDAG  &DAG = DCI.DAG;
9638     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9639     SDLoc DL(St);
9640     SDValue BasePtr = St->getBasePtr();
9641     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9642                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9643                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9644                                   St->isNonTemporal(), St->getAlignment());
9645
9646     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9647                                     DAG.getConstant(4, DL, MVT::i32));
9648     return DAG.getStore(NewST1.getValue(0), DL,
9649                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9650                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9651                         St->isNonTemporal(),
9652                         std::min(4U, St->getAlignment() / 2));
9653   }
9654
9655   if (StVal.getValueType() == MVT::i64 &&
9656       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9657
9658     // Bitcast an i64 store extracted from a vector to f64.
9659     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9660     SelectionDAG &DAG = DCI.DAG;
9661     SDLoc dl(StVal);
9662     SDValue IntVec = StVal.getOperand(0);
9663     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9664                                    IntVec.getValueType().getVectorNumElements());
9665     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9666     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9667                                  Vec, StVal.getOperand(1));
9668     dl = SDLoc(N);
9669     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9670     // Make the DAGCombiner fold the bitcasts.
9671     DCI.AddToWorklist(Vec.getNode());
9672     DCI.AddToWorklist(ExtElt.getNode());
9673     DCI.AddToWorklist(V.getNode());
9674     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9675                         St->getPointerInfo(), St->isVolatile(),
9676                         St->isNonTemporal(), St->getAlignment(),
9677                         St->getAAInfo());
9678   }
9679
9680   // If this is a legal vector store, try to combine it into a VST1_UPD.
9681   if (ISD::isNormalStore(N) && VT.isVector() &&
9682       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9683     return CombineBaseUpdate(N, DCI);
9684
9685   return SDValue();
9686 }
9687
9688 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9689 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9690 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9691 {
9692   integerPart cN;
9693   integerPart c0 = 0;
9694   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9695        I != E; I++) {
9696     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9697     if (!C)
9698       return false;
9699
9700     bool isExact;
9701     APFloat APF = C->getValueAPF();
9702     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9703         != APFloat::opOK || !isExact)
9704       return false;
9705
9706     c0 = (I == 0) ? cN : c0;
9707     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9708       return false;
9709   }
9710   C = c0;
9711   return true;
9712 }
9713
9714 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9715 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9716 /// when the VMUL has a constant operand that is a power of 2.
9717 ///
9718 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9719 ///  vmul.f32        d16, d17, d16
9720 ///  vcvt.s32.f32    d16, d16
9721 /// becomes:
9722 ///  vcvt.s32.f32    d16, d16, #3
9723 static SDValue PerformVCVTCombine(SDNode *N,
9724                                   TargetLowering::DAGCombinerInfo &DCI,
9725                                   const ARMSubtarget *Subtarget) {
9726   SelectionDAG &DAG = DCI.DAG;
9727   SDValue Op = N->getOperand(0);
9728
9729   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9730       Op.getOpcode() != ISD::FMUL)
9731     return SDValue();
9732
9733   uint64_t C;
9734   SDValue N0 = Op->getOperand(0);
9735   SDValue ConstVec = Op->getOperand(1);
9736   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9737
9738   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9739       !isConstVecPow2(ConstVec, isSigned, C))
9740     return SDValue();
9741
9742   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9743   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9744   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9745   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9746       NumLanes > 4) {
9747     // These instructions only exist converting from f32 to i32. We can handle
9748     // smaller integers by generating an extra truncate, but larger ones would
9749     // be lossy. We also can't handle more then 4 lanes, since these intructions
9750     // only support v2i32/v4i32 types.
9751     return SDValue();
9752   }
9753
9754   SDLoc dl(N);
9755   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9756     Intrinsic::arm_neon_vcvtfp2fxu;
9757   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9758                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9759                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9760                                  N0,
9761                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9762
9763   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9764     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9765
9766   return FixConv;
9767 }
9768
9769 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9770 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9771 /// when the VDIV has a constant operand that is a power of 2.
9772 ///
9773 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9774 ///  vcvt.f32.s32    d16, d16
9775 ///  vdiv.f32        d16, d17, d16
9776 /// becomes:
9777 ///  vcvt.f32.s32    d16, d16, #3
9778 static SDValue PerformVDIVCombine(SDNode *N,
9779                                   TargetLowering::DAGCombinerInfo &DCI,
9780                                   const ARMSubtarget *Subtarget) {
9781   SelectionDAG &DAG = DCI.DAG;
9782   SDValue Op = N->getOperand(0);
9783   unsigned OpOpcode = Op.getNode()->getOpcode();
9784
9785   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9786       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9787     return SDValue();
9788
9789   uint64_t C;
9790   SDValue ConstVec = N->getOperand(1);
9791   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9792
9793   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9794       !isConstVecPow2(ConstVec, isSigned, C))
9795     return SDValue();
9796
9797   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9798   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9799   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9800     // These instructions only exist converting from i32 to f32. We can handle
9801     // smaller integers by generating an extra extend, but larger ones would
9802     // be lossy.
9803     return SDValue();
9804   }
9805
9806   SDLoc dl(N);
9807   SDValue ConvInput = Op.getOperand(0);
9808   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9809   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9810     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9811                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9812                             ConvInput);
9813
9814   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9815     Intrinsic::arm_neon_vcvtfxu2fp;
9816   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9817                      Op.getValueType(),
9818                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9819                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9820 }
9821
9822 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9823 /// operand of a vector shift operation, where all the elements of the
9824 /// build_vector must have the same constant integer value.
9825 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9826   // Ignore bit_converts.
9827   while (Op.getOpcode() == ISD::BITCAST)
9828     Op = Op.getOperand(0);
9829   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9830   APInt SplatBits, SplatUndef;
9831   unsigned SplatBitSize;
9832   bool HasAnyUndefs;
9833   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9834                                       HasAnyUndefs, ElementBits) ||
9835       SplatBitSize > ElementBits)
9836     return false;
9837   Cnt = SplatBits.getSExtValue();
9838   return true;
9839 }
9840
9841 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9842 /// operand of a vector shift left operation.  That value must be in the range:
9843 ///   0 <= Value < ElementBits for a left shift; or
9844 ///   0 <= Value <= ElementBits for a long left shift.
9845 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9846   assert(VT.isVector() && "vector shift count is not a vector type");
9847   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9848   if (! getVShiftImm(Op, ElementBits, Cnt))
9849     return false;
9850   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9851 }
9852
9853 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9854 /// operand of a vector shift right operation.  For a shift opcode, the value
9855 /// is positive, but for an intrinsic the value count must be negative. The
9856 /// absolute value must be in the range:
9857 ///   1 <= |Value| <= ElementBits for a right shift; or
9858 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9859 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9860                          int64_t &Cnt) {
9861   assert(VT.isVector() && "vector shift count is not a vector type");
9862   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9863   if (! getVShiftImm(Op, ElementBits, Cnt))
9864     return false;
9865   if (!isIntrinsic)
9866     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9867   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9868     Cnt = -Cnt;
9869     return true;
9870   }
9871   return false;
9872 }
9873
9874 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9875 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9876   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9877   switch (IntNo) {
9878   default:
9879     // Don't do anything for most intrinsics.
9880     break;
9881
9882   case Intrinsic::arm_neon_vabds:
9883     if (!N->getValueType(0).isInteger())
9884       return SDValue();
9885     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9886                        N->getOperand(1), N->getOperand(2));
9887   case Intrinsic::arm_neon_vabdu:
9888     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9889                        N->getOperand(1), N->getOperand(2));
9890
9891   // Vector shifts: check for immediate versions and lower them.
9892   // Note: This is done during DAG combining instead of DAG legalizing because
9893   // the build_vectors for 64-bit vector element shift counts are generally
9894   // not legal, and it is hard to see their values after they get legalized to
9895   // loads from a constant pool.
9896   case Intrinsic::arm_neon_vshifts:
9897   case Intrinsic::arm_neon_vshiftu:
9898   case Intrinsic::arm_neon_vrshifts:
9899   case Intrinsic::arm_neon_vrshiftu:
9900   case Intrinsic::arm_neon_vrshiftn:
9901   case Intrinsic::arm_neon_vqshifts:
9902   case Intrinsic::arm_neon_vqshiftu:
9903   case Intrinsic::arm_neon_vqshiftsu:
9904   case Intrinsic::arm_neon_vqshiftns:
9905   case Intrinsic::arm_neon_vqshiftnu:
9906   case Intrinsic::arm_neon_vqshiftnsu:
9907   case Intrinsic::arm_neon_vqrshiftns:
9908   case Intrinsic::arm_neon_vqrshiftnu:
9909   case Intrinsic::arm_neon_vqrshiftnsu: {
9910     EVT VT = N->getOperand(1).getValueType();
9911     int64_t Cnt;
9912     unsigned VShiftOpc = 0;
9913
9914     switch (IntNo) {
9915     case Intrinsic::arm_neon_vshifts:
9916     case Intrinsic::arm_neon_vshiftu:
9917       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9918         VShiftOpc = ARMISD::VSHL;
9919         break;
9920       }
9921       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9922         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9923                      ARMISD::VSHRs : ARMISD::VSHRu);
9924         break;
9925       }
9926       return SDValue();
9927
9928     case Intrinsic::arm_neon_vrshifts:
9929     case Intrinsic::arm_neon_vrshiftu:
9930       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9931         break;
9932       return SDValue();
9933
9934     case Intrinsic::arm_neon_vqshifts:
9935     case Intrinsic::arm_neon_vqshiftu:
9936       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9937         break;
9938       return SDValue();
9939
9940     case Intrinsic::arm_neon_vqshiftsu:
9941       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9942         break;
9943       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9944
9945     case Intrinsic::arm_neon_vrshiftn:
9946     case Intrinsic::arm_neon_vqshiftns:
9947     case Intrinsic::arm_neon_vqshiftnu:
9948     case Intrinsic::arm_neon_vqshiftnsu:
9949     case Intrinsic::arm_neon_vqrshiftns:
9950     case Intrinsic::arm_neon_vqrshiftnu:
9951     case Intrinsic::arm_neon_vqrshiftnsu:
9952       // Narrowing shifts require an immediate right shift.
9953       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9954         break;
9955       llvm_unreachable("invalid shift count for narrowing vector shift "
9956                        "intrinsic");
9957
9958     default:
9959       llvm_unreachable("unhandled vector shift");
9960     }
9961
9962     switch (IntNo) {
9963     case Intrinsic::arm_neon_vshifts:
9964     case Intrinsic::arm_neon_vshiftu:
9965       // Opcode already set above.
9966       break;
9967     case Intrinsic::arm_neon_vrshifts:
9968       VShiftOpc = ARMISD::VRSHRs; break;
9969     case Intrinsic::arm_neon_vrshiftu:
9970       VShiftOpc = ARMISD::VRSHRu; break;
9971     case Intrinsic::arm_neon_vrshiftn:
9972       VShiftOpc = ARMISD::VRSHRN; break;
9973     case Intrinsic::arm_neon_vqshifts:
9974       VShiftOpc = ARMISD::VQSHLs; break;
9975     case Intrinsic::arm_neon_vqshiftu:
9976       VShiftOpc = ARMISD::VQSHLu; break;
9977     case Intrinsic::arm_neon_vqshiftsu:
9978       VShiftOpc = ARMISD::VQSHLsu; break;
9979     case Intrinsic::arm_neon_vqshiftns:
9980       VShiftOpc = ARMISD::VQSHRNs; break;
9981     case Intrinsic::arm_neon_vqshiftnu:
9982       VShiftOpc = ARMISD::VQSHRNu; break;
9983     case Intrinsic::arm_neon_vqshiftnsu:
9984       VShiftOpc = ARMISD::VQSHRNsu; break;
9985     case Intrinsic::arm_neon_vqrshiftns:
9986       VShiftOpc = ARMISD::VQRSHRNs; break;
9987     case Intrinsic::arm_neon_vqrshiftnu:
9988       VShiftOpc = ARMISD::VQRSHRNu; break;
9989     case Intrinsic::arm_neon_vqrshiftnsu:
9990       VShiftOpc = ARMISD::VQRSHRNsu; break;
9991     }
9992
9993     SDLoc dl(N);
9994     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9995                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9996   }
9997
9998   case Intrinsic::arm_neon_vshiftins: {
9999     EVT VT = N->getOperand(1).getValueType();
10000     int64_t Cnt;
10001     unsigned VShiftOpc = 0;
10002
10003     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10004       VShiftOpc = ARMISD::VSLI;
10005     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10006       VShiftOpc = ARMISD::VSRI;
10007     else {
10008       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10009     }
10010
10011     SDLoc dl(N);
10012     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10013                        N->getOperand(1), N->getOperand(2),
10014                        DAG.getConstant(Cnt, dl, MVT::i32));
10015   }
10016
10017   case Intrinsic::arm_neon_vqrshifts:
10018   case Intrinsic::arm_neon_vqrshiftu:
10019     // No immediate versions of these to check for.
10020     break;
10021   }
10022
10023   return SDValue();
10024 }
10025
10026 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10027 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10028 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10029 /// vector element shift counts are generally not legal, and it is hard to see
10030 /// their values after they get legalized to loads from a constant pool.
10031 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10032                                    const ARMSubtarget *ST) {
10033   EVT VT = N->getValueType(0);
10034   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10035     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10036     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10037     SDValue N1 = N->getOperand(1);
10038     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10039       SDValue N0 = N->getOperand(0);
10040       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10041           DAG.MaskedValueIsZero(N0.getOperand(0),
10042                                 APInt::getHighBitsSet(32, 16)))
10043         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10044     }
10045   }
10046
10047   // Nothing to be done for scalar shifts.
10048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10049   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10050     return SDValue();
10051
10052   assert(ST->hasNEON() && "unexpected vector shift");
10053   int64_t Cnt;
10054
10055   switch (N->getOpcode()) {
10056   default: llvm_unreachable("unexpected shift opcode");
10057
10058   case ISD::SHL:
10059     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10060       SDLoc dl(N);
10061       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10062                          DAG.getConstant(Cnt, dl, MVT::i32));
10063     }
10064     break;
10065
10066   case ISD::SRA:
10067   case ISD::SRL:
10068     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10069       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10070                             ARMISD::VSHRs : ARMISD::VSHRu);
10071       SDLoc dl(N);
10072       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10073                          DAG.getConstant(Cnt, dl, MVT::i32));
10074     }
10075   }
10076   return SDValue();
10077 }
10078
10079 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10080 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10081 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10082                                     const ARMSubtarget *ST) {
10083   SDValue N0 = N->getOperand(0);
10084
10085   // Check for sign- and zero-extensions of vector extract operations of 8-
10086   // and 16-bit vector elements.  NEON supports these directly.  They are
10087   // handled during DAG combining because type legalization will promote them
10088   // to 32-bit types and it is messy to recognize the operations after that.
10089   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10090     SDValue Vec = N0.getOperand(0);
10091     SDValue Lane = N0.getOperand(1);
10092     EVT VT = N->getValueType(0);
10093     EVT EltVT = N0.getValueType();
10094     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10095
10096     if (VT == MVT::i32 &&
10097         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10098         TLI.isTypeLegal(Vec.getValueType()) &&
10099         isa<ConstantSDNode>(Lane)) {
10100
10101       unsigned Opc = 0;
10102       switch (N->getOpcode()) {
10103       default: llvm_unreachable("unexpected opcode");
10104       case ISD::SIGN_EXTEND:
10105         Opc = ARMISD::VGETLANEs;
10106         break;
10107       case ISD::ZERO_EXTEND:
10108       case ISD::ANY_EXTEND:
10109         Opc = ARMISD::VGETLANEu;
10110         break;
10111       }
10112       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10113     }
10114   }
10115
10116   return SDValue();
10117 }
10118
10119 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10120 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10121 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10122                                        const ARMSubtarget *ST) {
10123   // If the target supports NEON, try to use vmax/vmin instructions for f32
10124   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10125   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10126   // a NaN; only do the transformation when it matches that behavior.
10127
10128   // For now only do this when using NEON for FP operations; if using VFP, it
10129   // is not obvious that the benefit outweighs the cost of switching to the
10130   // NEON pipeline.
10131   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10132       N->getValueType(0) != MVT::f32)
10133     return SDValue();
10134
10135   SDValue CondLHS = N->getOperand(0);
10136   SDValue CondRHS = N->getOperand(1);
10137   SDValue LHS = N->getOperand(2);
10138   SDValue RHS = N->getOperand(3);
10139   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10140
10141   unsigned Opcode = 0;
10142   bool IsReversed;
10143   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10144     IsReversed = false; // x CC y ? x : y
10145   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10146     IsReversed = true ; // x CC y ? y : x
10147   } else {
10148     return SDValue();
10149   }
10150
10151   bool IsUnordered;
10152   switch (CC) {
10153   default: break;
10154   case ISD::SETOLT:
10155   case ISD::SETOLE:
10156   case ISD::SETLT:
10157   case ISD::SETLE:
10158   case ISD::SETULT:
10159   case ISD::SETULE:
10160     // If LHS is NaN, an ordered comparison will be false and the result will
10161     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10162     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10163     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10164     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10165       break;
10166     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10167     // will return -0, so vmin can only be used for unsafe math or if one of
10168     // the operands is known to be nonzero.
10169     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10170         !DAG.getTarget().Options.UnsafeFPMath &&
10171         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10172       break;
10173     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10174     break;
10175
10176   case ISD::SETOGT:
10177   case ISD::SETOGE:
10178   case ISD::SETGT:
10179   case ISD::SETGE:
10180   case ISD::SETUGT:
10181   case ISD::SETUGE:
10182     // If LHS is NaN, an ordered comparison will be false and the result will
10183     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10184     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10185     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10186     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10187       break;
10188     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10189     // will return +0, so vmax can only be used for unsafe math or if one of
10190     // the operands is known to be nonzero.
10191     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10192         !DAG.getTarget().Options.UnsafeFPMath &&
10193         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10194       break;
10195     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10196     break;
10197   }
10198
10199   if (!Opcode)
10200     return SDValue();
10201   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10202 }
10203
10204 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10205 SDValue
10206 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10207   SDValue Cmp = N->getOperand(4);
10208   if (Cmp.getOpcode() != ARMISD::CMPZ)
10209     // Only looking at EQ and NE cases.
10210     return SDValue();
10211
10212   EVT VT = N->getValueType(0);
10213   SDLoc dl(N);
10214   SDValue LHS = Cmp.getOperand(0);
10215   SDValue RHS = Cmp.getOperand(1);
10216   SDValue FalseVal = N->getOperand(0);
10217   SDValue TrueVal = N->getOperand(1);
10218   SDValue ARMcc = N->getOperand(2);
10219   ARMCC::CondCodes CC =
10220     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10221
10222   // Simplify
10223   //   mov     r1, r0
10224   //   cmp     r1, x
10225   //   mov     r0, y
10226   //   moveq   r0, x
10227   // to
10228   //   cmp     r0, x
10229   //   movne   r0, y
10230   //
10231   //   mov     r1, r0
10232   //   cmp     r1, x
10233   //   mov     r0, x
10234   //   movne   r0, y
10235   // to
10236   //   cmp     r0, x
10237   //   movne   r0, y
10238   /// FIXME: Turn this into a target neutral optimization?
10239   SDValue Res;
10240   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10241     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10242                       N->getOperand(3), Cmp);
10243   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10244     SDValue ARMcc;
10245     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10246     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10247                       N->getOperand(3), NewCmp);
10248   }
10249
10250   if (Res.getNode()) {
10251     APInt KnownZero, KnownOne;
10252     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10253     // Capture demanded bits information that would be otherwise lost.
10254     if (KnownZero == 0xfffffffe)
10255       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10256                         DAG.getValueType(MVT::i1));
10257     else if (KnownZero == 0xffffff00)
10258       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10259                         DAG.getValueType(MVT::i8));
10260     else if (KnownZero == 0xffff0000)
10261       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10262                         DAG.getValueType(MVT::i16));
10263   }
10264
10265   return Res;
10266 }
10267
10268 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10269                                              DAGCombinerInfo &DCI) const {
10270   switch (N->getOpcode()) {
10271   default: break;
10272   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10273   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10274   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10275   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10276   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10277   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10278   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10279   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10280   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10281   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10282   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10283   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10284   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10285   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10286   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10287   case ISD::FP_TO_SINT:
10288   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10289   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10290   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10291   case ISD::SHL:
10292   case ISD::SRA:
10293   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10294   case ISD::SIGN_EXTEND:
10295   case ISD::ZERO_EXTEND:
10296   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10297   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10298   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10299   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10300   case ARMISD::VLD2DUP:
10301   case ARMISD::VLD3DUP:
10302   case ARMISD::VLD4DUP:
10303     return PerformVLDCombine(N, DCI);
10304   case ARMISD::BUILD_VECTOR:
10305     return PerformARMBUILD_VECTORCombine(N, DCI);
10306   case ISD::INTRINSIC_VOID:
10307   case ISD::INTRINSIC_W_CHAIN:
10308     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10309     case Intrinsic::arm_neon_vld1:
10310     case Intrinsic::arm_neon_vld2:
10311     case Intrinsic::arm_neon_vld3:
10312     case Intrinsic::arm_neon_vld4:
10313     case Intrinsic::arm_neon_vld2lane:
10314     case Intrinsic::arm_neon_vld3lane:
10315     case Intrinsic::arm_neon_vld4lane:
10316     case Intrinsic::arm_neon_vst1:
10317     case Intrinsic::arm_neon_vst2:
10318     case Intrinsic::arm_neon_vst3:
10319     case Intrinsic::arm_neon_vst4:
10320     case Intrinsic::arm_neon_vst2lane:
10321     case Intrinsic::arm_neon_vst3lane:
10322     case Intrinsic::arm_neon_vst4lane:
10323       return PerformVLDCombine(N, DCI);
10324     default: break;
10325     }
10326     break;
10327   }
10328   return SDValue();
10329 }
10330
10331 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10332                                                           EVT VT) const {
10333   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10334 }
10335
10336 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10337                                                        unsigned,
10338                                                        unsigned,
10339                                                        bool *Fast) const {
10340   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10341   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10342
10343   switch (VT.getSimpleVT().SimpleTy) {
10344   default:
10345     return false;
10346   case MVT::i8:
10347   case MVT::i16:
10348   case MVT::i32: {
10349     // Unaligned access can use (for example) LRDB, LRDH, LDR
10350     if (AllowsUnaligned) {
10351       if (Fast)
10352         *Fast = Subtarget->hasV7Ops();
10353       return true;
10354     }
10355     return false;
10356   }
10357   case MVT::f64:
10358   case MVT::v2f64: {
10359     // For any little-endian targets with neon, we can support unaligned ld/st
10360     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10361     // A big-endian target may also explicitly support unaligned accesses
10362     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10363       if (Fast)
10364         *Fast = true;
10365       return true;
10366     }
10367     return false;
10368   }
10369   }
10370 }
10371
10372 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10373                        unsigned AlignCheck) {
10374   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10375           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10376 }
10377
10378 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10379                                            unsigned DstAlign, unsigned SrcAlign,
10380                                            bool IsMemset, bool ZeroMemset,
10381                                            bool MemcpyStrSrc,
10382                                            MachineFunction &MF) const {
10383   const Function *F = MF.getFunction();
10384
10385   // See if we can use NEON instructions for this...
10386   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10387       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10388     bool Fast;
10389     if (Size >= 16 &&
10390         (memOpAlign(SrcAlign, DstAlign, 16) ||
10391          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10392       return MVT::v2f64;
10393     } else if (Size >= 8 &&
10394                (memOpAlign(SrcAlign, DstAlign, 8) ||
10395                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10396                  Fast))) {
10397       return MVT::f64;
10398     }
10399   }
10400
10401   // Lowering to i32/i16 if the size permits.
10402   if (Size >= 4)
10403     return MVT::i32;
10404   else if (Size >= 2)
10405     return MVT::i16;
10406
10407   // Let the target-independent logic figure it out.
10408   return MVT::Other;
10409 }
10410
10411 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10412   if (Val.getOpcode() != ISD::LOAD)
10413     return false;
10414
10415   EVT VT1 = Val.getValueType();
10416   if (!VT1.isSimple() || !VT1.isInteger() ||
10417       !VT2.isSimple() || !VT2.isInteger())
10418     return false;
10419
10420   switch (VT1.getSimpleVT().SimpleTy) {
10421   default: break;
10422   case MVT::i1:
10423   case MVT::i8:
10424   case MVT::i16:
10425     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10426     return true;
10427   }
10428
10429   return false;
10430 }
10431
10432 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10433   EVT VT = ExtVal.getValueType();
10434
10435   if (!isTypeLegal(VT))
10436     return false;
10437
10438   // Don't create a loadext if we can fold the extension into a wide/long
10439   // instruction.
10440   // If there's more than one user instruction, the loadext is desirable no
10441   // matter what.  There can be two uses by the same instruction.
10442   if (ExtVal->use_empty() ||
10443       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10444     return true;
10445
10446   SDNode *U = *ExtVal->use_begin();
10447   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10448        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10449     return false;
10450
10451   return true;
10452 }
10453
10454 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10455   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10456     return false;
10457
10458   if (!isTypeLegal(EVT::getEVT(Ty1)))
10459     return false;
10460
10461   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10462
10463   // Assuming the caller doesn't have a zeroext or signext return parameter,
10464   // truncation all the way down to i1 is valid.
10465   return true;
10466 }
10467
10468
10469 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10470   if (V < 0)
10471     return false;
10472
10473   unsigned Scale = 1;
10474   switch (VT.getSimpleVT().SimpleTy) {
10475   default: return false;
10476   case MVT::i1:
10477   case MVT::i8:
10478     // Scale == 1;
10479     break;
10480   case MVT::i16:
10481     // Scale == 2;
10482     Scale = 2;
10483     break;
10484   case MVT::i32:
10485     // Scale == 4;
10486     Scale = 4;
10487     break;
10488   }
10489
10490   if ((V & (Scale - 1)) != 0)
10491     return false;
10492   V /= Scale;
10493   return V == (V & ((1LL << 5) - 1));
10494 }
10495
10496 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10497                                       const ARMSubtarget *Subtarget) {
10498   bool isNeg = false;
10499   if (V < 0) {
10500     isNeg = true;
10501     V = - V;
10502   }
10503
10504   switch (VT.getSimpleVT().SimpleTy) {
10505   default: return false;
10506   case MVT::i1:
10507   case MVT::i8:
10508   case MVT::i16:
10509   case MVT::i32:
10510     // + imm12 or - imm8
10511     if (isNeg)
10512       return V == (V & ((1LL << 8) - 1));
10513     return V == (V & ((1LL << 12) - 1));
10514   case MVT::f32:
10515   case MVT::f64:
10516     // Same as ARM mode. FIXME: NEON?
10517     if (!Subtarget->hasVFP2())
10518       return false;
10519     if ((V & 3) != 0)
10520       return false;
10521     V >>= 2;
10522     return V == (V & ((1LL << 8) - 1));
10523   }
10524 }
10525
10526 /// isLegalAddressImmediate - Return true if the integer value can be used
10527 /// as the offset of the target addressing mode for load / store of the
10528 /// given type.
10529 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10530                                     const ARMSubtarget *Subtarget) {
10531   if (V == 0)
10532     return true;
10533
10534   if (!VT.isSimple())
10535     return false;
10536
10537   if (Subtarget->isThumb1Only())
10538     return isLegalT1AddressImmediate(V, VT);
10539   else if (Subtarget->isThumb2())
10540     return isLegalT2AddressImmediate(V, VT, Subtarget);
10541
10542   // ARM mode.
10543   if (V < 0)
10544     V = - V;
10545   switch (VT.getSimpleVT().SimpleTy) {
10546   default: return false;
10547   case MVT::i1:
10548   case MVT::i8:
10549   case MVT::i32:
10550     // +- imm12
10551     return V == (V & ((1LL << 12) - 1));
10552   case MVT::i16:
10553     // +- imm8
10554     return V == (V & ((1LL << 8) - 1));
10555   case MVT::f32:
10556   case MVT::f64:
10557     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10558       return false;
10559     if ((V & 3) != 0)
10560       return false;
10561     V >>= 2;
10562     return V == (V & ((1LL << 8) - 1));
10563   }
10564 }
10565
10566 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10567                                                       EVT VT) const {
10568   int Scale = AM.Scale;
10569   if (Scale < 0)
10570     return false;
10571
10572   switch (VT.getSimpleVT().SimpleTy) {
10573   default: return false;
10574   case MVT::i1:
10575   case MVT::i8:
10576   case MVT::i16:
10577   case MVT::i32:
10578     if (Scale == 1)
10579       return true;
10580     // r + r << imm
10581     Scale = Scale & ~1;
10582     return Scale == 2 || Scale == 4 || Scale == 8;
10583   case MVT::i64:
10584     // r + r
10585     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10586       return true;
10587     return false;
10588   case MVT::isVoid:
10589     // Note, we allow "void" uses (basically, uses that aren't loads or
10590     // stores), because arm allows folding a scale into many arithmetic
10591     // operations.  This should be made more precise and revisited later.
10592
10593     // Allow r << imm, but the imm has to be a multiple of two.
10594     if (Scale & 1) return false;
10595     return isPowerOf2_32(Scale);
10596   }
10597 }
10598
10599 /// isLegalAddressingMode - Return true if the addressing mode represented
10600 /// by AM is legal for this target, for a load/store of the specified type.
10601 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10602                                               const AddrMode &AM, Type *Ty,
10603                                               unsigned AS) const {
10604   EVT VT = getValueType(DL, Ty, true);
10605   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10606     return false;
10607
10608   // Can never fold addr of global into load/store.
10609   if (AM.BaseGV)
10610     return false;
10611
10612   switch (AM.Scale) {
10613   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10614     break;
10615   case 1:
10616     if (Subtarget->isThumb1Only())
10617       return false;
10618     // FALL THROUGH.
10619   default:
10620     // ARM doesn't support any R+R*scale+imm addr modes.
10621     if (AM.BaseOffs)
10622       return false;
10623
10624     if (!VT.isSimple())
10625       return false;
10626
10627     if (Subtarget->isThumb2())
10628       return isLegalT2ScaledAddressingMode(AM, VT);
10629
10630     int Scale = AM.Scale;
10631     switch (VT.getSimpleVT().SimpleTy) {
10632     default: return false;
10633     case MVT::i1:
10634     case MVT::i8:
10635     case MVT::i32:
10636       if (Scale < 0) Scale = -Scale;
10637       if (Scale == 1)
10638         return true;
10639       // r + r << imm
10640       return isPowerOf2_32(Scale & ~1);
10641     case MVT::i16:
10642     case MVT::i64:
10643       // r + r
10644       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10645         return true;
10646       return false;
10647
10648     case MVT::isVoid:
10649       // Note, we allow "void" uses (basically, uses that aren't loads or
10650       // stores), because arm allows folding a scale into many arithmetic
10651       // operations.  This should be made more precise and revisited later.
10652
10653       // Allow r << imm, but the imm has to be a multiple of two.
10654       if (Scale & 1) return false;
10655       return isPowerOf2_32(Scale);
10656     }
10657   }
10658   return true;
10659 }
10660
10661 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10662 /// icmp immediate, that is the target has icmp instructions which can compare
10663 /// a register against the immediate without having to materialize the
10664 /// immediate into a register.
10665 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10666   // Thumb2 and ARM modes can use cmn for negative immediates.
10667   if (!Subtarget->isThumb())
10668     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10669   if (Subtarget->isThumb2())
10670     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10671   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10672   return Imm >= 0 && Imm <= 255;
10673 }
10674
10675 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10676 /// *or sub* immediate, that is the target has add or sub instructions which can
10677 /// add a register with the immediate without having to materialize the
10678 /// immediate into a register.
10679 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10680   // Same encoding for add/sub, just flip the sign.
10681   int64_t AbsImm = std::abs(Imm);
10682   if (!Subtarget->isThumb())
10683     return ARM_AM::getSOImmVal(AbsImm) != -1;
10684   if (Subtarget->isThumb2())
10685     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10686   // Thumb1 only has 8-bit unsigned immediate.
10687   return AbsImm >= 0 && AbsImm <= 255;
10688 }
10689
10690 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10691                                       bool isSEXTLoad, SDValue &Base,
10692                                       SDValue &Offset, bool &isInc,
10693                                       SelectionDAG &DAG) {
10694   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10695     return false;
10696
10697   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10698     // AddressingMode 3
10699     Base = Ptr->getOperand(0);
10700     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10701       int RHSC = (int)RHS->getZExtValue();
10702       if (RHSC < 0 && RHSC > -256) {
10703         assert(Ptr->getOpcode() == ISD::ADD);
10704         isInc = false;
10705         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10706         return true;
10707       }
10708     }
10709     isInc = (Ptr->getOpcode() == ISD::ADD);
10710     Offset = Ptr->getOperand(1);
10711     return true;
10712   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10713     // AddressingMode 2
10714     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10715       int RHSC = (int)RHS->getZExtValue();
10716       if (RHSC < 0 && RHSC > -0x1000) {
10717         assert(Ptr->getOpcode() == ISD::ADD);
10718         isInc = false;
10719         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10720         Base = Ptr->getOperand(0);
10721         return true;
10722       }
10723     }
10724
10725     if (Ptr->getOpcode() == ISD::ADD) {
10726       isInc = true;
10727       ARM_AM::ShiftOpc ShOpcVal=
10728         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10729       if (ShOpcVal != ARM_AM::no_shift) {
10730         Base = Ptr->getOperand(1);
10731         Offset = Ptr->getOperand(0);
10732       } else {
10733         Base = Ptr->getOperand(0);
10734         Offset = Ptr->getOperand(1);
10735       }
10736       return true;
10737     }
10738
10739     isInc = (Ptr->getOpcode() == ISD::ADD);
10740     Base = Ptr->getOperand(0);
10741     Offset = Ptr->getOperand(1);
10742     return true;
10743   }
10744
10745   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10746   return false;
10747 }
10748
10749 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10750                                      bool isSEXTLoad, SDValue &Base,
10751                                      SDValue &Offset, bool &isInc,
10752                                      SelectionDAG &DAG) {
10753   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10754     return false;
10755
10756   Base = Ptr->getOperand(0);
10757   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10758     int RHSC = (int)RHS->getZExtValue();
10759     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10760       assert(Ptr->getOpcode() == ISD::ADD);
10761       isInc = false;
10762       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10763       return true;
10764     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10765       isInc = Ptr->getOpcode() == ISD::ADD;
10766       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10767       return true;
10768     }
10769   }
10770
10771   return false;
10772 }
10773
10774 /// getPreIndexedAddressParts - returns true by value, base pointer and
10775 /// offset pointer and addressing mode by reference if the node's address
10776 /// can be legally represented as pre-indexed load / store address.
10777 bool
10778 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10779                                              SDValue &Offset,
10780                                              ISD::MemIndexedMode &AM,
10781                                              SelectionDAG &DAG) const {
10782   if (Subtarget->isThumb1Only())
10783     return false;
10784
10785   EVT VT;
10786   SDValue Ptr;
10787   bool isSEXTLoad = false;
10788   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10789     Ptr = LD->getBasePtr();
10790     VT  = LD->getMemoryVT();
10791     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10792   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10793     Ptr = ST->getBasePtr();
10794     VT  = ST->getMemoryVT();
10795   } else
10796     return false;
10797
10798   bool isInc;
10799   bool isLegal = false;
10800   if (Subtarget->isThumb2())
10801     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10802                                        Offset, isInc, DAG);
10803   else
10804     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10805                                         Offset, isInc, DAG);
10806   if (!isLegal)
10807     return false;
10808
10809   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10810   return true;
10811 }
10812
10813 /// getPostIndexedAddressParts - returns true by value, base pointer and
10814 /// offset pointer and addressing mode by reference if this node can be
10815 /// combined with a load / store to form a post-indexed load / store.
10816 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10817                                                    SDValue &Base,
10818                                                    SDValue &Offset,
10819                                                    ISD::MemIndexedMode &AM,
10820                                                    SelectionDAG &DAG) const {
10821   if (Subtarget->isThumb1Only())
10822     return false;
10823
10824   EVT VT;
10825   SDValue Ptr;
10826   bool isSEXTLoad = false;
10827   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10828     VT  = LD->getMemoryVT();
10829     Ptr = LD->getBasePtr();
10830     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10831   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10832     VT  = ST->getMemoryVT();
10833     Ptr = ST->getBasePtr();
10834   } else
10835     return false;
10836
10837   bool isInc;
10838   bool isLegal = false;
10839   if (Subtarget->isThumb2())
10840     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10841                                        isInc, DAG);
10842   else
10843     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10844                                         isInc, DAG);
10845   if (!isLegal)
10846     return false;
10847
10848   if (Ptr != Base) {
10849     // Swap base ptr and offset to catch more post-index load / store when
10850     // it's legal. In Thumb2 mode, offset must be an immediate.
10851     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10852         !Subtarget->isThumb2())
10853       std::swap(Base, Offset);
10854
10855     // Post-indexed load / store update the base pointer.
10856     if (Ptr != Base)
10857       return false;
10858   }
10859
10860   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10861   return true;
10862 }
10863
10864 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10865                                                       APInt &KnownZero,
10866                                                       APInt &KnownOne,
10867                                                       const SelectionDAG &DAG,
10868                                                       unsigned Depth) const {
10869   unsigned BitWidth = KnownOne.getBitWidth();
10870   KnownZero = KnownOne = APInt(BitWidth, 0);
10871   switch (Op.getOpcode()) {
10872   default: break;
10873   case ARMISD::ADDC:
10874   case ARMISD::ADDE:
10875   case ARMISD::SUBC:
10876   case ARMISD::SUBE:
10877     // These nodes' second result is a boolean
10878     if (Op.getResNo() == 0)
10879       break;
10880     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10881     break;
10882   case ARMISD::CMOV: {
10883     // Bits are known zero/one if known on the LHS and RHS.
10884     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10885     if (KnownZero == 0 && KnownOne == 0) return;
10886
10887     APInt KnownZeroRHS, KnownOneRHS;
10888     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10889     KnownZero &= KnownZeroRHS;
10890     KnownOne  &= KnownOneRHS;
10891     return;
10892   }
10893   case ISD::INTRINSIC_W_CHAIN: {
10894     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10895     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10896     switch (IntID) {
10897     default: return;
10898     case Intrinsic::arm_ldaex:
10899     case Intrinsic::arm_ldrex: {
10900       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10901       unsigned MemBits = VT.getScalarType().getSizeInBits();
10902       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10903       return;
10904     }
10905     }
10906   }
10907   }
10908 }
10909
10910 //===----------------------------------------------------------------------===//
10911 //                           ARM Inline Assembly Support
10912 //===----------------------------------------------------------------------===//
10913
10914 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10915   // Looking for "rev" which is V6+.
10916   if (!Subtarget->hasV6Ops())
10917     return false;
10918
10919   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10920   std::string AsmStr = IA->getAsmString();
10921   SmallVector<StringRef, 4> AsmPieces;
10922   SplitString(AsmStr, AsmPieces, ";\n");
10923
10924   switch (AsmPieces.size()) {
10925   default: return false;
10926   case 1:
10927     AsmStr = AsmPieces[0];
10928     AsmPieces.clear();
10929     SplitString(AsmStr, AsmPieces, " \t,");
10930
10931     // rev $0, $1
10932     if (AsmPieces.size() == 3 &&
10933         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10934         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10935       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10936       if (Ty && Ty->getBitWidth() == 32)
10937         return IntrinsicLowering::LowerToByteSwap(CI);
10938     }
10939     break;
10940   }
10941
10942   return false;
10943 }
10944
10945 /// getConstraintType - Given a constraint letter, return the type of
10946 /// constraint it is for this target.
10947 ARMTargetLowering::ConstraintType
10948 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10949   if (Constraint.size() == 1) {
10950     switch (Constraint[0]) {
10951     default:  break;
10952     case 'l': return C_RegisterClass;
10953     case 'w': return C_RegisterClass;
10954     case 'h': return C_RegisterClass;
10955     case 'x': return C_RegisterClass;
10956     case 't': return C_RegisterClass;
10957     case 'j': return C_Other; // Constant for movw.
10958       // An address with a single base register. Due to the way we
10959       // currently handle addresses it is the same as an 'r' memory constraint.
10960     case 'Q': return C_Memory;
10961     }
10962   } else if (Constraint.size() == 2) {
10963     switch (Constraint[0]) {
10964     default: break;
10965     // All 'U+' constraints are addresses.
10966     case 'U': return C_Memory;
10967     }
10968   }
10969   return TargetLowering::getConstraintType(Constraint);
10970 }
10971
10972 /// Examine constraint type and operand type and determine a weight value.
10973 /// This object must already have been set up with the operand type
10974 /// and the current alternative constraint selected.
10975 TargetLowering::ConstraintWeight
10976 ARMTargetLowering::getSingleConstraintMatchWeight(
10977     AsmOperandInfo &info, const char *constraint) const {
10978   ConstraintWeight weight = CW_Invalid;
10979   Value *CallOperandVal = info.CallOperandVal;
10980     // If we don't have a value, we can't do a match,
10981     // but allow it at the lowest weight.
10982   if (!CallOperandVal)
10983     return CW_Default;
10984   Type *type = CallOperandVal->getType();
10985   // Look at the constraint type.
10986   switch (*constraint) {
10987   default:
10988     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10989     break;
10990   case 'l':
10991     if (type->isIntegerTy()) {
10992       if (Subtarget->isThumb())
10993         weight = CW_SpecificReg;
10994       else
10995         weight = CW_Register;
10996     }
10997     break;
10998   case 'w':
10999     if (type->isFloatingPointTy())
11000       weight = CW_Register;
11001     break;
11002   }
11003   return weight;
11004 }
11005
11006 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11007 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11008     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11009   if (Constraint.size() == 1) {
11010     // GCC ARM Constraint Letters
11011     switch (Constraint[0]) {
11012     case 'l': // Low regs or general regs.
11013       if (Subtarget->isThumb())
11014         return RCPair(0U, &ARM::tGPRRegClass);
11015       return RCPair(0U, &ARM::GPRRegClass);
11016     case 'h': // High regs or no regs.
11017       if (Subtarget->isThumb())
11018         return RCPair(0U, &ARM::hGPRRegClass);
11019       break;
11020     case 'r':
11021       if (Subtarget->isThumb1Only())
11022         return RCPair(0U, &ARM::tGPRRegClass);
11023       return RCPair(0U, &ARM::GPRRegClass);
11024     case 'w':
11025       if (VT == MVT::Other)
11026         break;
11027       if (VT == MVT::f32)
11028         return RCPair(0U, &ARM::SPRRegClass);
11029       if (VT.getSizeInBits() == 64)
11030         return RCPair(0U, &ARM::DPRRegClass);
11031       if (VT.getSizeInBits() == 128)
11032         return RCPair(0U, &ARM::QPRRegClass);
11033       break;
11034     case 'x':
11035       if (VT == MVT::Other)
11036         break;
11037       if (VT == MVT::f32)
11038         return RCPair(0U, &ARM::SPR_8RegClass);
11039       if (VT.getSizeInBits() == 64)
11040         return RCPair(0U, &ARM::DPR_8RegClass);
11041       if (VT.getSizeInBits() == 128)
11042         return RCPair(0U, &ARM::QPR_8RegClass);
11043       break;
11044     case 't':
11045       if (VT == MVT::f32)
11046         return RCPair(0U, &ARM::SPRRegClass);
11047       break;
11048     }
11049   }
11050   if (StringRef("{cc}").equals_lower(Constraint))
11051     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11052
11053   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11054 }
11055
11056 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11057 /// vector.  If it is invalid, don't add anything to Ops.
11058 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11059                                                      std::string &Constraint,
11060                                                      std::vector<SDValue>&Ops,
11061                                                      SelectionDAG &DAG) const {
11062   SDValue Result;
11063
11064   // Currently only support length 1 constraints.
11065   if (Constraint.length() != 1) return;
11066
11067   char ConstraintLetter = Constraint[0];
11068   switch (ConstraintLetter) {
11069   default: break;
11070   case 'j':
11071   case 'I': case 'J': case 'K': case 'L':
11072   case 'M': case 'N': case 'O':
11073     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11074     if (!C)
11075       return;
11076
11077     int64_t CVal64 = C->getSExtValue();
11078     int CVal = (int) CVal64;
11079     // None of these constraints allow values larger than 32 bits.  Check
11080     // that the value fits in an int.
11081     if (CVal != CVal64)
11082       return;
11083
11084     switch (ConstraintLetter) {
11085       case 'j':
11086         // Constant suitable for movw, must be between 0 and
11087         // 65535.
11088         if (Subtarget->hasV6T2Ops())
11089           if (CVal >= 0 && CVal <= 65535)
11090             break;
11091         return;
11092       case 'I':
11093         if (Subtarget->isThumb1Only()) {
11094           // This must be a constant between 0 and 255, for ADD
11095           // immediates.
11096           if (CVal >= 0 && CVal <= 255)
11097             break;
11098         } else if (Subtarget->isThumb2()) {
11099           // A constant that can be used as an immediate value in a
11100           // data-processing instruction.
11101           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11102             break;
11103         } else {
11104           // A constant that can be used as an immediate value in a
11105           // data-processing instruction.
11106           if (ARM_AM::getSOImmVal(CVal) != -1)
11107             break;
11108         }
11109         return;
11110
11111       case 'J':
11112         if (Subtarget->isThumb()) {  // FIXME thumb2
11113           // This must be a constant between -255 and -1, for negated ADD
11114           // immediates. This can be used in GCC with an "n" modifier that
11115           // prints the negated value, for use with SUB instructions. It is
11116           // not useful otherwise but is implemented for compatibility.
11117           if (CVal >= -255 && CVal <= -1)
11118             break;
11119         } else {
11120           // This must be a constant between -4095 and 4095. It is not clear
11121           // what this constraint is intended for. Implemented for
11122           // compatibility with GCC.
11123           if (CVal >= -4095 && CVal <= 4095)
11124             break;
11125         }
11126         return;
11127
11128       case 'K':
11129         if (Subtarget->isThumb1Only()) {
11130           // A 32-bit value where only one byte has a nonzero value. Exclude
11131           // zero to match GCC. This constraint is used by GCC internally for
11132           // constants that can be loaded with a move/shift combination.
11133           // It is not useful otherwise but is implemented for compatibility.
11134           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11135             break;
11136         } else if (Subtarget->isThumb2()) {
11137           // A constant whose bitwise inverse can be used as an immediate
11138           // value in a data-processing instruction. This can be used in GCC
11139           // with a "B" modifier that prints the inverted value, for use with
11140           // BIC and MVN instructions. It is not useful otherwise but is
11141           // implemented for compatibility.
11142           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11143             break;
11144         } else {
11145           // A constant whose bitwise inverse can be used as an immediate
11146           // value in a data-processing instruction. This can be used in GCC
11147           // with a "B" modifier that prints the inverted value, for use with
11148           // BIC and MVN instructions. It is not useful otherwise but is
11149           // implemented for compatibility.
11150           if (ARM_AM::getSOImmVal(~CVal) != -1)
11151             break;
11152         }
11153         return;
11154
11155       case 'L':
11156         if (Subtarget->isThumb1Only()) {
11157           // This must be a constant between -7 and 7,
11158           // for 3-operand ADD/SUB immediate instructions.
11159           if (CVal >= -7 && CVal < 7)
11160             break;
11161         } else if (Subtarget->isThumb2()) {
11162           // A constant whose negation can be used as an immediate value in a
11163           // data-processing instruction. This can be used in GCC with an "n"
11164           // modifier that prints the negated value, for use with SUB
11165           // instructions. It is not useful otherwise but is implemented for
11166           // compatibility.
11167           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11168             break;
11169         } else {
11170           // A constant whose negation can be used as an immediate value in a
11171           // data-processing instruction. This can be used in GCC with an "n"
11172           // modifier that prints the negated value, for use with SUB
11173           // instructions. It is not useful otherwise but is implemented for
11174           // compatibility.
11175           if (ARM_AM::getSOImmVal(-CVal) != -1)
11176             break;
11177         }
11178         return;
11179
11180       case 'M':
11181         if (Subtarget->isThumb()) { // FIXME thumb2
11182           // This must be a multiple of 4 between 0 and 1020, for
11183           // ADD sp + immediate.
11184           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11185             break;
11186         } else {
11187           // A power of two or a constant between 0 and 32.  This is used in
11188           // GCC for the shift amount on shifted register operands, but it is
11189           // useful in general for any shift amounts.
11190           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11191             break;
11192         }
11193         return;
11194
11195       case 'N':
11196         if (Subtarget->isThumb()) {  // FIXME thumb2
11197           // This must be a constant between 0 and 31, for shift amounts.
11198           if (CVal >= 0 && CVal <= 31)
11199             break;
11200         }
11201         return;
11202
11203       case 'O':
11204         if (Subtarget->isThumb()) {  // FIXME thumb2
11205           // This must be a multiple of 4 between -508 and 508, for
11206           // ADD/SUB sp = sp + immediate.
11207           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11208             break;
11209         }
11210         return;
11211     }
11212     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11213     break;
11214   }
11215
11216   if (Result.getNode()) {
11217     Ops.push_back(Result);
11218     return;
11219   }
11220   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11221 }
11222
11223 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11224   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11225          "Register-based DivRem lowering only");
11226   unsigned Opcode = Op->getOpcode();
11227   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11228          "Invalid opcode for Div/Rem lowering");
11229   bool isSigned = (Opcode == ISD::SDIVREM);
11230   EVT VT = Op->getValueType(0);
11231   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11232
11233   RTLIB::Libcall LC;
11234   switch (VT.getSimpleVT().SimpleTy) {
11235   default: llvm_unreachable("Unexpected request for libcall!");
11236   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11237   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11238   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11239   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11240   }
11241
11242   SDValue InChain = DAG.getEntryNode();
11243
11244   TargetLowering::ArgListTy Args;
11245   TargetLowering::ArgListEntry Entry;
11246   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11247     EVT ArgVT = Op->getOperand(i).getValueType();
11248     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11249     Entry.Node = Op->getOperand(i);
11250     Entry.Ty = ArgTy;
11251     Entry.isSExt = isSigned;
11252     Entry.isZExt = !isSigned;
11253     Args.push_back(Entry);
11254   }
11255
11256   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11257                                          getPointerTy(DAG.getDataLayout()));
11258
11259   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11260
11261   SDLoc dl(Op);
11262   TargetLowering::CallLoweringInfo CLI(DAG);
11263   CLI.setDebugLoc(dl).setChain(InChain)
11264     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11265     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11266
11267   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11268   return CallInfo.first;
11269 }
11270
11271 SDValue
11272 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11273   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11274   SDLoc DL(Op);
11275
11276   // Get the inputs.
11277   SDValue Chain = Op.getOperand(0);
11278   SDValue Size  = Op.getOperand(1);
11279
11280   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11281                               DAG.getConstant(2, DL, MVT::i32));
11282
11283   SDValue Flag;
11284   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11285   Flag = Chain.getValue(1);
11286
11287   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11288   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11289
11290   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11291   Chain = NewSP.getValue(1);
11292
11293   SDValue Ops[2] = { NewSP, Chain };
11294   return DAG.getMergeValues(Ops, DL);
11295 }
11296
11297 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11298   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11299          "Unexpected type for custom-lowering FP_EXTEND");
11300
11301   RTLIB::Libcall LC;
11302   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11303
11304   SDValue SrcVal = Op.getOperand(0);
11305   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11306                      /*isSigned*/ false, SDLoc(Op)).first;
11307 }
11308
11309 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11310   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11311          Subtarget->isFPOnlySP() &&
11312          "Unexpected type for custom-lowering FP_ROUND");
11313
11314   RTLIB::Libcall LC;
11315   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11316
11317   SDValue SrcVal = Op.getOperand(0);
11318   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11319                      /*isSigned*/ false, SDLoc(Op)).first;
11320 }
11321
11322 bool
11323 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11324   // The ARM target isn't yet aware of offsets.
11325   return false;
11326 }
11327
11328 bool ARM::isBitFieldInvertedMask(unsigned v) {
11329   if (v == 0xffffffff)
11330     return false;
11331
11332   // there can be 1's on either or both "outsides", all the "inside"
11333   // bits must be 0's
11334   return isShiftedMask_32(~v);
11335 }
11336
11337 /// isFPImmLegal - Returns true if the target can instruction select the
11338 /// specified FP immediate natively. If false, the legalizer will
11339 /// materialize the FP immediate as a load from a constant pool.
11340 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11341   if (!Subtarget->hasVFP3())
11342     return false;
11343   if (VT == MVT::f32)
11344     return ARM_AM::getFP32Imm(Imm) != -1;
11345   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11346     return ARM_AM::getFP64Imm(Imm) != -1;
11347   return false;
11348 }
11349
11350 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11351 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11352 /// specified in the intrinsic calls.
11353 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11354                                            const CallInst &I,
11355                                            unsigned Intrinsic) const {
11356   switch (Intrinsic) {
11357   case Intrinsic::arm_neon_vld1:
11358   case Intrinsic::arm_neon_vld2:
11359   case Intrinsic::arm_neon_vld3:
11360   case Intrinsic::arm_neon_vld4:
11361   case Intrinsic::arm_neon_vld2lane:
11362   case Intrinsic::arm_neon_vld3lane:
11363   case Intrinsic::arm_neon_vld4lane: {
11364     Info.opc = ISD::INTRINSIC_W_CHAIN;
11365     // Conservatively set memVT to the entire set of vectors loaded.
11366     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11367     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11368     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11369     Info.ptrVal = I.getArgOperand(0);
11370     Info.offset = 0;
11371     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11372     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11373     Info.vol = false; // volatile loads with NEON intrinsics not supported
11374     Info.readMem = true;
11375     Info.writeMem = false;
11376     return true;
11377   }
11378   case Intrinsic::arm_neon_vst1:
11379   case Intrinsic::arm_neon_vst2:
11380   case Intrinsic::arm_neon_vst3:
11381   case Intrinsic::arm_neon_vst4:
11382   case Intrinsic::arm_neon_vst2lane:
11383   case Intrinsic::arm_neon_vst3lane:
11384   case Intrinsic::arm_neon_vst4lane: {
11385     Info.opc = ISD::INTRINSIC_VOID;
11386     // Conservatively set memVT to the entire set of vectors stored.
11387     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11388     unsigned NumElts = 0;
11389     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11390       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11391       if (!ArgTy->isVectorTy())
11392         break;
11393       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11394     }
11395     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11396     Info.ptrVal = I.getArgOperand(0);
11397     Info.offset = 0;
11398     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11399     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11400     Info.vol = false; // volatile stores with NEON intrinsics not supported
11401     Info.readMem = false;
11402     Info.writeMem = true;
11403     return true;
11404   }
11405   case Intrinsic::arm_ldaex:
11406   case Intrinsic::arm_ldrex: {
11407     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11408     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11409     Info.opc = ISD::INTRINSIC_W_CHAIN;
11410     Info.memVT = MVT::getVT(PtrTy->getElementType());
11411     Info.ptrVal = I.getArgOperand(0);
11412     Info.offset = 0;
11413     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11414     Info.vol = true;
11415     Info.readMem = true;
11416     Info.writeMem = false;
11417     return true;
11418   }
11419   case Intrinsic::arm_stlex:
11420   case Intrinsic::arm_strex: {
11421     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11422     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11423     Info.opc = ISD::INTRINSIC_W_CHAIN;
11424     Info.memVT = MVT::getVT(PtrTy->getElementType());
11425     Info.ptrVal = I.getArgOperand(1);
11426     Info.offset = 0;
11427     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11428     Info.vol = true;
11429     Info.readMem = false;
11430     Info.writeMem = true;
11431     return true;
11432   }
11433   case Intrinsic::arm_stlexd:
11434   case Intrinsic::arm_strexd: {
11435     Info.opc = ISD::INTRINSIC_W_CHAIN;
11436     Info.memVT = MVT::i64;
11437     Info.ptrVal = I.getArgOperand(2);
11438     Info.offset = 0;
11439     Info.align = 8;
11440     Info.vol = true;
11441     Info.readMem = false;
11442     Info.writeMem = true;
11443     return true;
11444   }
11445   case Intrinsic::arm_ldaexd:
11446   case Intrinsic::arm_ldrexd: {
11447     Info.opc = ISD::INTRINSIC_W_CHAIN;
11448     Info.memVT = MVT::i64;
11449     Info.ptrVal = I.getArgOperand(0);
11450     Info.offset = 0;
11451     Info.align = 8;
11452     Info.vol = true;
11453     Info.readMem = true;
11454     Info.writeMem = false;
11455     return true;
11456   }
11457   default:
11458     break;
11459   }
11460
11461   return false;
11462 }
11463
11464 /// \brief Returns true if it is beneficial to convert a load of a constant
11465 /// to just the constant itself.
11466 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11467                                                           Type *Ty) const {
11468   assert(Ty->isIntegerTy());
11469
11470   unsigned Bits = Ty->getPrimitiveSizeInBits();
11471   if (Bits == 0 || Bits > 32)
11472     return false;
11473   return true;
11474 }
11475
11476 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11477
11478 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11479                                         ARM_MB::MemBOpt Domain) const {
11480   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11481
11482   // First, if the target has no DMB, see what fallback we can use.
11483   if (!Subtarget->hasDataBarrier()) {
11484     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11485     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11486     // here.
11487     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11488       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11489       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11490                         Builder.getInt32(0), Builder.getInt32(7),
11491                         Builder.getInt32(10), Builder.getInt32(5)};
11492       return Builder.CreateCall(MCR, args);
11493     } else {
11494       // Instead of using barriers, atomic accesses on these subtargets use
11495       // libcalls.
11496       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11497     }
11498   } else {
11499     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11500     // Only a full system barrier exists in the M-class architectures.
11501     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11502     Constant *CDomain = Builder.getInt32(Domain);
11503     return Builder.CreateCall(DMB, CDomain);
11504   }
11505 }
11506
11507 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11508 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11509                                          AtomicOrdering Ord, bool IsStore,
11510                                          bool IsLoad) const {
11511   if (!getInsertFencesForAtomic())
11512     return nullptr;
11513
11514   switch (Ord) {
11515   case NotAtomic:
11516   case Unordered:
11517     llvm_unreachable("Invalid fence: unordered/non-atomic");
11518   case Monotonic:
11519   case Acquire:
11520     return nullptr; // Nothing to do
11521   case SequentiallyConsistent:
11522     if (!IsStore)
11523       return nullptr; // Nothing to do
11524     /*FALLTHROUGH*/
11525   case Release:
11526   case AcquireRelease:
11527     if (Subtarget->isSwift())
11528       return makeDMB(Builder, ARM_MB::ISHST);
11529     // FIXME: add a comment with a link to documentation justifying this.
11530     else
11531       return makeDMB(Builder, ARM_MB::ISH);
11532   }
11533   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11534 }
11535
11536 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11537                                           AtomicOrdering Ord, bool IsStore,
11538                                           bool IsLoad) const {
11539   if (!getInsertFencesForAtomic())
11540     return nullptr;
11541
11542   switch (Ord) {
11543   case NotAtomic:
11544   case Unordered:
11545     llvm_unreachable("Invalid fence: unordered/not-atomic");
11546   case Monotonic:
11547   case Release:
11548     return nullptr; // Nothing to do
11549   case Acquire:
11550   case AcquireRelease:
11551   case SequentiallyConsistent:
11552     return makeDMB(Builder, ARM_MB::ISH);
11553   }
11554   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11555 }
11556
11557 // Loads and stores less than 64-bits are already atomic; ones above that
11558 // are doomed anyway, so defer to the default libcall and blame the OS when
11559 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11560 // anything for those.
11561 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11562   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11563   return (Size == 64) && !Subtarget->isMClass();
11564 }
11565
11566 // Loads and stores less than 64-bits are already atomic; ones above that
11567 // are doomed anyway, so defer to the default libcall and blame the OS when
11568 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11569 // anything for those.
11570 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11571 // guarantee, see DDI0406C ARM architecture reference manual,
11572 // sections A8.8.72-74 LDRD)
11573 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11574   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11575   return (Size == 64) && !Subtarget->isMClass();
11576 }
11577
11578 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11579 // and up to 64 bits on the non-M profiles
11580 TargetLoweringBase::AtomicRMWExpansionKind
11581 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11582   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11583   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11584              ? AtomicRMWExpansionKind::LLSC
11585              : AtomicRMWExpansionKind::None;
11586 }
11587
11588 // This has so far only been implemented for MachO.
11589 bool ARMTargetLowering::useLoadStackGuardNode() const {
11590   return Subtarget->isTargetMachO();
11591 }
11592
11593 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11594                                                   unsigned &Cost) const {
11595   // If we do not have NEON, vector types are not natively supported.
11596   if (!Subtarget->hasNEON())
11597     return false;
11598
11599   // Floating point values and vector values map to the same register file.
11600   // Therefore, althought we could do a store extract of a vector type, this is
11601   // better to leave at float as we have more freedom in the addressing mode for
11602   // those.
11603   if (VectorTy->isFPOrFPVectorTy())
11604     return false;
11605
11606   // If the index is unknown at compile time, this is very expensive to lower
11607   // and it is not possible to combine the store with the extract.
11608   if (!isa<ConstantInt>(Idx))
11609     return false;
11610
11611   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11612   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11613   // We can do a store + vector extract on any vector that fits perfectly in a D
11614   // or Q register.
11615   if (BitWidth == 64 || BitWidth == 128) {
11616     Cost = 0;
11617     return true;
11618   }
11619   return false;
11620 }
11621
11622 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11623                                          AtomicOrdering Ord) const {
11624   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11625   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11626   bool IsAcquire = isAtLeastAcquire(Ord);
11627
11628   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11629   // intrinsic must return {i32, i32} and we have to recombine them into a
11630   // single i64 here.
11631   if (ValTy->getPrimitiveSizeInBits() == 64) {
11632     Intrinsic::ID Int =
11633         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11634     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11635
11636     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11637     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11638
11639     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11640     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11641     if (!Subtarget->isLittle())
11642       std::swap (Lo, Hi);
11643     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11644     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11645     return Builder.CreateOr(
11646         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11647   }
11648
11649   Type *Tys[] = { Addr->getType() };
11650   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11651   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11652
11653   return Builder.CreateTruncOrBitCast(
11654       Builder.CreateCall(Ldrex, Addr),
11655       cast<PointerType>(Addr->getType())->getElementType());
11656 }
11657
11658 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11659                                                Value *Addr,
11660                                                AtomicOrdering Ord) const {
11661   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11662   bool IsRelease = isAtLeastRelease(Ord);
11663
11664   // Since the intrinsics must have legal type, the i64 intrinsics take two
11665   // parameters: "i32, i32". We must marshal Val into the appropriate form
11666   // before the call.
11667   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11668     Intrinsic::ID Int =
11669         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11670     Function *Strex = Intrinsic::getDeclaration(M, Int);
11671     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11672
11673     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11674     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11675     if (!Subtarget->isLittle())
11676       std::swap (Lo, Hi);
11677     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11678     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11679   }
11680
11681   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11682   Type *Tys[] = { Addr->getType() };
11683   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11684
11685   return Builder.CreateCall(
11686       Strex, {Builder.CreateZExtOrBitCast(
11687                   Val, Strex->getFunctionType()->getParamType(0)),
11688               Addr});
11689 }
11690
11691 /// \brief Lower an interleaved load into a vldN intrinsic.
11692 ///
11693 /// E.g. Lower an interleaved load (Factor = 2):
11694 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11695 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11696 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11697 ///
11698 ///      Into:
11699 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11700 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11701 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11702 bool ARMTargetLowering::lowerInterleavedLoad(
11703     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11704     ArrayRef<unsigned> Indices, unsigned Factor) const {
11705   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11706          "Invalid interleave factor");
11707   assert(!Shuffles.empty() && "Empty shufflevector input");
11708   assert(Shuffles.size() == Indices.size() &&
11709          "Unmatched number of shufflevectors and indices");
11710
11711   VectorType *VecTy = Shuffles[0]->getType();
11712   Type *EltTy = VecTy->getVectorElementType();
11713
11714   const DataLayout &DL = LI->getModule()->getDataLayout();
11715   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11716   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11717
11718   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11719   // support i64/f64 element).
11720   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11721     return false;
11722
11723   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11724   // load integer vectors first and then convert to pointer vectors.
11725   if (EltTy->isPointerTy())
11726     VecTy =
11727         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11728
11729   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11730                                             Intrinsic::arm_neon_vld3,
11731                                             Intrinsic::arm_neon_vld4};
11732
11733   Function *VldnFunc =
11734       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11735
11736   IRBuilder<> Builder(LI);
11737   SmallVector<Value *, 2> Ops;
11738
11739   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11740   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11741   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11742
11743   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11744
11745   // Replace uses of each shufflevector with the corresponding vector loaded
11746   // by ldN.
11747   for (unsigned i = 0; i < Shuffles.size(); i++) {
11748     ShuffleVectorInst *SV = Shuffles[i];
11749     unsigned Index = Indices[i];
11750
11751     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11752
11753     // Convert the integer vector to pointer vector if the element is pointer.
11754     if (EltTy->isPointerTy())
11755       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11756
11757     SV->replaceAllUsesWith(SubVec);
11758   }
11759
11760   return true;
11761 }
11762
11763 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11764 ///
11765 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11766 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11767                                    unsigned NumElts) {
11768   SmallVector<Constant *, 16> Mask;
11769   for (unsigned i = 0; i < NumElts; i++)
11770     Mask.push_back(Builder.getInt32(Start + i));
11771
11772   return ConstantVector::get(Mask);
11773 }
11774
11775 /// \brief Lower an interleaved store into a vstN intrinsic.
11776 ///
11777 /// E.g. Lower an interleaved store (Factor = 3):
11778 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11779 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11780 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11781 ///
11782 ///      Into:
11783 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11784 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11785 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11786 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11787 ///
11788 /// Note that the new shufflevectors will be removed and we'll only generate one
11789 /// vst3 instruction in CodeGen.
11790 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11791                                               ShuffleVectorInst *SVI,
11792                                               unsigned Factor) const {
11793   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11794          "Invalid interleave factor");
11795
11796   VectorType *VecTy = SVI->getType();
11797   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11798          "Invalid interleaved store");
11799
11800   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11801   Type *EltTy = VecTy->getVectorElementType();
11802   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11803
11804   const DataLayout &DL = SI->getModule()->getDataLayout();
11805   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11806   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11807
11808   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11809   // doesn't support i64/f64 element).
11810   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11811     return false;
11812
11813   Value *Op0 = SVI->getOperand(0);
11814   Value *Op1 = SVI->getOperand(1);
11815   IRBuilder<> Builder(SI);
11816
11817   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11818   // vectors to integer vectors.
11819   if (EltTy->isPointerTy()) {
11820     Type *IntTy = DL.getIntPtrType(EltTy);
11821
11822     // Convert to the corresponding integer vector.
11823     Type *IntVecTy =
11824         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11825     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11826     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11827
11828     SubVecTy = VectorType::get(IntTy, NumSubElts);
11829   }
11830
11831   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11832                                        Intrinsic::arm_neon_vst3,
11833                                        Intrinsic::arm_neon_vst4};
11834   Function *VstNFunc = Intrinsic::getDeclaration(
11835       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11836
11837   SmallVector<Value *, 6> Ops;
11838
11839   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11840   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11841
11842   // Split the shufflevector operands into sub vectors for the new vstN call.
11843   for (unsigned i = 0; i < Factor; i++)
11844     Ops.push_back(Builder.CreateShuffleVector(
11845         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11846
11847   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11848   Builder.CreateCall(VstNFunc, Ops);
11849   return true;
11850 }
11851
11852 enum HABaseType {
11853   HA_UNKNOWN = 0,
11854   HA_FLOAT,
11855   HA_DOUBLE,
11856   HA_VECT64,
11857   HA_VECT128
11858 };
11859
11860 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11861                                    uint64_t &Members) {
11862   if (auto *ST = dyn_cast<StructType>(Ty)) {
11863     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11864       uint64_t SubMembers = 0;
11865       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11866         return false;
11867       Members += SubMembers;
11868     }
11869   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11870     uint64_t SubMembers = 0;
11871     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11872       return false;
11873     Members += SubMembers * AT->getNumElements();
11874   } else if (Ty->isFloatTy()) {
11875     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11876       return false;
11877     Members = 1;
11878     Base = HA_FLOAT;
11879   } else if (Ty->isDoubleTy()) {
11880     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11881       return false;
11882     Members = 1;
11883     Base = HA_DOUBLE;
11884   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11885     Members = 1;
11886     switch (Base) {
11887     case HA_FLOAT:
11888     case HA_DOUBLE:
11889       return false;
11890     case HA_VECT64:
11891       return VT->getBitWidth() == 64;
11892     case HA_VECT128:
11893       return VT->getBitWidth() == 128;
11894     case HA_UNKNOWN:
11895       switch (VT->getBitWidth()) {
11896       case 64:
11897         Base = HA_VECT64;
11898         return true;
11899       case 128:
11900         Base = HA_VECT128;
11901         return true;
11902       default:
11903         return false;
11904       }
11905     }
11906   }
11907
11908   return (Members > 0 && Members <= 4);
11909 }
11910
11911 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11912 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11913 /// passing according to AAPCS rules.
11914 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11915     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11916   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11917       CallingConv::ARM_AAPCS_VFP)
11918     return false;
11919
11920   HABaseType Base = HA_UNKNOWN;
11921   uint64_t Members = 0;
11922   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11923   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11924
11925   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11926   return IsHA || IsIntArray;
11927 }