ARM/ELF: Better codegen for global variable addresses.
[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   if (!VT.isFloatingPoint() &&
151       VT != MVT::v2i64 && VT != MVT::v1i64)
152     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
153       setOperationAction(Opcode, VT, Legal);
154
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPRRegClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
163   addRegisterClass(VT, &ARM::DPairRegClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
168                                      const ARMSubtarget &STI)
169     : TargetLowering(TM), Subtarget(&STI) {
170   RegInfo = Subtarget->getRegisterInfo();
171   Itins = Subtarget->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
179       static const struct {
180         const RTLIB::Libcall Op;
181         const char * const Name;
182         const ISD::CondCode Cond;
183       } LibraryCalls[] = {
184         // Single-precision floating-point arithmetic.
185         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
186         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
189
190         // Double-precision floating-point arithmetic.
191         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
192         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
193         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
194         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
195
196         // Single-precision comparisons.
197         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
198         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
199         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
200         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
201         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
202         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
203         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
204         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
205
206         // Double-precision comparisons.
207         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
208         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
209         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
210         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
211         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
212         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
213         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
214         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
215
216         // Floating-point to integer conversions.
217         // i64 conversions are done via library routines even when generating VFP
218         // instructions, so use the same ones.
219         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
220         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
221         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
222         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
223
224         // Conversions between floating types.
225         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
226         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
227
228         // Integer to floating-point conversions.
229         // i64 conversions are done via library routines even when generating VFP
230         // instructions, so use the same ones.
231         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
232         // e.g., __floatunsidf vs. __floatunssidfvfp.
233         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
234         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
235         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
236         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
237       };
238
239       for (const auto &LC : LibraryCalls) {
240         setLibcallName(LC.Op, LC.Name);
241         if (LC.Cond != ISD::SETCC_INVALID)
242           setCmpLibcallCC(LC.Op, LC.Cond);
243       }
244     }
245   }
246
247   // These libcalls are not available in 32-bit.
248   setLibcallName(RTLIB::SHL_I128, nullptr);
249   setLibcallName(RTLIB::SRL_I128, nullptr);
250   setLibcallName(RTLIB::SRA_I128, nullptr);
251
252   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
253       !Subtarget->isTargetWindows()) {
254     static const struct {
255       const RTLIB::Libcall Op;
256       const char * const Name;
257       const CallingConv::ID CC;
258       const ISD::CondCode Cond;
259     } LibraryCalls[] = {
260       // Double-precision floating-point arithmetic helper functions
261       // RTABI chapter 4.1.2, Table 2
262       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266
267       // Double-precision floating-point comparison helper functions
268       // RTABI chapter 4.1.2, Table 3
269       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
271       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
272       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
273       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
274       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
277
278       // Single-precision floating-point arithmetic helper functions
279       // RTABI chapter 4.1.2, Table 4
280       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284
285       // Single-precision floating-point comparison helper functions
286       // RTABI chapter 4.1.2, Table 5
287       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
289       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
290       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
291       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
292       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
295
296       // Floating-point to integer conversions.
297       // RTABI chapter 4.1.2, Table 6
298       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306
307       // Conversions between floating types.
308       // RTABI chapter 4.1.2, Table 7
309       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Integer to floating-point conversions.
314       // RTABI chapter 4.1.2, Table 8
315       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323
324       // Long long helper functions
325       // RTABI chapter 4.2, Table 9
326       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Integer division functions
332       // RTABI chapter 4.3.1
333       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341
342       // Memory operations
343       // RTABI chapter 4.3.4
344       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347     };
348
349     for (const auto &LC : LibraryCalls) {
350       setLibcallName(LC.Op, LC.Name);
351       setLibcallCallingConv(LC.Op, LC.CC);
352       if (LC.Cond != ISD::SETCC_INVALID)
353         setCmpLibcallCC(LC.Op, LC.Cond);
354     }
355   }
356
357   if (Subtarget->isTargetWindows()) {
358     static const struct {
359       const RTLIB::Libcall Op;
360       const char * const Name;
361       const CallingConv::ID CC;
362     } LibraryCalls[] = {
363       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
366       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
367       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UINTTOFP_I64_F64, "__u64tod", 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   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
400   // a __gnu_ prefix (which is the default).
401   if (Subtarget->isTargetAEABI()) {
402     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
403     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
404     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
405   }
406
407   if (Subtarget->isThumb1Only())
408     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
409   else
410     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
411   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
412       !Subtarget->isThumb1Only()) {
413     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
414     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
415   }
416
417   for (MVT VT : MVT::vector_valuetypes()) {
418     for (MVT InnerVT : MVT::vector_valuetypes()) {
419       setTruncStoreAction(VT, InnerVT, Expand);
420       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
421       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
422       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
423     }
424
425     setOperationAction(ISD::MULHS, VT, Expand);
426     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
427     setOperationAction(ISD::MULHU, VT, Expand);
428     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
429
430     setOperationAction(ISD::BSWAP, VT, Expand);
431   }
432
433   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435
436   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
437   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
438
439   if (Subtarget->hasNEON()) {
440     addDRTypeForNEON(MVT::v2f32);
441     addDRTypeForNEON(MVT::v8i8);
442     addDRTypeForNEON(MVT::v4i16);
443     addDRTypeForNEON(MVT::v2i32);
444     addDRTypeForNEON(MVT::v1i64);
445
446     addQRTypeForNEON(MVT::v4f32);
447     addQRTypeForNEON(MVT::v2f64);
448     addQRTypeForNEON(MVT::v16i8);
449     addQRTypeForNEON(MVT::v8i16);
450     addQRTypeForNEON(MVT::v4i32);
451     addQRTypeForNEON(MVT::v2i64);
452
453     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
454     // neither Neon nor VFP support any arithmetic operations on it.
455     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
456     // supported for v4f32.
457     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
458     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
459     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
460     // FIXME: Code duplication: FDIV and FREM are expanded always, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
463     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
464     // FIXME: Create unittest.
465     // In another words, find a way when "copysign" appears in DAG with vector
466     // operands.
467     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
468     // FIXME: Code duplication: SETCC has custom operation action, see
469     // ARMTargetLowering::addTypeForNEON method for details.
470     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
471     // FIXME: Create unittest for FNEG and for FABS.
472     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
473     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
476     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
477     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
478     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
479     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
480     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
481     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
482     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
483     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
484     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
485     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
486     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
487     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
488     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
489     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
490     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
491
492     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
493     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
495     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
496     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
497     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
498     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
500     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
501     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
502     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
504     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
507
508     // Mark v2f32 intrinsics.
509     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
524
525     // Neon does not support some operations on v1i64 and v2i64 types.
526     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
527     // Custom handling for some quad-vector types to detect VMULL.
528     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
529     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
530     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
531     // Custom handling for some vector types to avoid expensive expansions
532     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
533     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
534     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
535     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
536     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
537     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
538     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
539     // a destination type that is wider than the source, and nor does
540     // it have a FP_TO_[SU]INT instruction with a narrower destination than
541     // source.
542     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
543     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
544     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
545     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
546
547     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
548     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
549
550     // NEON does not have single instruction CTPOP for vectors with element
551     // types wider than 8-bits.  However, custom lowering can leverage the
552     // v8i8/v16i8 vcnt instruction.
553     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
554     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
555     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
556     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
557
558     // NEON does not have single instruction CTTZ for vectors.
559     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
560     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
561     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
562     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
563
564     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
565     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
566     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
567     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
568
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
570     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
571     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
572     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
573
574     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
575     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
576     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
577     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
578
579     // NEON only has FMA instructions as of VFP4.
580     if (!Subtarget->hasVFP4()) {
581       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
582       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
583     }
584
585     setTargetDAGCombine(ISD::INTRINSIC_VOID);
586     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
587     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
588     setTargetDAGCombine(ISD::SHL);
589     setTargetDAGCombine(ISD::SRL);
590     setTargetDAGCombine(ISD::SRA);
591     setTargetDAGCombine(ISD::SIGN_EXTEND);
592     setTargetDAGCombine(ISD::ZERO_EXTEND);
593     setTargetDAGCombine(ISD::ANY_EXTEND);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601     setTargetDAGCombine(ISD::LOAD);
602
603     // It is legal to extload from v4i8 to v4i16 or v4i32.
604     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
605                    MVT::v2i32}) {
606       for (MVT VT : MVT::integer_vector_valuetypes()) {
607         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
608         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
609         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
610       }
611     }
612   }
613
614   // ARM and Thumb2 support UMLAL/SMLAL.
615   if (!Subtarget->isThumb1Only())
616     setTargetDAGCombine(ISD::ADDC);
617
618   if (Subtarget->isFPOnlySP()) {
619     // When targeting a floating-point unit with only single-precision
620     // operations, f64 is legal for the few double-precision instructions which
621     // are present However, no double-precision operations other than moves,
622     // loads and stores are provided by the hardware.
623     setOperationAction(ISD::FADD,       MVT::f64, Expand);
624     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
625     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
626     setOperationAction(ISD::FMA,        MVT::f64, Expand);
627     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
628     setOperationAction(ISD::FREM,       MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
630     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
631     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
632     setOperationAction(ISD::FABS,       MVT::f64, Expand);
633     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
634     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
635     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
636     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
637     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
638     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
639     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
640     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
641     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
642     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
643     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
644     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
645     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
647     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
648     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
649     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
650     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
651     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
652     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
653     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
654     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
655     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
656   }
657
658   computeRegisterProperties(Subtarget->getRegisterInfo());
659
660   // ARM does not have floating-point extending loads.
661   for (MVT VT : MVT::fp_valuetypes()) {
662     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
663     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
664   }
665
666   // ... or truncating stores
667   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
668   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
669   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
670
671   // ARM does not have i1 sign extending load.
672   for (MVT VT : MVT::integer_valuetypes())
673     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
674
675   // ARM supports all 4 flavors of integer indexed load / store.
676   if (!Subtarget->isThumb1Only()) {
677     for (unsigned im = (unsigned)ISD::PRE_INC;
678          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
679       setIndexedLoadAction(im,  MVT::i1,  Legal);
680       setIndexedLoadAction(im,  MVT::i8,  Legal);
681       setIndexedLoadAction(im,  MVT::i16, Legal);
682       setIndexedLoadAction(im,  MVT::i32, Legal);
683       setIndexedStoreAction(im, MVT::i1,  Legal);
684       setIndexedStoreAction(im, MVT::i8,  Legal);
685       setIndexedStoreAction(im, MVT::i16, Legal);
686       setIndexedStoreAction(im, MVT::i32, Legal);
687     }
688   }
689
690   setOperationAction(ISD::SADDO, MVT::i32, Custom);
691   setOperationAction(ISD::UADDO, MVT::i32, Custom);
692   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
693   setOperationAction(ISD::USUBO, MVT::i32, Custom);
694
695   // i64 operation support.
696   setOperationAction(ISD::MUL,     MVT::i64, Expand);
697   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
698   if (Subtarget->isThumb1Only()) {
699     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
700     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
701   }
702   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
703       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
704     setOperationAction(ISD::MULHS, MVT::i32, Expand);
705
706   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
707   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
708   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
709   setOperationAction(ISD::SRL,       MVT::i64, Custom);
710   setOperationAction(ISD::SRA,       MVT::i64, Custom);
711
712   if (!Subtarget->isThumb1Only()) {
713     // FIXME: We should do this for Thumb1 as well.
714     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
715     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
716     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
717     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
718   }
719
720   // ARM does not have ROTL.
721   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
722   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
723   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
724   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
725     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
726
727   // These just redirect to CTTZ and CTLZ on ARM.
728   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
729   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
730
731   // @llvm.readcyclecounter requires the Performance Monitors extension.
732   // Default to the 0 expansion on unsupported platforms.
733   // FIXME: Technically there are older ARM CPUs that have
734   // implementation-specific ways of obtaining this information.
735   if (Subtarget->hasPerfMon())
736     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
737
738   // Only ARMv6 has BSWAP.
739   if (!Subtarget->hasV6Ops())
740     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
741
742   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
743       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
744     // These are expanded into libcalls if the cpu doesn't have HW divider.
745     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
746     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
747   }
748
749   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
750     setOperationAction(ISD::SDIV, MVT::i32, Custom);
751     setOperationAction(ISD::UDIV, MVT::i32, Custom);
752
753     setOperationAction(ISD::SDIV, MVT::i64, Custom);
754     setOperationAction(ISD::UDIV, MVT::i64, Custom);
755   }
756
757   setOperationAction(ISD::SREM,  MVT::i32, Expand);
758   setOperationAction(ISD::UREM,  MVT::i32, Expand);
759   // Register based DivRem for AEABI (RTABI 4.2)
760   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
761     setOperationAction(ISD::SREM, MVT::i64, Custom);
762     setOperationAction(ISD::UREM, MVT::i64, Custom);
763
764     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
765     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
766     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
767     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
768     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
769     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
770     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
771     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
772
773     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
774     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
775     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
776     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
777     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
778     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
779     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
780     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
781
782     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
783     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
784   } else {
785     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
786     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
787   }
788
789   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
790   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
791   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
792   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
793
794   setOperationAction(ISD::TRAP, MVT::Other, Legal);
795
796   // Use the default implementation.
797   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
798   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
799   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
800   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
801   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
802   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
803
804   if (!Subtarget->isTargetMachO()) {
805     // Non-MachO platforms may return values in these registers via the
806     // personality function.
807     setExceptionPointerRegister(ARM::R0);
808     setExceptionSelectorRegister(ARM::R1);
809   }
810
811   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
812     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
813   else
814     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
815
816   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
817   // the default expansion. If we are targeting a single threaded system,
818   // then set them all for expand so we can lower them later into their
819   // non-atomic form.
820   if (TM.Options.ThreadModel == ThreadModel::Single)
821     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
822   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
823     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
824     // to ldrex/strex loops already.
825     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
826
827     // On v8, we have particularly efficient implementations of atomic fences
828     // if they can be combined with nearby atomic loads and stores.
829     if (!Subtarget->hasV8Ops()) {
830       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
831       setInsertFencesForAtomic(true);
832     }
833   } else {
834     // If there's anything we can use as a barrier, go through custom lowering
835     // for ATOMIC_FENCE.
836     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
837                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
838
839     // Set them all for expansion, which will force libcalls.
840     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
841     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
842     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
843     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
844     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
845     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
846     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
847     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
848     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
849     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
850     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
851     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
852     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
853     // Unordered/Monotonic case.
854     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
855     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
856   }
857
858   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
859
860   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
861   if (!Subtarget->hasV6Ops()) {
862     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
863     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
864   }
865   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
866
867   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
868       !Subtarget->isThumb1Only()) {
869     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
870     // iff target supports vfp2.
871     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
872     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
873   }
874
875   // We want to custom lower some of our intrinsics.
876   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
877   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
878   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
879   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
880   if (Subtarget->isTargetDarwin())
881     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
882
883   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
884   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
885   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
886   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
887   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
888   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
889   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
890   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
891   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
892
893   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
894   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
895   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
896   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
897   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
898
899   // We don't support sin/cos/fmod/copysign/pow
900   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
901   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
902   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
903   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
904   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
905   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
906   setOperationAction(ISD::FREM,      MVT::f64, Expand);
907   setOperationAction(ISD::FREM,      MVT::f32, Expand);
908   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
909       !Subtarget->isThumb1Only()) {
910     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
911     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
912   }
913   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
914   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
915
916   if (!Subtarget->hasVFP4()) {
917     setOperationAction(ISD::FMA, MVT::f64, Expand);
918     setOperationAction(ISD::FMA, MVT::f32, Expand);
919   }
920
921   // Various VFP goodness
922   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
923     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
924     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
925       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
926       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
927     }
928
929     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
930     if (!Subtarget->hasFP16()) {
931       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
932       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
933     }
934   }
935
936   // Combine sin / cos into one node or libcall if possible.
937   if (Subtarget->hasSinCos()) {
938     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
939     setLibcallName(RTLIB::SINCOS_F64, "sincos");
940     if (Subtarget->getTargetTriple().isiOS()) {
941       // For iOS, we don't want to the normal expansion of a libcall to
942       // sincos. We want to issue a libcall to __sincos_stret.
943       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
944       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
945     }
946   }
947
948   // FP-ARMv8 implements a lot of rounding-like FP operations.
949   if (Subtarget->hasFPARMv8()) {
950     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
951     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
952     setOperationAction(ISD::FROUND, MVT::f32, Legal);
953     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
954     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
955     setOperationAction(ISD::FRINT, MVT::f32, Legal);
956     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
957     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
958     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
959     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
960     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
961     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
962
963     if (!Subtarget->isFPOnlySP()) {
964       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
965       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
966       setOperationAction(ISD::FROUND, MVT::f64, Legal);
967       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
968       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
969       setOperationAction(ISD::FRINT, MVT::f64, Legal);
970       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
971       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
972     }
973   }
974
975   if (Subtarget->hasNEON()) {
976     // vmin and vmax aren't available in a scalar form, so we use
977     // a NEON instruction with an undef lane instead.
978     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
979     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
980     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
981     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
982     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
983     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
984   }
985
986   // We have target-specific dag combine patterns for the following nodes:
987   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
988   setTargetDAGCombine(ISD::ADD);
989   setTargetDAGCombine(ISD::SUB);
990   setTargetDAGCombine(ISD::MUL);
991   setTargetDAGCombine(ISD::AND);
992   setTargetDAGCombine(ISD::OR);
993   setTargetDAGCombine(ISD::XOR);
994
995   if (Subtarget->hasV6Ops())
996     setTargetDAGCombine(ISD::SRL);
997
998   setStackPointerRegisterToSaveRestore(ARM::SP);
999
1000   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1001       !Subtarget->hasVFP2())
1002     setSchedulingPreference(Sched::RegPressure);
1003   else
1004     setSchedulingPreference(Sched::Hybrid);
1005
1006   //// temporary - rewrite interface to use type
1007   MaxStoresPerMemset = 8;
1008   MaxStoresPerMemsetOptSize = 4;
1009   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1010   MaxStoresPerMemcpyOptSize = 2;
1011   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1012   MaxStoresPerMemmoveOptSize = 2;
1013
1014   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1015   // are at least 4 bytes aligned.
1016   setMinStackArgumentAlignment(4);
1017
1018   // Prefer likely predicted branches to selects on out-of-order cores.
1019   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1020
1021   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1022 }
1023
1024 bool ARMTargetLowering::useSoftFloat() const {
1025   return Subtarget->useSoftFloat();
1026 }
1027
1028 // FIXME: It might make sense to define the representative register class as the
1029 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1030 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1031 // SPR's representative would be DPR_VFP2. This should work well if register
1032 // pressure tracking were modified such that a register use would increment the
1033 // pressure of the register class's representative and all of it's super
1034 // classes' representatives transitively. We have not implemented this because
1035 // of the difficulty prior to coalescing of modeling operand register classes
1036 // due to the common occurrence of cross class copies and subregister insertions
1037 // and extractions.
1038 std::pair<const TargetRegisterClass *, uint8_t>
1039 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1040                                            MVT VT) const {
1041   const TargetRegisterClass *RRC = nullptr;
1042   uint8_t Cost = 1;
1043   switch (VT.SimpleTy) {
1044   default:
1045     return TargetLowering::findRepresentativeClass(TRI, VT);
1046   // Use DPR as representative register class for all floating point
1047   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1048   // the cost is 1 for both f32 and f64.
1049   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1050   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1051     RRC = &ARM::DPRRegClass;
1052     // When NEON is used for SP, only half of the register file is available
1053     // because operations that define both SP and DP results will be constrained
1054     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1055     // coalescing by double-counting the SP regs. See the FIXME above.
1056     if (Subtarget->useNEONForSinglePrecisionFP())
1057       Cost = 2;
1058     break;
1059   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1060   case MVT::v4f32: case MVT::v2f64:
1061     RRC = &ARM::DPRRegClass;
1062     Cost = 2;
1063     break;
1064   case MVT::v4i64:
1065     RRC = &ARM::DPRRegClass;
1066     Cost = 4;
1067     break;
1068   case MVT::v8i64:
1069     RRC = &ARM::DPRRegClass;
1070     Cost = 8;
1071     break;
1072   }
1073   return std::make_pair(RRC, Cost);
1074 }
1075
1076 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1077   switch ((ARMISD::NodeType)Opcode) {
1078   case ARMISD::FIRST_NUMBER:  break;
1079   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1080   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1081   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1082   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1083   case ARMISD::CALL:          return "ARMISD::CALL";
1084   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1085   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1086   case ARMISD::tCALL:         return "ARMISD::tCALL";
1087   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1088   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1089   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1090   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1091   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1092   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1093   case ARMISD::CMP:           return "ARMISD::CMP";
1094   case ARMISD::CMN:           return "ARMISD::CMN";
1095   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1096   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1097   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1098   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1099   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1100
1101   case ARMISD::CMOV:          return "ARMISD::CMOV";
1102
1103   case ARMISD::RBIT:          return "ARMISD::RBIT";
1104
1105   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1106   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1107   case ARMISD::RRX:           return "ARMISD::RRX";
1108
1109   case ARMISD::ADDC:          return "ARMISD::ADDC";
1110   case ARMISD::ADDE:          return "ARMISD::ADDE";
1111   case ARMISD::SUBC:          return "ARMISD::SUBC";
1112   case ARMISD::SUBE:          return "ARMISD::SUBE";
1113
1114   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1115   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1116
1117   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1118   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1119   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1120
1121   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1122
1123   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1124
1125   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1126
1127   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1128
1129   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1130
1131   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1132   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1133
1134   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1135   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1136   case ARMISD::VCGE:          return "ARMISD::VCGE";
1137   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1138   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1139   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1140   case ARMISD::VCGT:          return "ARMISD::VCGT";
1141   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1142   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1143   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1144   case ARMISD::VTST:          return "ARMISD::VTST";
1145
1146   case ARMISD::VSHL:          return "ARMISD::VSHL";
1147   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1148   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1149   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1150   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1151   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1152   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1153   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1154   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1155   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1156   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1157   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1158   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1159   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1160   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1161   case ARMISD::VSLI:          return "ARMISD::VSLI";
1162   case ARMISD::VSRI:          return "ARMISD::VSRI";
1163   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1164   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1165   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1166   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1167   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1168   case ARMISD::VDUP:          return "ARMISD::VDUP";
1169   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1170   case ARMISD::VEXT:          return "ARMISD::VEXT";
1171   case ARMISD::VREV64:        return "ARMISD::VREV64";
1172   case ARMISD::VREV32:        return "ARMISD::VREV32";
1173   case ARMISD::VREV16:        return "ARMISD::VREV16";
1174   case ARMISD::VZIP:          return "ARMISD::VZIP";
1175   case ARMISD::VUZP:          return "ARMISD::VUZP";
1176   case ARMISD::VTRN:          return "ARMISD::VTRN";
1177   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1178   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1179   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1180   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1181   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1182   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1183   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1184   case ARMISD::BFI:           return "ARMISD::BFI";
1185   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1186   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1187   case ARMISD::VBSL:          return "ARMISD::VBSL";
1188   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1189   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1190   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1191   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1192   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1193   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1194   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1195   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1196   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1197   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1198   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1199   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1200   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1201   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1202   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1203   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1204   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1205   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1206   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1207   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1208   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1209   }
1210   return nullptr;
1211 }
1212
1213 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1214                                           EVT VT) const {
1215   if (!VT.isVector())
1216     return getPointerTy(DL);
1217   return VT.changeVectorElementTypeToInteger();
1218 }
1219
1220 /// getRegClassFor - Return the register class that should be used for the
1221 /// specified value type.
1222 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1223   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1224   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1225   // load / store 4 to 8 consecutive D registers.
1226   if (Subtarget->hasNEON()) {
1227     if (VT == MVT::v4i64)
1228       return &ARM::QQPRRegClass;
1229     if (VT == MVT::v8i64)
1230       return &ARM::QQQQPRRegClass;
1231   }
1232   return TargetLowering::getRegClassFor(VT);
1233 }
1234
1235 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1236 // source/dest is aligned and the copy size is large enough. We therefore want
1237 // to align such objects passed to memory intrinsics.
1238 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1239                                                unsigned &PrefAlign) const {
1240   if (!isa<MemIntrinsic>(CI))
1241     return false;
1242   MinSize = 8;
1243   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1244   // cycle faster than 4-byte aligned LDM.
1245   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1246   return true;
1247 }
1248
1249 // Create a fast isel object.
1250 FastISel *
1251 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1252                                   const TargetLibraryInfo *libInfo) const {
1253   return ARM::createFastISel(funcInfo, libInfo);
1254 }
1255
1256 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1257   unsigned NumVals = N->getNumValues();
1258   if (!NumVals)
1259     return Sched::RegPressure;
1260
1261   for (unsigned i = 0; i != NumVals; ++i) {
1262     EVT VT = N->getValueType(i);
1263     if (VT == MVT::Glue || VT == MVT::Other)
1264       continue;
1265     if (VT.isFloatingPoint() || VT.isVector())
1266       return Sched::ILP;
1267   }
1268
1269   if (!N->isMachineOpcode())
1270     return Sched::RegPressure;
1271
1272   // Load are scheduled for latency even if there instruction itinerary
1273   // is not available.
1274   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1275   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1276
1277   if (MCID.getNumDefs() == 0)
1278     return Sched::RegPressure;
1279   if (!Itins->isEmpty() &&
1280       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1281     return Sched::ILP;
1282
1283   return Sched::RegPressure;
1284 }
1285
1286 //===----------------------------------------------------------------------===//
1287 // Lowering Code
1288 //===----------------------------------------------------------------------===//
1289
1290 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1291 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1292   switch (CC) {
1293   default: llvm_unreachable("Unknown condition code!");
1294   case ISD::SETNE:  return ARMCC::NE;
1295   case ISD::SETEQ:  return ARMCC::EQ;
1296   case ISD::SETGT:  return ARMCC::GT;
1297   case ISD::SETGE:  return ARMCC::GE;
1298   case ISD::SETLT:  return ARMCC::LT;
1299   case ISD::SETLE:  return ARMCC::LE;
1300   case ISD::SETUGT: return ARMCC::HI;
1301   case ISD::SETUGE: return ARMCC::HS;
1302   case ISD::SETULT: return ARMCC::LO;
1303   case ISD::SETULE: return ARMCC::LS;
1304   }
1305 }
1306
1307 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1308 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1309                         ARMCC::CondCodes &CondCode2) {
1310   CondCode2 = ARMCC::AL;
1311   switch (CC) {
1312   default: llvm_unreachable("Unknown FP condition!");
1313   case ISD::SETEQ:
1314   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1315   case ISD::SETGT:
1316   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1317   case ISD::SETGE:
1318   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1319   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1320   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1321   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1322   case ISD::SETO:   CondCode = ARMCC::VC; break;
1323   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1324   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1325   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1326   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1327   case ISD::SETLT:
1328   case ISD::SETULT: CondCode = ARMCC::LT; break;
1329   case ISD::SETLE:
1330   case ISD::SETULE: CondCode = ARMCC::LE; break;
1331   case ISD::SETNE:
1332   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1333   }
1334 }
1335
1336 //===----------------------------------------------------------------------===//
1337 //                      Calling Convention Implementation
1338 //===----------------------------------------------------------------------===//
1339
1340 #include "ARMGenCallingConv.inc"
1341
1342 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1343 /// account presence of floating point hardware and calling convention
1344 /// limitations, such as support for variadic functions.
1345 CallingConv::ID
1346 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1347                                            bool isVarArg) const {
1348   switch (CC) {
1349   default:
1350     llvm_unreachable("Unsupported calling convention");
1351   case CallingConv::ARM_AAPCS:
1352   case CallingConv::ARM_APCS:
1353   case CallingConv::GHC:
1354     return CC;
1355   case CallingConv::ARM_AAPCS_VFP:
1356     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1357   case CallingConv::C:
1358     if (!Subtarget->isAAPCS_ABI())
1359       return CallingConv::ARM_APCS;
1360     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1361              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1362              !isVarArg)
1363       return CallingConv::ARM_AAPCS_VFP;
1364     else
1365       return CallingConv::ARM_AAPCS;
1366   case CallingConv::Fast:
1367     if (!Subtarget->isAAPCS_ABI()) {
1368       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1369         return CallingConv::Fast;
1370       return CallingConv::ARM_APCS;
1371     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1372       return CallingConv::ARM_AAPCS_VFP;
1373     else
1374       return CallingConv::ARM_AAPCS;
1375   }
1376 }
1377
1378 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1379 /// CallingConvention.
1380 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1381                                                  bool Return,
1382                                                  bool isVarArg) const {
1383   switch (getEffectiveCallingConv(CC, isVarArg)) {
1384   default:
1385     llvm_unreachable("Unsupported calling convention");
1386   case CallingConv::ARM_APCS:
1387     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1388   case CallingConv::ARM_AAPCS:
1389     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1390   case CallingConv::ARM_AAPCS_VFP:
1391     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1392   case CallingConv::Fast:
1393     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1394   case CallingConv::GHC:
1395     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1396   }
1397 }
1398
1399 /// LowerCallResult - Lower the result values of a call into the
1400 /// appropriate copies out of appropriate physical registers.
1401 SDValue
1402 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1403                                    CallingConv::ID CallConv, bool isVarArg,
1404                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1405                                    SDLoc dl, SelectionDAG &DAG,
1406                                    SmallVectorImpl<SDValue> &InVals,
1407                                    bool isThisReturn, SDValue ThisVal) const {
1408
1409   // Assign locations to each value returned by this call.
1410   SmallVector<CCValAssign, 16> RVLocs;
1411   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1412                     *DAG.getContext(), Call);
1413   CCInfo.AnalyzeCallResult(Ins,
1414                            CCAssignFnForNode(CallConv, /* Return*/ true,
1415                                              isVarArg));
1416
1417   // Copy all of the result registers out of their specified physreg.
1418   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1419     CCValAssign VA = RVLocs[i];
1420
1421     // Pass 'this' value directly from the argument to return value, to avoid
1422     // reg unit interference
1423     if (i == 0 && isThisReturn) {
1424       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1425              "unexpected return calling convention register assignment");
1426       InVals.push_back(ThisVal);
1427       continue;
1428     }
1429
1430     SDValue Val;
1431     if (VA.needsCustom()) {
1432       // Handle f64 or half of a v2f64.
1433       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1434                                       InFlag);
1435       Chain = Lo.getValue(1);
1436       InFlag = Lo.getValue(2);
1437       VA = RVLocs[++i]; // skip ahead to next loc
1438       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1439                                       InFlag);
1440       Chain = Hi.getValue(1);
1441       InFlag = Hi.getValue(2);
1442       if (!Subtarget->isLittle())
1443         std::swap (Lo, Hi);
1444       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1445
1446       if (VA.getLocVT() == MVT::v2f64) {
1447         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1448         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1449                           DAG.getConstant(0, dl, MVT::i32));
1450
1451         VA = RVLocs[++i]; // skip ahead to next loc
1452         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1453         Chain = Lo.getValue(1);
1454         InFlag = Lo.getValue(2);
1455         VA = RVLocs[++i]; // skip ahead to next loc
1456         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1457         Chain = Hi.getValue(1);
1458         InFlag = Hi.getValue(2);
1459         if (!Subtarget->isLittle())
1460           std::swap (Lo, Hi);
1461         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1462         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1463                           DAG.getConstant(1, dl, MVT::i32));
1464       }
1465     } else {
1466       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1467                                InFlag);
1468       Chain = Val.getValue(1);
1469       InFlag = Val.getValue(2);
1470     }
1471
1472     switch (VA.getLocInfo()) {
1473     default: llvm_unreachable("Unknown loc info!");
1474     case CCValAssign::Full: break;
1475     case CCValAssign::BCvt:
1476       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1477       break;
1478     }
1479
1480     InVals.push_back(Val);
1481   }
1482
1483   return Chain;
1484 }
1485
1486 /// LowerMemOpCallTo - Store the argument to the stack.
1487 SDValue
1488 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1489                                     SDValue StackPtr, SDValue Arg,
1490                                     SDLoc dl, SelectionDAG &DAG,
1491                                     const CCValAssign &VA,
1492                                     ISD::ArgFlagsTy Flags) const {
1493   unsigned LocMemOffset = VA.getLocMemOffset();
1494   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1495   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1496                        StackPtr, PtrOff);
1497   return DAG.getStore(
1498       Chain, dl, Arg, PtrOff,
1499       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1500       false, false, 0);
1501 }
1502
1503 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1504                                          SDValue Chain, SDValue &Arg,
1505                                          RegsToPassVector &RegsToPass,
1506                                          CCValAssign &VA, CCValAssign &NextVA,
1507                                          SDValue &StackPtr,
1508                                          SmallVectorImpl<SDValue> &MemOpChains,
1509                                          ISD::ArgFlagsTy Flags) const {
1510
1511   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1512                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1513   unsigned id = Subtarget->isLittle() ? 0 : 1;
1514   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1515
1516   if (NextVA.isRegLoc())
1517     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1518   else {
1519     assert(NextVA.isMemLoc());
1520     if (!StackPtr.getNode())
1521       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1522                                     getPointerTy(DAG.getDataLayout()));
1523
1524     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1525                                            dl, DAG, NextVA,
1526                                            Flags));
1527   }
1528 }
1529
1530 /// LowerCall - Lowering a call into a callseq_start <-
1531 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1532 /// nodes.
1533 SDValue
1534 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1535                              SmallVectorImpl<SDValue> &InVals) const {
1536   SelectionDAG &DAG                     = CLI.DAG;
1537   SDLoc &dl                             = CLI.DL;
1538   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1539   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1540   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1541   SDValue Chain                         = CLI.Chain;
1542   SDValue Callee                        = CLI.Callee;
1543   bool &isTailCall                      = CLI.IsTailCall;
1544   CallingConv::ID CallConv              = CLI.CallConv;
1545   bool doesNotRet                       = CLI.DoesNotReturn;
1546   bool isVarArg                         = CLI.IsVarArg;
1547
1548   MachineFunction &MF = DAG.getMachineFunction();
1549   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1550   bool isThisReturn   = false;
1551   bool isSibCall      = false;
1552   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1553
1554   // Disable tail calls if they're not supported.
1555   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1556     isTailCall = false;
1557
1558   if (isTailCall) {
1559     // Check if it's really possible to do a tail call.
1560     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1561                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1562                                                    Outs, OutVals, Ins, DAG);
1563     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1564       report_fatal_error("failed to perform tail call elimination on a call "
1565                          "site marked musttail");
1566     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1567     // detected sibcalls.
1568     if (isTailCall) {
1569       ++NumTailCalls;
1570       isSibCall = true;
1571     }
1572   }
1573
1574   // Analyze operands of the call, assigning locations to each operand.
1575   SmallVector<CCValAssign, 16> ArgLocs;
1576   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1577                     *DAG.getContext(), Call);
1578   CCInfo.AnalyzeCallOperands(Outs,
1579                              CCAssignFnForNode(CallConv, /* Return*/ false,
1580                                                isVarArg));
1581
1582   // Get a count of how many bytes are to be pushed on the stack.
1583   unsigned NumBytes = CCInfo.getNextStackOffset();
1584
1585   // For tail calls, memory operands are available in our caller's stack.
1586   if (isSibCall)
1587     NumBytes = 0;
1588
1589   // Adjust the stack pointer for the new arguments...
1590   // These operations are automatically eliminated by the prolog/epilog pass
1591   if (!isSibCall)
1592     Chain = DAG.getCALLSEQ_START(Chain,
1593                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1594
1595   SDValue StackPtr =
1596       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1597
1598   RegsToPassVector RegsToPass;
1599   SmallVector<SDValue, 8> MemOpChains;
1600
1601   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1602   // of tail call optimization, arguments are handled later.
1603   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1604        i != e;
1605        ++i, ++realArgIdx) {
1606     CCValAssign &VA = ArgLocs[i];
1607     SDValue Arg = OutVals[realArgIdx];
1608     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1609     bool isByVal = Flags.isByVal();
1610
1611     // Promote the value if needed.
1612     switch (VA.getLocInfo()) {
1613     default: llvm_unreachable("Unknown loc info!");
1614     case CCValAssign::Full: break;
1615     case CCValAssign::SExt:
1616       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1617       break;
1618     case CCValAssign::ZExt:
1619       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1620       break;
1621     case CCValAssign::AExt:
1622       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1623       break;
1624     case CCValAssign::BCvt:
1625       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1626       break;
1627     }
1628
1629     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1630     if (VA.needsCustom()) {
1631       if (VA.getLocVT() == MVT::v2f64) {
1632         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1633                                   DAG.getConstant(0, dl, MVT::i32));
1634         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1635                                   DAG.getConstant(1, dl, MVT::i32));
1636
1637         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1638                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1639
1640         VA = ArgLocs[++i]; // skip ahead to next loc
1641         if (VA.isRegLoc()) {
1642           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1643                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1644         } else {
1645           assert(VA.isMemLoc());
1646
1647           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1648                                                  dl, DAG, VA, Flags));
1649         }
1650       } else {
1651         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1652                          StackPtr, MemOpChains, Flags);
1653       }
1654     } else if (VA.isRegLoc()) {
1655       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1656         assert(VA.getLocVT() == MVT::i32 &&
1657                "unexpected calling convention register assignment");
1658         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1659                "unexpected use of 'returned'");
1660         isThisReturn = true;
1661       }
1662       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1663     } else if (isByVal) {
1664       assert(VA.isMemLoc());
1665       unsigned offset = 0;
1666
1667       // True if this byval aggregate will be split between registers
1668       // and memory.
1669       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1670       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1671
1672       if (CurByValIdx < ByValArgsCount) {
1673
1674         unsigned RegBegin, RegEnd;
1675         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1676
1677         EVT PtrVT =
1678             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1679         unsigned int i, j;
1680         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1681           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1682           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1683           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1684                                      MachinePointerInfo(),
1685                                      false, false, false,
1686                                      DAG.InferPtrAlignment(AddArg));
1687           MemOpChains.push_back(Load.getValue(1));
1688           RegsToPass.push_back(std::make_pair(j, Load));
1689         }
1690
1691         // If parameter size outsides register area, "offset" value
1692         // helps us to calculate stack slot for remained part properly.
1693         offset = RegEnd - RegBegin;
1694
1695         CCInfo.nextInRegsParam();
1696       }
1697
1698       if (Flags.getByValSize() > 4*offset) {
1699         auto PtrVT = getPointerTy(DAG.getDataLayout());
1700         unsigned LocMemOffset = VA.getLocMemOffset();
1701         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1702         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1703         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1704         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1705         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1706                                            MVT::i32);
1707         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1708                                             MVT::i32);
1709
1710         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1711         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1712         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1713                                           Ops));
1714       }
1715     } else if (!isSibCall) {
1716       assert(VA.isMemLoc());
1717
1718       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1719                                              dl, DAG, VA, Flags));
1720     }
1721   }
1722
1723   if (!MemOpChains.empty())
1724     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1725
1726   // Build a sequence of copy-to-reg nodes chained together with token chain
1727   // and flag operands which copy the outgoing args into the appropriate regs.
1728   SDValue InFlag;
1729   // Tail call byval lowering might overwrite argument registers so in case of
1730   // tail call optimization the copies to registers are lowered later.
1731   if (!isTailCall)
1732     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1733       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1734                                RegsToPass[i].second, InFlag);
1735       InFlag = Chain.getValue(1);
1736     }
1737
1738   // For tail calls lower the arguments to the 'real' stack slot.
1739   if (isTailCall) {
1740     // Force all the incoming stack arguments to be loaded from the stack
1741     // before any new outgoing arguments are stored to the stack, because the
1742     // outgoing stack slots may alias the incoming argument stack slots, and
1743     // the alias isn't otherwise explicit. This is slightly more conservative
1744     // than necessary, because it means that each store effectively depends
1745     // on every argument instead of just those arguments it would clobber.
1746
1747     // Do not flag preceding copytoreg stuff together with the following stuff.
1748     InFlag = SDValue();
1749     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1750       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1751                                RegsToPass[i].second, InFlag);
1752       InFlag = Chain.getValue(1);
1753     }
1754     InFlag = SDValue();
1755   }
1756
1757   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1758   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1759   // node so that legalize doesn't hack it.
1760   bool isDirect = false;
1761   bool isARMFunc = false;
1762   bool isLocalARMFunc = false;
1763   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1764   auto PtrVt = getPointerTy(DAG.getDataLayout());
1765
1766   if (Subtarget->genLongCalls()) {
1767     assert((Subtarget->isTargetWindows() ||
1768             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1769            "long-calls with non-static relocation model!");
1770     // Handle a global address or an external symbol. If it's not one of
1771     // those, the target's already in a register, so we don't need to do
1772     // anything extra.
1773     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1774       const GlobalValue *GV = G->getGlobal();
1775       // Create a constant pool entry for the callee address
1776       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1777       ARMConstantPoolValue *CPV =
1778         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1779
1780       // Get the address of the callee into a register
1781       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1782       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1783       Callee = DAG.getLoad(
1784           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1785           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1786           false, false, 0);
1787     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1788       const char *Sym = S->getSymbol();
1789
1790       // Create a constant pool entry for the callee address
1791       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1792       ARMConstantPoolValue *CPV =
1793         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1794                                       ARMPCLabelIndex, 0);
1795       // Get the address of the callee into a register
1796       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1797       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1798       Callee = DAG.getLoad(
1799           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1800           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1801           false, false, 0);
1802     }
1803   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1804     const GlobalValue *GV = G->getGlobal();
1805     isDirect = true;
1806     bool isDef = GV->isStrongDefinitionForLinker();
1807     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1808                    getTargetMachine().getRelocationModel() != Reloc::Static;
1809     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1810     // ARM call to a local ARM function is predicable.
1811     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1812     // tBX takes a register source operand.
1813     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1814       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1815       Callee = DAG.getNode(
1816           ARMISD::WrapperPIC, dl, PtrVt,
1817           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1818       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1819                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1820                            false, false, true, 0);
1821     } else if (Subtarget->isTargetCOFF()) {
1822       assert(Subtarget->isTargetWindows() &&
1823              "Windows is the only supported COFF target");
1824       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1825                                  ? ARMII::MO_DLLIMPORT
1826                                  : ARMII::MO_NO_FLAG;
1827       Callee =
1828           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1829       if (GV->hasDLLImportStorageClass())
1830         Callee =
1831             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1832                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1833                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1834                         false, false, false, 0);
1835     } else {
1836       // On ELF targets for PIC code, direct calls should go through the PLT
1837       unsigned OpFlags = 0;
1838       if (Subtarget->isTargetELF() &&
1839           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1840         OpFlags = ARMII::MO_PLT;
1841       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1842     }
1843   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1844     isDirect = true;
1845     bool isStub = Subtarget->isTargetMachO() &&
1846                   getTargetMachine().getRelocationModel() != Reloc::Static;
1847     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1848     // tBX takes a register source operand.
1849     const char *Sym = S->getSymbol();
1850     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1851       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1852       ARMConstantPoolValue *CPV =
1853         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1854                                       ARMPCLabelIndex, 4);
1855       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1856       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1857       Callee = DAG.getLoad(
1858           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1859           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1860           false, false, 0);
1861       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1862       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1863     } else {
1864       unsigned OpFlags = 0;
1865       // On ELF targets for PIC code, direct calls should go through the PLT
1866       if (Subtarget->isTargetELF() &&
1867                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1868         OpFlags = ARMII::MO_PLT;
1869       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1870     }
1871   }
1872
1873   // FIXME: handle tail calls differently.
1874   unsigned CallOpc;
1875   if (Subtarget->isThumb()) {
1876     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1877       CallOpc = ARMISD::CALL_NOLINK;
1878     else
1879       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1880   } else {
1881     if (!isDirect && !Subtarget->hasV5TOps())
1882       CallOpc = ARMISD::CALL_NOLINK;
1883     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1884              // Emit regular call when code size is the priority
1885              !MF.getFunction()->optForMinSize())
1886       // "mov lr, pc; b _foo" to avoid confusing the RSP
1887       CallOpc = ARMISD::CALL_NOLINK;
1888     else
1889       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1890   }
1891
1892   std::vector<SDValue> Ops;
1893   Ops.push_back(Chain);
1894   Ops.push_back(Callee);
1895
1896   // Add argument registers to the end of the list so that they are known live
1897   // into the call.
1898   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1899     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1900                                   RegsToPass[i].second.getValueType()));
1901
1902   // Add a register mask operand representing the call-preserved registers.
1903   if (!isTailCall) {
1904     const uint32_t *Mask;
1905     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1906     if (isThisReturn) {
1907       // For 'this' returns, use the R0-preserving mask if applicable
1908       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1909       if (!Mask) {
1910         // Set isThisReturn to false if the calling convention is not one that
1911         // allows 'returned' to be modeled in this way, so LowerCallResult does
1912         // not try to pass 'this' straight through
1913         isThisReturn = false;
1914         Mask = ARI->getCallPreservedMask(MF, CallConv);
1915       }
1916     } else
1917       Mask = ARI->getCallPreservedMask(MF, CallConv);
1918
1919     assert(Mask && "Missing call preserved mask for calling convention");
1920     Ops.push_back(DAG.getRegisterMask(Mask));
1921   }
1922
1923   if (InFlag.getNode())
1924     Ops.push_back(InFlag);
1925
1926   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1927   if (isTailCall) {
1928     MF.getFrameInfo()->setHasTailCall();
1929     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1930   }
1931
1932   // Returns a chain and a flag for retval copy to use.
1933   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1934   InFlag = Chain.getValue(1);
1935
1936   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1937                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1938   if (!Ins.empty())
1939     InFlag = Chain.getValue(1);
1940
1941   // Handle result values, copying them out of physregs into vregs that we
1942   // return.
1943   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1944                          InVals, isThisReturn,
1945                          isThisReturn ? OutVals[0] : SDValue());
1946 }
1947
1948 /// HandleByVal - Every parameter *after* a byval parameter is passed
1949 /// on the stack.  Remember the next parameter register to allocate,
1950 /// and then confiscate the rest of the parameter registers to insure
1951 /// this.
1952 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1953                                     unsigned Align) const {
1954   assert((State->getCallOrPrologue() == Prologue ||
1955           State->getCallOrPrologue() == Call) &&
1956          "unhandled ParmContext");
1957
1958   // Byval (as with any stack) slots are always at least 4 byte aligned.
1959   Align = std::max(Align, 4U);
1960
1961   unsigned Reg = State->AllocateReg(GPRArgRegs);
1962   if (!Reg)
1963     return;
1964
1965   unsigned AlignInRegs = Align / 4;
1966   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1967   for (unsigned i = 0; i < Waste; ++i)
1968     Reg = State->AllocateReg(GPRArgRegs);
1969
1970   if (!Reg)
1971     return;
1972
1973   unsigned Excess = 4 * (ARM::R4 - Reg);
1974
1975   // Special case when NSAA != SP and parameter size greater than size of
1976   // all remained GPR regs. In that case we can't split parameter, we must
1977   // send it to stack. We also must set NCRN to R4, so waste all
1978   // remained registers.
1979   const unsigned NSAAOffset = State->getNextStackOffset();
1980   if (NSAAOffset != 0 && Size > Excess) {
1981     while (State->AllocateReg(GPRArgRegs))
1982       ;
1983     return;
1984   }
1985
1986   // First register for byval parameter is the first register that wasn't
1987   // allocated before this method call, so it would be "reg".
1988   // If parameter is small enough to be saved in range [reg, r4), then
1989   // the end (first after last) register would be reg + param-size-in-regs,
1990   // else parameter would be splitted between registers and stack,
1991   // end register would be r4 in this case.
1992   unsigned ByValRegBegin = Reg;
1993   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1994   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1995   // Note, first register is allocated in the beginning of function already,
1996   // allocate remained amount of registers we need.
1997   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1998     State->AllocateReg(GPRArgRegs);
1999   // A byval parameter that is split between registers and memory needs its
2000   // size truncated here.
2001   // In the case where the entire structure fits in registers, we set the
2002   // size in memory to zero.
2003   Size = std::max<int>(Size - Excess, 0);
2004 }
2005
2006 /// MatchingStackOffset - Return true if the given stack call argument is
2007 /// already available in the same position (relatively) of the caller's
2008 /// incoming argument stack.
2009 static
2010 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2011                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2012                          const TargetInstrInfo *TII) {
2013   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2014   int FI = INT_MAX;
2015   if (Arg.getOpcode() == ISD::CopyFromReg) {
2016     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2017     if (!TargetRegisterInfo::isVirtualRegister(VR))
2018       return false;
2019     MachineInstr *Def = MRI->getVRegDef(VR);
2020     if (!Def)
2021       return false;
2022     if (!Flags.isByVal()) {
2023       if (!TII->isLoadFromStackSlot(Def, FI))
2024         return false;
2025     } else {
2026       return false;
2027     }
2028   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2029     if (Flags.isByVal())
2030       // ByVal argument is passed in as a pointer but it's now being
2031       // dereferenced. e.g.
2032       // define @foo(%struct.X* %A) {
2033       //   tail call @bar(%struct.X* byval %A)
2034       // }
2035       return false;
2036     SDValue Ptr = Ld->getBasePtr();
2037     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2038     if (!FINode)
2039       return false;
2040     FI = FINode->getIndex();
2041   } else
2042     return false;
2043
2044   assert(FI != INT_MAX);
2045   if (!MFI->isFixedObjectIndex(FI))
2046     return false;
2047   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2048 }
2049
2050 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2051 /// for tail call optimization. Targets which want to do tail call
2052 /// optimization should implement this function.
2053 bool
2054 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2055                                                      CallingConv::ID CalleeCC,
2056                                                      bool isVarArg,
2057                                                      bool isCalleeStructRet,
2058                                                      bool isCallerStructRet,
2059                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2060                                     const SmallVectorImpl<SDValue> &OutVals,
2061                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2062                                                      SelectionDAG& DAG) const {
2063   const Function *CallerF = DAG.getMachineFunction().getFunction();
2064   CallingConv::ID CallerCC = CallerF->getCallingConv();
2065   bool CCMatch = CallerCC == CalleeCC;
2066
2067   assert(Subtarget->supportsTailCall());
2068
2069   // Look for obvious safe cases to perform tail call optimization that do not
2070   // require ABI changes. This is what gcc calls sibcall.
2071
2072   // Do not sibcall optimize vararg calls unless the call site is not passing
2073   // any arguments.
2074   if (isVarArg && !Outs.empty())
2075     return false;
2076
2077   // Exception-handling functions need a special set of instructions to indicate
2078   // a return to the hardware. Tail-calling another function would probably
2079   // break this.
2080   if (CallerF->hasFnAttribute("interrupt"))
2081     return false;
2082
2083   // Also avoid sibcall optimization if either caller or callee uses struct
2084   // return semantics.
2085   if (isCalleeStructRet || isCallerStructRet)
2086     return false;
2087
2088   // Externally-defined functions with weak linkage should not be
2089   // tail-called on ARM when the OS does not support dynamic
2090   // pre-emption of symbols, as the AAELF spec requires normal calls
2091   // to undefined weak functions to be replaced with a NOP or jump to the
2092   // next instruction. The behaviour of branch instructions in this
2093   // situation (as used for tail calls) is implementation-defined, so we
2094   // cannot rely on the linker replacing the tail call with a return.
2095   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2096     const GlobalValue *GV = G->getGlobal();
2097     const Triple &TT = getTargetMachine().getTargetTriple();
2098     if (GV->hasExternalWeakLinkage() &&
2099         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2100       return false;
2101   }
2102
2103   // If the calling conventions do not match, then we'd better make sure the
2104   // results are returned in the same way as what the caller expects.
2105   if (!CCMatch) {
2106     SmallVector<CCValAssign, 16> RVLocs1;
2107     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2108                        *DAG.getContext(), Call);
2109     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2110
2111     SmallVector<CCValAssign, 16> RVLocs2;
2112     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2113                        *DAG.getContext(), Call);
2114     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2115
2116     if (RVLocs1.size() != RVLocs2.size())
2117       return false;
2118     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2119       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2120         return false;
2121       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2122         return false;
2123       if (RVLocs1[i].isRegLoc()) {
2124         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2125           return false;
2126       } else {
2127         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2128           return false;
2129       }
2130     }
2131   }
2132
2133   // If Caller's vararg or byval argument has been split between registers and
2134   // stack, do not perform tail call, since part of the argument is in caller's
2135   // local frame.
2136   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2137                                       getInfo<ARMFunctionInfo>();
2138   if (AFI_Caller->getArgRegsSaveSize())
2139     return false;
2140
2141   // If the callee takes no arguments then go on to check the results of the
2142   // call.
2143   if (!Outs.empty()) {
2144     // Check if stack adjustment is needed. For now, do not do this if any
2145     // argument is passed on the stack.
2146     SmallVector<CCValAssign, 16> ArgLocs;
2147     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2148                       *DAG.getContext(), Call);
2149     CCInfo.AnalyzeCallOperands(Outs,
2150                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2151     if (CCInfo.getNextStackOffset()) {
2152       MachineFunction &MF = DAG.getMachineFunction();
2153
2154       // Check if the arguments are already laid out in the right way as
2155       // the caller's fixed stack objects.
2156       MachineFrameInfo *MFI = MF.getFrameInfo();
2157       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2158       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2159       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2160            i != e;
2161            ++i, ++realArgIdx) {
2162         CCValAssign &VA = ArgLocs[i];
2163         EVT RegVT = VA.getLocVT();
2164         SDValue Arg = OutVals[realArgIdx];
2165         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2166         if (VA.getLocInfo() == CCValAssign::Indirect)
2167           return false;
2168         if (VA.needsCustom()) {
2169           // f64 and vector types are split into multiple registers or
2170           // register/stack-slot combinations.  The types will not match
2171           // the registers; give up on memory f64 refs until we figure
2172           // out what to do about this.
2173           if (!VA.isRegLoc())
2174             return false;
2175           if (!ArgLocs[++i].isRegLoc())
2176             return false;
2177           if (RegVT == MVT::v2f64) {
2178             if (!ArgLocs[++i].isRegLoc())
2179               return false;
2180             if (!ArgLocs[++i].isRegLoc())
2181               return false;
2182           }
2183         } else if (!VA.isRegLoc()) {
2184           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2185                                    MFI, MRI, TII))
2186             return false;
2187         }
2188       }
2189     }
2190   }
2191
2192   return true;
2193 }
2194
2195 bool
2196 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2197                                   MachineFunction &MF, bool isVarArg,
2198                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2199                                   LLVMContext &Context) const {
2200   SmallVector<CCValAssign, 16> RVLocs;
2201   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2202   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2203                                                     isVarArg));
2204 }
2205
2206 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2207                                     SDLoc DL, SelectionDAG &DAG) {
2208   const MachineFunction &MF = DAG.getMachineFunction();
2209   const Function *F = MF.getFunction();
2210
2211   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2212
2213   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2214   // version of the "preferred return address". These offsets affect the return
2215   // instruction if this is a return from PL1 without hypervisor extensions.
2216   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2217   //    SWI:     0      "subs pc, lr, #0"
2218   //    ABORT:   +4     "subs pc, lr, #4"
2219   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2220   // UNDEF varies depending on where the exception came from ARM or Thumb
2221   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2222
2223   int64_t LROffset;
2224   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2225       IntKind == "ABORT")
2226     LROffset = 4;
2227   else if (IntKind == "SWI" || IntKind == "UNDEF")
2228     LROffset = 0;
2229   else
2230     report_fatal_error("Unsupported interrupt attribute. If present, value "
2231                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2232
2233   RetOps.insert(RetOps.begin() + 1,
2234                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2235
2236   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2237 }
2238
2239 SDValue
2240 ARMTargetLowering::LowerReturn(SDValue Chain,
2241                                CallingConv::ID CallConv, bool isVarArg,
2242                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2243                                const SmallVectorImpl<SDValue> &OutVals,
2244                                SDLoc dl, SelectionDAG &DAG) const {
2245
2246   // CCValAssign - represent the assignment of the return value to a location.
2247   SmallVector<CCValAssign, 16> RVLocs;
2248
2249   // CCState - Info about the registers and stack slots.
2250   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2251                     *DAG.getContext(), Call);
2252
2253   // Analyze outgoing return values.
2254   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2255                                                isVarArg));
2256
2257   SDValue Flag;
2258   SmallVector<SDValue, 4> RetOps;
2259   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2260   bool isLittleEndian = Subtarget->isLittle();
2261
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2264   AFI->setReturnRegsCount(RVLocs.size());
2265
2266   // Copy the result values into the output registers.
2267   for (unsigned i = 0, realRVLocIdx = 0;
2268        i != RVLocs.size();
2269        ++i, ++realRVLocIdx) {
2270     CCValAssign &VA = RVLocs[i];
2271     assert(VA.isRegLoc() && "Can only return in registers!");
2272
2273     SDValue Arg = OutVals[realRVLocIdx];
2274
2275     switch (VA.getLocInfo()) {
2276     default: llvm_unreachable("Unknown loc info!");
2277     case CCValAssign::Full: break;
2278     case CCValAssign::BCvt:
2279       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2280       break;
2281     }
2282
2283     if (VA.needsCustom()) {
2284       if (VA.getLocVT() == MVT::v2f64) {
2285         // Extract the first half and return it in two registers.
2286         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2287                                    DAG.getConstant(0, dl, MVT::i32));
2288         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2289                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2290
2291         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2292                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2293                                  Flag);
2294         Flag = Chain.getValue(1);
2295         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2296         VA = RVLocs[++i]; // skip ahead to next loc
2297         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2298                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2299                                  Flag);
2300         Flag = Chain.getValue(1);
2301         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2302         VA = RVLocs[++i]; // skip ahead to next loc
2303
2304         // Extract the 2nd half and fall through to handle it as an f64 value.
2305         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2306                           DAG.getConstant(1, dl, MVT::i32));
2307       }
2308       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2309       // available.
2310       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2311                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2312       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2313                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2314                                Flag);
2315       Flag = Chain.getValue(1);
2316       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2317       VA = RVLocs[++i]; // skip ahead to next loc
2318       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2319                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2320                                Flag);
2321     } else
2322       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2323
2324     // Guarantee that all emitted copies are
2325     // stuck together, avoiding something bad.
2326     Flag = Chain.getValue(1);
2327     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2328   }
2329
2330   // Update chain and glue.
2331   RetOps[0] = Chain;
2332   if (Flag.getNode())
2333     RetOps.push_back(Flag);
2334
2335   // CPUs which aren't M-class use a special sequence to return from
2336   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2337   // though we use "subs pc, lr, #N").
2338   //
2339   // M-class CPUs actually use a normal return sequence with a special
2340   // (hardware-provided) value in LR, so the normal code path works.
2341   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2342       !Subtarget->isMClass()) {
2343     if (Subtarget->isThumb1Only())
2344       report_fatal_error("interrupt attribute is not supported in Thumb1");
2345     return LowerInterruptReturn(RetOps, dl, DAG);
2346   }
2347
2348   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2349 }
2350
2351 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2352   if (N->getNumValues() != 1)
2353     return false;
2354   if (!N->hasNUsesOfValue(1, 0))
2355     return false;
2356
2357   SDValue TCChain = Chain;
2358   SDNode *Copy = *N->use_begin();
2359   if (Copy->getOpcode() == ISD::CopyToReg) {
2360     // If the copy has a glue operand, we conservatively assume it isn't safe to
2361     // perform a tail call.
2362     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2363       return false;
2364     TCChain = Copy->getOperand(0);
2365   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2366     SDNode *VMov = Copy;
2367     // f64 returned in a pair of GPRs.
2368     SmallPtrSet<SDNode*, 2> Copies;
2369     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2370          UI != UE; ++UI) {
2371       if (UI->getOpcode() != ISD::CopyToReg)
2372         return false;
2373       Copies.insert(*UI);
2374     }
2375     if (Copies.size() > 2)
2376       return false;
2377
2378     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2379          UI != UE; ++UI) {
2380       SDValue UseChain = UI->getOperand(0);
2381       if (Copies.count(UseChain.getNode()))
2382         // Second CopyToReg
2383         Copy = *UI;
2384       else {
2385         // We are at the top of this chain.
2386         // If the copy has a glue operand, we conservatively assume it
2387         // isn't safe to perform a tail call.
2388         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2389           return false;
2390         // First CopyToReg
2391         TCChain = UseChain;
2392       }
2393     }
2394   } else if (Copy->getOpcode() == ISD::BITCAST) {
2395     // f32 returned in a single GPR.
2396     if (!Copy->hasOneUse())
2397       return false;
2398     Copy = *Copy->use_begin();
2399     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2400       return false;
2401     // If the copy has a glue operand, we conservatively assume it isn't safe to
2402     // perform a tail call.
2403     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2404       return false;
2405     TCChain = Copy->getOperand(0);
2406   } else {
2407     return false;
2408   }
2409
2410   bool HasRet = false;
2411   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2412        UI != UE; ++UI) {
2413     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2414         UI->getOpcode() != ARMISD::INTRET_FLAG)
2415       return false;
2416     HasRet = true;
2417   }
2418
2419   if (!HasRet)
2420     return false;
2421
2422   Chain = TCChain;
2423   return true;
2424 }
2425
2426 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2427   if (!Subtarget->supportsTailCall())
2428     return false;
2429
2430   auto Attr =
2431       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2432   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2433     return false;
2434
2435   return true;
2436 }
2437
2438 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2439 // and pass the lower and high parts through.
2440 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2441   SDLoc DL(Op);
2442   SDValue WriteValue = Op->getOperand(2);
2443
2444   // This function is only supposed to be called for i64 type argument.
2445   assert(WriteValue.getValueType() == MVT::i64
2446           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2447
2448   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2449                            DAG.getConstant(0, DL, MVT::i32));
2450   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2451                            DAG.getConstant(1, DL, MVT::i32));
2452   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2453   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2454 }
2455
2456 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2457 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2458 // one of the above mentioned nodes. It has to be wrapped because otherwise
2459 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2460 // be used to form addressing mode. These wrapped nodes will be selected
2461 // into MOVi.
2462 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2463   EVT PtrVT = Op.getValueType();
2464   // FIXME there is no actual debug info here
2465   SDLoc dl(Op);
2466   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2467   SDValue Res;
2468   if (CP->isMachineConstantPoolEntry())
2469     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2470                                     CP->getAlignment());
2471   else
2472     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2473                                     CP->getAlignment());
2474   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2475 }
2476
2477 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2478   return MachineJumpTableInfo::EK_Inline;
2479 }
2480
2481 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2482                                              SelectionDAG &DAG) const {
2483   MachineFunction &MF = DAG.getMachineFunction();
2484   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2485   unsigned ARMPCLabelIndex = 0;
2486   SDLoc DL(Op);
2487   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2488   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2489   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2490   SDValue CPAddr;
2491   if (RelocM == Reloc::Static) {
2492     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2493   } else {
2494     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2495     ARMPCLabelIndex = AFI->createPICLabelUId();
2496     ARMConstantPoolValue *CPV =
2497       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2498                                       ARMCP::CPBlockAddress, PCAdj);
2499     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2500   }
2501   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2502   SDValue Result =
2503       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2504                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2505                   false, false, false, 0);
2506   if (RelocM == Reloc::Static)
2507     return Result;
2508   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2509   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2510 }
2511
2512 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2513 SDValue
2514 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2515                                                  SelectionDAG &DAG) const {
2516   SDLoc dl(GA);
2517   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2518   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2519   MachineFunction &MF = DAG.getMachineFunction();
2520   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2521   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2522   ARMConstantPoolValue *CPV =
2523     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2524                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2525   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2526   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2527   Argument =
2528       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2529                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2530                   false, false, false, 0);
2531   SDValue Chain = Argument.getValue(1);
2532
2533   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2534   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2535
2536   // call __tls_get_addr.
2537   ArgListTy Args;
2538   ArgListEntry Entry;
2539   Entry.Node = Argument;
2540   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2541   Args.push_back(Entry);
2542
2543   // FIXME: is there useful debug info available here?
2544   TargetLowering::CallLoweringInfo CLI(DAG);
2545   CLI.setDebugLoc(dl).setChain(Chain)
2546     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2547                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2548                0);
2549
2550   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2551   return CallResult.first;
2552 }
2553
2554 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2555 // "local exec" model.
2556 SDValue
2557 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2558                                         SelectionDAG &DAG,
2559                                         TLSModel::Model model) const {
2560   const GlobalValue *GV = GA->getGlobal();
2561   SDLoc dl(GA);
2562   SDValue Offset;
2563   SDValue Chain = DAG.getEntryNode();
2564   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2565   // Get the Thread Pointer
2566   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2567
2568   if (model == TLSModel::InitialExec) {
2569     MachineFunction &MF = DAG.getMachineFunction();
2570     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2571     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2572     // Initial exec model.
2573     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2574     ARMConstantPoolValue *CPV =
2575       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2576                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2577                                       true);
2578     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2579     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2580     Offset = DAG.getLoad(
2581         PtrVT, dl, Chain, Offset,
2582         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2583         false, false, 0);
2584     Chain = Offset.getValue(1);
2585
2586     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2587     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2588
2589     Offset = DAG.getLoad(
2590         PtrVT, dl, Chain, Offset,
2591         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2592         false, false, 0);
2593   } else {
2594     // local exec model
2595     assert(model == TLSModel::LocalExec);
2596     ARMConstantPoolValue *CPV =
2597       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2598     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2599     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2600     Offset = DAG.getLoad(
2601         PtrVT, dl, Chain, Offset,
2602         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2603         false, false, 0);
2604   }
2605
2606   // The address of the thread local variable is the add of the thread
2607   // pointer with the offset of the variable.
2608   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2609 }
2610
2611 SDValue
2612 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2613   // TODO: implement the "local dynamic" model
2614   assert(Subtarget->isTargetELF() &&
2615          "TLS not implemented for non-ELF targets");
2616   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2617   if (DAG.getTarget().Options.EmulatedTLS)
2618     return LowerToTLSEmulatedModel(GA, DAG);
2619
2620   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2621
2622   switch (model) {
2623     case TLSModel::GeneralDynamic:
2624     case TLSModel::LocalDynamic:
2625       return LowerToTLSGeneralDynamicModel(GA, DAG);
2626     case TLSModel::InitialExec:
2627     case TLSModel::LocalExec:
2628       return LowerToTLSExecModels(GA, DAG, model);
2629   }
2630   llvm_unreachable("bogus TLS model");
2631 }
2632
2633 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2634                                                  SelectionDAG &DAG) const {
2635   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2636   SDLoc dl(Op);
2637   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2638   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2639     bool UseGOT_PREL =
2640         !(GV->hasHiddenVisibility() || GV->isStrongDefinitionForLinker());
2641
2642     MachineFunction &MF = DAG.getMachineFunction();
2643     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2644     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2645     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2646     SDLoc dl(Op);
2647     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2648     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2649         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2650         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2651         /*AddCurrentAddress=*/UseGOT_PREL);
2652     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2653     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2654     SDValue Result = DAG.getLoad(
2655         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2656         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2657         false, false, 0);
2658     SDValue Chain = Result.getValue(1);
2659     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2660     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2661     if (UseGOT_PREL)
2662       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2663                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2664                            false, false, false, 0);
2665     return Result;
2666   }
2667
2668   // If we have T2 ops, we can materialize the address directly via movt/movw
2669   // pair. This is always cheaper.
2670   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2671     ++NumMovwMovt;
2672     // FIXME: Once remat is capable of dealing with instructions with register
2673     // operands, expand this into two nodes.
2674     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2675                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2676   } else {
2677     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2678     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2679     return DAG.getLoad(
2680         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2681         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2682         false, false, 0);
2683   }
2684 }
2685
2686 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2687                                                     SelectionDAG &DAG) const {
2688   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2689   SDLoc dl(Op);
2690   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2691   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2692
2693   if (Subtarget->useMovt(DAG.getMachineFunction()))
2694     ++NumMovwMovt;
2695
2696   // FIXME: Once remat is capable of dealing with instructions with register
2697   // operands, expand this into multiple nodes
2698   unsigned Wrapper =
2699       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2700
2701   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2702   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2703
2704   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2705     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2706                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2707                          false, false, false, 0);
2708   return Result;
2709 }
2710
2711 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2712                                                      SelectionDAG &DAG) const {
2713   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2714   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2715          "Windows on ARM expects to use movw/movt");
2716
2717   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2718   const ARMII::TOF TargetFlags =
2719     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2720   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721   SDValue Result;
2722   SDLoc DL(Op);
2723
2724   ++NumMovwMovt;
2725
2726   // FIXME: Once remat is capable of dealing with instructions with register
2727   // operands, expand this into two nodes.
2728   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2729                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2730                                                   TargetFlags));
2731   if (GV->hasDLLImportStorageClass())
2732     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2733                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2734                          false, false, false, 0);
2735   return Result;
2736 }
2737
2738 SDValue
2739 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2740   SDLoc dl(Op);
2741   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2742   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2743                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2744                      Op.getOperand(1), Val);
2745 }
2746
2747 SDValue
2748 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2749   SDLoc dl(Op);
2750   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2751                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2752 }
2753
2754 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2755                                                       SelectionDAG &DAG) const {
2756   SDLoc dl(Op);
2757   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2758                      Op.getOperand(0));
2759 }
2760
2761 SDValue
2762 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2763                                           const ARMSubtarget *Subtarget) const {
2764   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2765   SDLoc dl(Op);
2766   switch (IntNo) {
2767   default: return SDValue();    // Don't custom lower most intrinsics.
2768   case Intrinsic::arm_rbit: {
2769     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2770            "RBIT intrinsic must have i32 type!");
2771     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2772   }
2773   case Intrinsic::arm_thread_pointer: {
2774     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2775     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2776   }
2777   case Intrinsic::eh_sjlj_lsda: {
2778     MachineFunction &MF = DAG.getMachineFunction();
2779     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2780     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2781     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2782     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2783     SDValue CPAddr;
2784     unsigned PCAdj = (RelocM != Reloc::PIC_)
2785       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2786     ARMConstantPoolValue *CPV =
2787       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2788                                       ARMCP::CPLSDA, PCAdj);
2789     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2790     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2791     SDValue Result = DAG.getLoad(
2792         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2793         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2794         false, false, 0);
2795
2796     if (RelocM == Reloc::PIC_) {
2797       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2798       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2799     }
2800     return Result;
2801   }
2802   case Intrinsic::arm_neon_vmulls:
2803   case Intrinsic::arm_neon_vmullu: {
2804     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2805       ? ARMISD::VMULLs : ARMISD::VMULLu;
2806     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2807                        Op.getOperand(1), Op.getOperand(2));
2808   }
2809   case Intrinsic::arm_neon_vminnm:
2810   case Intrinsic::arm_neon_vmaxnm: {
2811     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2812       ? ISD::FMINNUM : ISD::FMAXNUM;
2813     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2814                        Op.getOperand(1), Op.getOperand(2));
2815   }
2816   case Intrinsic::arm_neon_vminu:
2817   case Intrinsic::arm_neon_vmaxu: {
2818     if (Op.getValueType().isFloatingPoint())
2819       return SDValue();
2820     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2821       ? ISD::UMIN : ISD::UMAX;
2822     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2823                          Op.getOperand(1), Op.getOperand(2));
2824   }
2825   case Intrinsic::arm_neon_vmins:
2826   case Intrinsic::arm_neon_vmaxs: {
2827     // v{min,max}s is overloaded between signed integers and floats.
2828     if (!Op.getValueType().isFloatingPoint()) {
2829       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2830         ? ISD::SMIN : ISD::SMAX;
2831       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2832                          Op.getOperand(1), Op.getOperand(2));
2833     }
2834     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2835       ? ISD::FMINNAN : ISD::FMAXNAN;
2836     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2837                        Op.getOperand(1), Op.getOperand(2));
2838   }
2839   }
2840 }
2841
2842 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2843                                  const ARMSubtarget *Subtarget) {
2844   // FIXME: handle "fence singlethread" more efficiently.
2845   SDLoc dl(Op);
2846   if (!Subtarget->hasDataBarrier()) {
2847     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2848     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2849     // here.
2850     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2851            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2852     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2853                        DAG.getConstant(0, dl, MVT::i32));
2854   }
2855
2856   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2857   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2858   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2859   if (Subtarget->isMClass()) {
2860     // Only a full system barrier exists in the M-class architectures.
2861     Domain = ARM_MB::SY;
2862   } else if (Subtarget->isSwift() && Ord == Release) {
2863     // Swift happens to implement ISHST barriers in a way that's compatible with
2864     // Release semantics but weaker than ISH so we'd be fools not to use
2865     // it. Beware: other processors probably don't!
2866     Domain = ARM_MB::ISHST;
2867   }
2868
2869   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2870                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2871                      DAG.getConstant(Domain, dl, MVT::i32));
2872 }
2873
2874 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2875                              const ARMSubtarget *Subtarget) {
2876   // ARM pre v5TE and Thumb1 does not have preload instructions.
2877   if (!(Subtarget->isThumb2() ||
2878         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2879     // Just preserve the chain.
2880     return Op.getOperand(0);
2881
2882   SDLoc dl(Op);
2883   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2884   if (!isRead &&
2885       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2886     // ARMv7 with MP extension has PLDW.
2887     return Op.getOperand(0);
2888
2889   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2890   if (Subtarget->isThumb()) {
2891     // Invert the bits.
2892     isRead = ~isRead & 1;
2893     isData = ~isData & 1;
2894   }
2895
2896   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2897                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2898                      DAG.getConstant(isData, dl, MVT::i32));
2899 }
2900
2901 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2902   MachineFunction &MF = DAG.getMachineFunction();
2903   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2904
2905   // vastart just stores the address of the VarArgsFrameIndex slot into the
2906   // memory location argument.
2907   SDLoc dl(Op);
2908   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2909   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2910   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2911   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2912                       MachinePointerInfo(SV), false, false, 0);
2913 }
2914
2915 SDValue
2916 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2917                                         SDValue &Root, SelectionDAG &DAG,
2918                                         SDLoc dl) const {
2919   MachineFunction &MF = DAG.getMachineFunction();
2920   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2921
2922   const TargetRegisterClass *RC;
2923   if (AFI->isThumb1OnlyFunction())
2924     RC = &ARM::tGPRRegClass;
2925   else
2926     RC = &ARM::GPRRegClass;
2927
2928   // Transform the arguments stored in physical registers into virtual ones.
2929   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2930   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2931
2932   SDValue ArgValue2;
2933   if (NextVA.isMemLoc()) {
2934     MachineFrameInfo *MFI = MF.getFrameInfo();
2935     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2936
2937     // Create load node to retrieve arguments from the stack.
2938     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2939     ArgValue2 = DAG.getLoad(
2940         MVT::i32, dl, Root, FIN,
2941         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2942         false, false, 0);
2943   } else {
2944     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2945     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2946   }
2947   if (!Subtarget->isLittle())
2948     std::swap (ArgValue, ArgValue2);
2949   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2950 }
2951
2952 // The remaining GPRs hold either the beginning of variable-argument
2953 // data, or the beginning of an aggregate passed by value (usually
2954 // byval).  Either way, we allocate stack slots adjacent to the data
2955 // provided by our caller, and store the unallocated registers there.
2956 // If this is a variadic function, the va_list pointer will begin with
2957 // these values; otherwise, this reassembles a (byval) structure that
2958 // was split between registers and memory.
2959 // Return: The frame index registers were stored into.
2960 int
2961 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2962                                   SDLoc dl, SDValue &Chain,
2963                                   const Value *OrigArg,
2964                                   unsigned InRegsParamRecordIdx,
2965                                   int ArgOffset,
2966                                   unsigned ArgSize) const {
2967   // Currently, two use-cases possible:
2968   // Case #1. Non-var-args function, and we meet first byval parameter.
2969   //          Setup first unallocated register as first byval register;
2970   //          eat all remained registers
2971   //          (these two actions are performed by HandleByVal method).
2972   //          Then, here, we initialize stack frame with
2973   //          "store-reg" instructions.
2974   // Case #2. Var-args function, that doesn't contain byval parameters.
2975   //          The same: eat all remained unallocated registers,
2976   //          initialize stack frame.
2977
2978   MachineFunction &MF = DAG.getMachineFunction();
2979   MachineFrameInfo *MFI = MF.getFrameInfo();
2980   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2981   unsigned RBegin, REnd;
2982   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2983     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2984   } else {
2985     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2986     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2987     REnd = ARM::R4;
2988   }
2989
2990   if (REnd != RBegin)
2991     ArgOffset = -4 * (ARM::R4 - RBegin);
2992
2993   auto PtrVT = getPointerTy(DAG.getDataLayout());
2994   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2995   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2996
2997   SmallVector<SDValue, 4> MemOps;
2998   const TargetRegisterClass *RC =
2999       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3000
3001   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3002     unsigned VReg = MF.addLiveIn(Reg, RC);
3003     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3004     SDValue Store =
3005         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3006                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3007     MemOps.push_back(Store);
3008     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3009   }
3010
3011   if (!MemOps.empty())
3012     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3013   return FrameIndex;
3014 }
3015
3016 // Setup stack frame, the va_list pointer will start from.
3017 void
3018 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3019                                         SDLoc dl, SDValue &Chain,
3020                                         unsigned ArgOffset,
3021                                         unsigned TotalArgRegsSaveSize,
3022                                         bool ForceMutable) const {
3023   MachineFunction &MF = DAG.getMachineFunction();
3024   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3025
3026   // Try to store any remaining integer argument regs
3027   // to their spots on the stack so that they may be loaded by deferencing
3028   // the result of va_next.
3029   // If there is no regs to be stored, just point address after last
3030   // argument passed via stack.
3031   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3032                                   CCInfo.getInRegsParamsCount(),
3033                                   CCInfo.getNextStackOffset(), 4);
3034   AFI->setVarArgsFrameIndex(FrameIndex);
3035 }
3036
3037 SDValue
3038 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3039                                         CallingConv::ID CallConv, bool isVarArg,
3040                                         const SmallVectorImpl<ISD::InputArg>
3041                                           &Ins,
3042                                         SDLoc dl, SelectionDAG &DAG,
3043                                         SmallVectorImpl<SDValue> &InVals)
3044                                           const {
3045   MachineFunction &MF = DAG.getMachineFunction();
3046   MachineFrameInfo *MFI = MF.getFrameInfo();
3047
3048   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3049
3050   // Assign locations to all of the incoming arguments.
3051   SmallVector<CCValAssign, 16> ArgLocs;
3052   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3053                     *DAG.getContext(), Prologue);
3054   CCInfo.AnalyzeFormalArguments(Ins,
3055                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3056                                                   isVarArg));
3057
3058   SmallVector<SDValue, 16> ArgValues;
3059   SDValue ArgValue;
3060   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3061   unsigned CurArgIdx = 0;
3062
3063   // Initially ArgRegsSaveSize is zero.
3064   // Then we increase this value each time we meet byval parameter.
3065   // We also increase this value in case of varargs function.
3066   AFI->setArgRegsSaveSize(0);
3067
3068   // Calculate the amount of stack space that we need to allocate to store
3069   // byval and variadic arguments that are passed in registers.
3070   // We need to know this before we allocate the first byval or variadic
3071   // argument, as they will be allocated a stack slot below the CFA (Canonical
3072   // Frame Address, the stack pointer at entry to the function).
3073   unsigned ArgRegBegin = ARM::R4;
3074   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3075     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3076       break;
3077
3078     CCValAssign &VA = ArgLocs[i];
3079     unsigned Index = VA.getValNo();
3080     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3081     if (!Flags.isByVal())
3082       continue;
3083
3084     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3085     unsigned RBegin, REnd;
3086     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3087     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3088
3089     CCInfo.nextInRegsParam();
3090   }
3091   CCInfo.rewindByValRegsInfo();
3092
3093   int lastInsIndex = -1;
3094   if (isVarArg && MFI->hasVAStart()) {
3095     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3096     if (RegIdx != array_lengthof(GPRArgRegs))
3097       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3098   }
3099
3100   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3101   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3102   auto PtrVT = getPointerTy(DAG.getDataLayout());
3103
3104   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3105     CCValAssign &VA = ArgLocs[i];
3106     if (Ins[VA.getValNo()].isOrigArg()) {
3107       std::advance(CurOrigArg,
3108                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3109       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3110     }
3111     // Arguments stored in registers.
3112     if (VA.isRegLoc()) {
3113       EVT RegVT = VA.getLocVT();
3114
3115       if (VA.needsCustom()) {
3116         // f64 and vector types are split up into multiple registers or
3117         // combinations of registers and stack slots.
3118         if (VA.getLocVT() == MVT::v2f64) {
3119           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3120                                                    Chain, DAG, dl);
3121           VA = ArgLocs[++i]; // skip ahead to next loc
3122           SDValue ArgValue2;
3123           if (VA.isMemLoc()) {
3124             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3125             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3126             ArgValue2 = DAG.getLoad(
3127                 MVT::f64, dl, Chain, FIN,
3128                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3129                 false, false, false, 0);
3130           } else {
3131             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3132                                              Chain, DAG, dl);
3133           }
3134           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3135           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3136                                  ArgValue, ArgValue1,
3137                                  DAG.getIntPtrConstant(0, dl));
3138           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3139                                  ArgValue, ArgValue2,
3140                                  DAG.getIntPtrConstant(1, dl));
3141         } else
3142           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3143
3144       } else {
3145         const TargetRegisterClass *RC;
3146
3147         if (RegVT == MVT::f32)
3148           RC = &ARM::SPRRegClass;
3149         else if (RegVT == MVT::f64)
3150           RC = &ARM::DPRRegClass;
3151         else if (RegVT == MVT::v2f64)
3152           RC = &ARM::QPRRegClass;
3153         else if (RegVT == MVT::i32)
3154           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3155                                            : &ARM::GPRRegClass;
3156         else
3157           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3158
3159         // Transform the arguments in physical registers into virtual ones.
3160         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3161         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3162       }
3163
3164       // If this is an 8 or 16-bit value, it is really passed promoted
3165       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3166       // truncate to the right size.
3167       switch (VA.getLocInfo()) {
3168       default: llvm_unreachable("Unknown loc info!");
3169       case CCValAssign::Full: break;
3170       case CCValAssign::BCvt:
3171         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3172         break;
3173       case CCValAssign::SExt:
3174         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3175                                DAG.getValueType(VA.getValVT()));
3176         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3177         break;
3178       case CCValAssign::ZExt:
3179         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3180                                DAG.getValueType(VA.getValVT()));
3181         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3182         break;
3183       }
3184
3185       InVals.push_back(ArgValue);
3186
3187     } else { // VA.isRegLoc()
3188
3189       // sanity check
3190       assert(VA.isMemLoc());
3191       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3192
3193       int index = VA.getValNo();
3194
3195       // Some Ins[] entries become multiple ArgLoc[] entries.
3196       // Process them only once.
3197       if (index != lastInsIndex)
3198         {
3199           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3200           // FIXME: For now, all byval parameter objects are marked mutable.
3201           // This can be changed with more analysis.
3202           // In case of tail call optimization mark all arguments mutable.
3203           // Since they could be overwritten by lowering of arguments in case of
3204           // a tail call.
3205           if (Flags.isByVal()) {
3206             assert(Ins[index].isOrigArg() &&
3207                    "Byval arguments cannot be implicit");
3208             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3209
3210             int FrameIndex = StoreByValRegs(
3211                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3212                 VA.getLocMemOffset(), Flags.getByValSize());
3213             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3214             CCInfo.nextInRegsParam();
3215           } else {
3216             unsigned FIOffset = VA.getLocMemOffset();
3217             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3218                                             FIOffset, true);
3219
3220             // Create load nodes to retrieve arguments from the stack.
3221             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3222             InVals.push_back(DAG.getLoad(
3223                 VA.getValVT(), dl, Chain, FIN,
3224                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3225                 false, false, false, 0));
3226           }
3227           lastInsIndex = index;
3228         }
3229     }
3230   }
3231
3232   // varargs
3233   if (isVarArg && MFI->hasVAStart())
3234     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3235                          CCInfo.getNextStackOffset(),
3236                          TotalArgRegsSaveSize);
3237
3238   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3239
3240   return Chain;
3241 }
3242
3243 /// isFloatingPointZero - Return true if this is +0.0.
3244 static bool isFloatingPointZero(SDValue Op) {
3245   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3246     return CFP->getValueAPF().isPosZero();
3247   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3248     // Maybe this has already been legalized into the constant pool?
3249     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3250       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3251       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3252         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3253           return CFP->getValueAPF().isPosZero();
3254     }
3255   } else if (Op->getOpcode() == ISD::BITCAST &&
3256              Op->getValueType(0) == MVT::f64) {
3257     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3258     // created by LowerConstantFP().
3259     SDValue BitcastOp = Op->getOperand(0);
3260     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3261       SDValue MoveOp = BitcastOp->getOperand(0);
3262       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3263           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3264         return true;
3265       }
3266     }
3267   }
3268   return false;
3269 }
3270
3271 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3272 /// the given operands.
3273 SDValue
3274 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3275                              SDValue &ARMcc, SelectionDAG &DAG,
3276                              SDLoc dl) const {
3277   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3278     unsigned C = RHSC->getZExtValue();
3279     if (!isLegalICmpImmediate(C)) {
3280       // Constant does not fit, try adjusting it by one?
3281       switch (CC) {
3282       default: break;
3283       case ISD::SETLT:
3284       case ISD::SETGE:
3285         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3286           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3287           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3288         }
3289         break;
3290       case ISD::SETULT:
3291       case ISD::SETUGE:
3292         if (C != 0 && isLegalICmpImmediate(C-1)) {
3293           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3294           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3295         }
3296         break;
3297       case ISD::SETLE:
3298       case ISD::SETGT:
3299         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3300           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3301           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3302         }
3303         break;
3304       case ISD::SETULE:
3305       case ISD::SETUGT:
3306         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3307           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3308           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3309         }
3310         break;
3311       }
3312     }
3313   }
3314
3315   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3316   ARMISD::NodeType CompareType;
3317   switch (CondCode) {
3318   default:
3319     CompareType = ARMISD::CMP;
3320     break;
3321   case ARMCC::EQ:
3322   case ARMCC::NE:
3323     // Uses only Z Flag
3324     CompareType = ARMISD::CMPZ;
3325     break;
3326   }
3327   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3328   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3329 }
3330
3331 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3332 SDValue
3333 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3334                              SDLoc dl) const {
3335   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3336   SDValue Cmp;
3337   if (!isFloatingPointZero(RHS))
3338     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3339   else
3340     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3341   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3342 }
3343
3344 /// duplicateCmp - Glue values can have only one use, so this function
3345 /// duplicates a comparison node.
3346 SDValue
3347 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3348   unsigned Opc = Cmp.getOpcode();
3349   SDLoc DL(Cmp);
3350   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3351     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3352
3353   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3354   Cmp = Cmp.getOperand(0);
3355   Opc = Cmp.getOpcode();
3356   if (Opc == ARMISD::CMPFP)
3357     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3358   else {
3359     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3360     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3361   }
3362   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3363 }
3364
3365 std::pair<SDValue, SDValue>
3366 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3367                                  SDValue &ARMcc) const {
3368   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3369
3370   SDValue Value, OverflowCmp;
3371   SDValue LHS = Op.getOperand(0);
3372   SDValue RHS = Op.getOperand(1);
3373   SDLoc dl(Op);
3374
3375   // FIXME: We are currently always generating CMPs because we don't support
3376   // generating CMN through the backend. This is not as good as the natural
3377   // CMP case because it causes a register dependency and cannot be folded
3378   // later.
3379
3380   switch (Op.getOpcode()) {
3381   default:
3382     llvm_unreachable("Unknown overflow instruction!");
3383   case ISD::SADDO:
3384     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3385     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3386     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3387     break;
3388   case ISD::UADDO:
3389     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3390     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3391     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3392     break;
3393   case ISD::SSUBO:
3394     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3395     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3396     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3397     break;
3398   case ISD::USUBO:
3399     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3400     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3401     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3402     break;
3403   } // switch (...)
3404
3405   return std::make_pair(Value, OverflowCmp);
3406 }
3407
3408
3409 SDValue
3410 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3411   // Let legalize expand this if it isn't a legal type yet.
3412   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3413     return SDValue();
3414
3415   SDValue Value, OverflowCmp;
3416   SDValue ARMcc;
3417   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3418   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3419   SDLoc dl(Op);
3420   // We use 0 and 1 as false and true values.
3421   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3422   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3423   EVT VT = Op.getValueType();
3424
3425   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3426                                  ARMcc, CCR, OverflowCmp);
3427
3428   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3429   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3430 }
3431
3432
3433 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3434   SDValue Cond = Op.getOperand(0);
3435   SDValue SelectTrue = Op.getOperand(1);
3436   SDValue SelectFalse = Op.getOperand(2);
3437   SDLoc dl(Op);
3438   unsigned Opc = Cond.getOpcode();
3439
3440   if (Cond.getResNo() == 1 &&
3441       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3442        Opc == ISD::USUBO)) {
3443     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3444       return SDValue();
3445
3446     SDValue Value, OverflowCmp;
3447     SDValue ARMcc;
3448     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3449     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3450     EVT VT = Op.getValueType();
3451
3452     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3453                    OverflowCmp, DAG);
3454   }
3455
3456   // Convert:
3457   //
3458   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3459   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3460   //
3461   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3462     const ConstantSDNode *CMOVTrue =
3463       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3464     const ConstantSDNode *CMOVFalse =
3465       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3466
3467     if (CMOVTrue && CMOVFalse) {
3468       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3469       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3470
3471       SDValue True;
3472       SDValue False;
3473       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3474         True = SelectTrue;
3475         False = SelectFalse;
3476       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3477         True = SelectFalse;
3478         False = SelectTrue;
3479       }
3480
3481       if (True.getNode() && False.getNode()) {
3482         EVT VT = Op.getValueType();
3483         SDValue ARMcc = Cond.getOperand(2);
3484         SDValue CCR = Cond.getOperand(3);
3485         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3486         assert(True.getValueType() == VT);
3487         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3488       }
3489     }
3490   }
3491
3492   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3493   // undefined bits before doing a full-word comparison with zero.
3494   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3495                      DAG.getConstant(1, dl, Cond.getValueType()));
3496
3497   return DAG.getSelectCC(dl, Cond,
3498                          DAG.getConstant(0, dl, Cond.getValueType()),
3499                          SelectTrue, SelectFalse, ISD::SETNE);
3500 }
3501
3502 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3503                                  bool &swpCmpOps, bool &swpVselOps) {
3504   // Start by selecting the GE condition code for opcodes that return true for
3505   // 'equality'
3506   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3507       CC == ISD::SETULE)
3508     CondCode = ARMCC::GE;
3509
3510   // and GT for opcodes that return false for 'equality'.
3511   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3512            CC == ISD::SETULT)
3513     CondCode = ARMCC::GT;
3514
3515   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3516   // to swap the compare operands.
3517   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3518       CC == ISD::SETULT)
3519     swpCmpOps = true;
3520
3521   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3522   // If we have an unordered opcode, we need to swap the operands to the VSEL
3523   // instruction (effectively negating the condition).
3524   //
3525   // This also has the effect of swapping which one of 'less' or 'greater'
3526   // returns true, so we also swap the compare operands. It also switches
3527   // whether we return true for 'equality', so we compensate by picking the
3528   // opposite condition code to our original choice.
3529   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3530       CC == ISD::SETUGT) {
3531     swpCmpOps = !swpCmpOps;
3532     swpVselOps = !swpVselOps;
3533     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3534   }
3535
3536   // 'ordered' is 'anything but unordered', so use the VS condition code and
3537   // swap the VSEL operands.
3538   if (CC == ISD::SETO) {
3539     CondCode = ARMCC::VS;
3540     swpVselOps = true;
3541   }
3542
3543   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3544   // code and swap the VSEL operands.
3545   if (CC == ISD::SETUNE) {
3546     CondCode = ARMCC::EQ;
3547     swpVselOps = true;
3548   }
3549 }
3550
3551 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3552                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3553                                    SDValue Cmp, SelectionDAG &DAG) const {
3554   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3555     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3556                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3557     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3558                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3559
3560     SDValue TrueLow = TrueVal.getValue(0);
3561     SDValue TrueHigh = TrueVal.getValue(1);
3562     SDValue FalseLow = FalseVal.getValue(0);
3563     SDValue FalseHigh = FalseVal.getValue(1);
3564
3565     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3566                               ARMcc, CCR, Cmp);
3567     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3568                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3569
3570     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3571   } else {
3572     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3573                        Cmp);
3574   }
3575 }
3576
3577 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3578   EVT VT = Op.getValueType();
3579   SDValue LHS = Op.getOperand(0);
3580   SDValue RHS = Op.getOperand(1);
3581   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3582   SDValue TrueVal = Op.getOperand(2);
3583   SDValue FalseVal = Op.getOperand(3);
3584   SDLoc dl(Op);
3585
3586   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3587     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3588                                                     dl);
3589
3590     // If softenSetCCOperands only returned one value, we should compare it to
3591     // zero.
3592     if (!RHS.getNode()) {
3593       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3594       CC = ISD::SETNE;
3595     }
3596   }
3597
3598   if (LHS.getValueType() == MVT::i32) {
3599     // Try to generate VSEL on ARMv8.
3600     // The VSEL instruction can't use all the usual ARM condition
3601     // codes: it only has two bits to select the condition code, so it's
3602     // constrained to use only GE, GT, VS and EQ.
3603     //
3604     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3605     // swap the operands of the previous compare instruction (effectively
3606     // inverting the compare condition, swapping 'less' and 'greater') and
3607     // sometimes need to swap the operands to the VSEL (which inverts the
3608     // condition in the sense of firing whenever the previous condition didn't)
3609     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3610                                     TrueVal.getValueType() == MVT::f64)) {
3611       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3612       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3613           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3614         CC = ISD::getSetCCInverse(CC, true);
3615         std::swap(TrueVal, FalseVal);
3616       }
3617     }
3618
3619     SDValue ARMcc;
3620     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3621     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3622     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3623   }
3624
3625   ARMCC::CondCodes CondCode, CondCode2;
3626   FPCCToARMCC(CC, CondCode, CondCode2);
3627
3628   // Try to generate VMAXNM/VMINNM on ARMv8.
3629   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3630                                   TrueVal.getValueType() == MVT::f64)) {
3631     bool swpCmpOps = false;
3632     bool swpVselOps = false;
3633     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3634
3635     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3636         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3637       if (swpCmpOps)
3638         std::swap(LHS, RHS);
3639       if (swpVselOps)
3640         std::swap(TrueVal, FalseVal);
3641     }
3642   }
3643
3644   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3645   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3646   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3647   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3648   if (CondCode2 != ARMCC::AL) {
3649     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3650     // FIXME: Needs another CMP because flag can have but one use.
3651     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3652     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3653   }
3654   return Result;
3655 }
3656
3657 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3658 /// to morph to an integer compare sequence.
3659 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3660                            const ARMSubtarget *Subtarget) {
3661   SDNode *N = Op.getNode();
3662   if (!N->hasOneUse())
3663     // Otherwise it requires moving the value from fp to integer registers.
3664     return false;
3665   if (!N->getNumValues())
3666     return false;
3667   EVT VT = Op.getValueType();
3668   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3669     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3670     // vmrs are very slow, e.g. cortex-a8.
3671     return false;
3672
3673   if (isFloatingPointZero(Op)) {
3674     SeenZero = true;
3675     return true;
3676   }
3677   return ISD::isNormalLoad(N);
3678 }
3679
3680 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3681   if (isFloatingPointZero(Op))
3682     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3683
3684   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3685     return DAG.getLoad(MVT::i32, SDLoc(Op),
3686                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3687                        Ld->isVolatile(), Ld->isNonTemporal(),
3688                        Ld->isInvariant(), Ld->getAlignment());
3689
3690   llvm_unreachable("Unknown VFP cmp argument!");
3691 }
3692
3693 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3694                            SDValue &RetVal1, SDValue &RetVal2) {
3695   SDLoc dl(Op);
3696
3697   if (isFloatingPointZero(Op)) {
3698     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3699     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3700     return;
3701   }
3702
3703   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3704     SDValue Ptr = Ld->getBasePtr();
3705     RetVal1 = DAG.getLoad(MVT::i32, dl,
3706                           Ld->getChain(), Ptr,
3707                           Ld->getPointerInfo(),
3708                           Ld->isVolatile(), Ld->isNonTemporal(),
3709                           Ld->isInvariant(), Ld->getAlignment());
3710
3711     EVT PtrType = Ptr.getValueType();
3712     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3713     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3714                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3715     RetVal2 = DAG.getLoad(MVT::i32, dl,
3716                           Ld->getChain(), NewPtr,
3717                           Ld->getPointerInfo().getWithOffset(4),
3718                           Ld->isVolatile(), Ld->isNonTemporal(),
3719                           Ld->isInvariant(), NewAlign);
3720     return;
3721   }
3722
3723   llvm_unreachable("Unknown VFP cmp argument!");
3724 }
3725
3726 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3727 /// f32 and even f64 comparisons to integer ones.
3728 SDValue
3729 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3730   SDValue Chain = Op.getOperand(0);
3731   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3732   SDValue LHS = Op.getOperand(2);
3733   SDValue RHS = Op.getOperand(3);
3734   SDValue Dest = Op.getOperand(4);
3735   SDLoc dl(Op);
3736
3737   bool LHSSeenZero = false;
3738   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3739   bool RHSSeenZero = false;
3740   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3741   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3742     // If unsafe fp math optimization is enabled and there are no other uses of
3743     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3744     // to an integer comparison.
3745     if (CC == ISD::SETOEQ)
3746       CC = ISD::SETEQ;
3747     else if (CC == ISD::SETUNE)
3748       CC = ISD::SETNE;
3749
3750     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3751     SDValue ARMcc;
3752     if (LHS.getValueType() == MVT::f32) {
3753       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3754                         bitcastf32Toi32(LHS, DAG), Mask);
3755       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3756                         bitcastf32Toi32(RHS, DAG), Mask);
3757       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3758       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3759       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3760                          Chain, Dest, ARMcc, CCR, Cmp);
3761     }
3762
3763     SDValue LHS1, LHS2;
3764     SDValue RHS1, RHS2;
3765     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3766     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3767     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3768     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3769     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3770     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3771     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3772     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3773     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3774   }
3775
3776   return SDValue();
3777 }
3778
3779 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3780   SDValue Chain = Op.getOperand(0);
3781   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3782   SDValue LHS = Op.getOperand(2);
3783   SDValue RHS = Op.getOperand(3);
3784   SDValue Dest = Op.getOperand(4);
3785   SDLoc dl(Op);
3786
3787   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3788     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3789                                                     dl);
3790
3791     // If softenSetCCOperands only returned one value, we should compare it to
3792     // zero.
3793     if (!RHS.getNode()) {
3794       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3795       CC = ISD::SETNE;
3796     }
3797   }
3798
3799   if (LHS.getValueType() == MVT::i32) {
3800     SDValue ARMcc;
3801     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3802     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3803     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3804                        Chain, Dest, ARMcc, CCR, Cmp);
3805   }
3806
3807   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3808
3809   if (getTargetMachine().Options.UnsafeFPMath &&
3810       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3811        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3812     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3813     if (Result.getNode())
3814       return Result;
3815   }
3816
3817   ARMCC::CondCodes CondCode, CondCode2;
3818   FPCCToARMCC(CC, CondCode, CondCode2);
3819
3820   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3821   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3822   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3823   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3824   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3825   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3826   if (CondCode2 != ARMCC::AL) {
3827     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3828     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3829     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3830   }
3831   return Res;
3832 }
3833
3834 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3835   SDValue Chain = Op.getOperand(0);
3836   SDValue Table = Op.getOperand(1);
3837   SDValue Index = Op.getOperand(2);
3838   SDLoc dl(Op);
3839
3840   EVT PTy = getPointerTy(DAG.getDataLayout());
3841   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3842   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3843   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3844   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3845   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3846   if (Subtarget->isThumb2()) {
3847     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3848     // which does another jump to the destination. This also makes it easier
3849     // to translate it to TBB / TBH later.
3850     // FIXME: This might not work if the function is extremely large.
3851     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3852                        Addr, Op.getOperand(2), JTI);
3853   }
3854   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3855     Addr =
3856         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3857                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3858                     false, false, false, 0);
3859     Chain = Addr.getValue(1);
3860     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3861     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3862   } else {
3863     Addr =
3864         DAG.getLoad(PTy, dl, Chain, Addr,
3865                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3866                     false, false, false, 0);
3867     Chain = Addr.getValue(1);
3868     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3869   }
3870 }
3871
3872 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3873   EVT VT = Op.getValueType();
3874   SDLoc dl(Op);
3875
3876   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3877     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3878       return Op;
3879     return DAG.UnrollVectorOp(Op.getNode());
3880   }
3881
3882   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3883          "Invalid type for custom lowering!");
3884   if (VT != MVT::v4i16)
3885     return DAG.UnrollVectorOp(Op.getNode());
3886
3887   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3888   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3889 }
3890
3891 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3892   EVT VT = Op.getValueType();
3893   if (VT.isVector())
3894     return LowerVectorFP_TO_INT(Op, DAG);
3895   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3896     RTLIB::Libcall LC;
3897     if (Op.getOpcode() == ISD::FP_TO_SINT)
3898       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3899                               Op.getValueType());
3900     else
3901       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3902                               Op.getValueType());
3903     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3904                        /*isSigned*/ false, SDLoc(Op)).first;
3905   }
3906
3907   return Op;
3908 }
3909
3910 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3911   EVT VT = Op.getValueType();
3912   SDLoc dl(Op);
3913
3914   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3915     if (VT.getVectorElementType() == MVT::f32)
3916       return Op;
3917     return DAG.UnrollVectorOp(Op.getNode());
3918   }
3919
3920   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3921          "Invalid type for custom lowering!");
3922   if (VT != MVT::v4f32)
3923     return DAG.UnrollVectorOp(Op.getNode());
3924
3925   unsigned CastOpc;
3926   unsigned Opc;
3927   switch (Op.getOpcode()) {
3928   default: llvm_unreachable("Invalid opcode!");
3929   case ISD::SINT_TO_FP:
3930     CastOpc = ISD::SIGN_EXTEND;
3931     Opc = ISD::SINT_TO_FP;
3932     break;
3933   case ISD::UINT_TO_FP:
3934     CastOpc = ISD::ZERO_EXTEND;
3935     Opc = ISD::UINT_TO_FP;
3936     break;
3937   }
3938
3939   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3940   return DAG.getNode(Opc, dl, VT, Op);
3941 }
3942
3943 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3944   EVT VT = Op.getValueType();
3945   if (VT.isVector())
3946     return LowerVectorINT_TO_FP(Op, DAG);
3947   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3948     RTLIB::Libcall LC;
3949     if (Op.getOpcode() == ISD::SINT_TO_FP)
3950       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3951                               Op.getValueType());
3952     else
3953       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3954                               Op.getValueType());
3955     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3956                        /*isSigned*/ false, SDLoc(Op)).first;
3957   }
3958
3959   return Op;
3960 }
3961
3962 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3963   // Implement fcopysign with a fabs and a conditional fneg.
3964   SDValue Tmp0 = Op.getOperand(0);
3965   SDValue Tmp1 = Op.getOperand(1);
3966   SDLoc dl(Op);
3967   EVT VT = Op.getValueType();
3968   EVT SrcVT = Tmp1.getValueType();
3969   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3970     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3971   bool UseNEON = !InGPR && Subtarget->hasNEON();
3972
3973   if (UseNEON) {
3974     // Use VBSL to copy the sign bit.
3975     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3976     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3977                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3978     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3979     if (VT == MVT::f64)
3980       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3981                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3982                          DAG.getConstant(32, dl, MVT::i32));
3983     else /*if (VT == MVT::f32)*/
3984       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3985     if (SrcVT == MVT::f32) {
3986       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3987       if (VT == MVT::f64)
3988         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3989                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3990                            DAG.getConstant(32, dl, MVT::i32));
3991     } else if (VT == MVT::f32)
3992       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3993                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3994                          DAG.getConstant(32, dl, MVT::i32));
3995     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3996     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3997
3998     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3999                                             dl, MVT::i32);
4000     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4001     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4002                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4003
4004     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4005                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4006                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4007     if (VT == MVT::f32) {
4008       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4009       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4010                         DAG.getConstant(0, dl, MVT::i32));
4011     } else {
4012       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4013     }
4014
4015     return Res;
4016   }
4017
4018   // Bitcast operand 1 to i32.
4019   if (SrcVT == MVT::f64)
4020     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4021                        Tmp1).getValue(1);
4022   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4023
4024   // Or in the signbit with integer operations.
4025   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4026   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4027   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4028   if (VT == MVT::f32) {
4029     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4030                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4031     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4032                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4033   }
4034
4035   // f64: Or the high part with signbit and then combine two parts.
4036   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4037                      Tmp0);
4038   SDValue Lo = Tmp0.getValue(0);
4039   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4040   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4041   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4042 }
4043
4044 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4045   MachineFunction &MF = DAG.getMachineFunction();
4046   MachineFrameInfo *MFI = MF.getFrameInfo();
4047   MFI->setReturnAddressIsTaken(true);
4048
4049   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4050     return SDValue();
4051
4052   EVT VT = Op.getValueType();
4053   SDLoc dl(Op);
4054   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4055   if (Depth) {
4056     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4057     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4058     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4059                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4060                        MachinePointerInfo(), false, false, false, 0);
4061   }
4062
4063   // Return LR, which contains the return address. Mark it an implicit live-in.
4064   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4065   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4066 }
4067
4068 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4069   const ARMBaseRegisterInfo &ARI =
4070     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4071   MachineFunction &MF = DAG.getMachineFunction();
4072   MachineFrameInfo *MFI = MF.getFrameInfo();
4073   MFI->setFrameAddressIsTaken(true);
4074
4075   EVT VT = Op.getValueType();
4076   SDLoc dl(Op);  // FIXME probably not meaningful
4077   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4078   unsigned FrameReg = ARI.getFrameRegister(MF);
4079   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4080   while (Depth--)
4081     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4082                             MachinePointerInfo(),
4083                             false, false, false, 0);
4084   return FrameAddr;
4085 }
4086
4087 // FIXME? Maybe this could be a TableGen attribute on some registers and
4088 // this table could be generated automatically from RegInfo.
4089 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4090                                               SelectionDAG &DAG) const {
4091   unsigned Reg = StringSwitch<unsigned>(RegName)
4092                        .Case("sp", ARM::SP)
4093                        .Default(0);
4094   if (Reg)
4095     return Reg;
4096   report_fatal_error(Twine("Invalid register name \""
4097                               + StringRef(RegName)  + "\"."));
4098 }
4099
4100 // Result is 64 bit value so split into two 32 bit values and return as a
4101 // pair of values.
4102 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4103                                 SelectionDAG &DAG) {
4104   SDLoc DL(N);
4105
4106   // This function is only supposed to be called for i64 type destination.
4107   assert(N->getValueType(0) == MVT::i64
4108           && "ExpandREAD_REGISTER called for non-i64 type result.");
4109
4110   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4111                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4112                              N->getOperand(0),
4113                              N->getOperand(1));
4114
4115   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4116                     Read.getValue(1)));
4117   Results.push_back(Read.getOperand(0));
4118 }
4119
4120 /// ExpandBITCAST - If the target supports VFP, this function is called to
4121 /// expand a bit convert where either the source or destination type is i64 to
4122 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4123 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4124 /// vectors), since the legalizer won't know what to do with that.
4125 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4126   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4127   SDLoc dl(N);
4128   SDValue Op = N->getOperand(0);
4129
4130   // This function is only supposed to be called for i64 types, either as the
4131   // source or destination of the bit convert.
4132   EVT SrcVT = Op.getValueType();
4133   EVT DstVT = N->getValueType(0);
4134   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4135          "ExpandBITCAST called for non-i64 type");
4136
4137   // Turn i64->f64 into VMOVDRR.
4138   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4139     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4140                              DAG.getConstant(0, dl, MVT::i32));
4141     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4142                              DAG.getConstant(1, dl, MVT::i32));
4143     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4144                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4145   }
4146
4147   // Turn f64->i64 into VMOVRRD.
4148   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4149     SDValue Cvt;
4150     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4151         SrcVT.getVectorNumElements() > 1)
4152       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4153                         DAG.getVTList(MVT::i32, MVT::i32),
4154                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4155     else
4156       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4157                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4158     // Merge the pieces into a single i64 value.
4159     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4160   }
4161
4162   return SDValue();
4163 }
4164
4165 /// getZeroVector - Returns a vector of specified type with all zero elements.
4166 /// Zero vectors are used to represent vector negation and in those cases
4167 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4168 /// not support i64 elements, so sometimes the zero vectors will need to be
4169 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4170 /// zero vector.
4171 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4172   assert(VT.isVector() && "Expected a vector type");
4173   // The canonical modified immediate encoding of a zero vector is....0!
4174   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4175   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4176   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4177   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4178 }
4179
4180 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4181 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4182 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4183                                                 SelectionDAG &DAG) const {
4184   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4185   EVT VT = Op.getValueType();
4186   unsigned VTBits = VT.getSizeInBits();
4187   SDLoc dl(Op);
4188   SDValue ShOpLo = Op.getOperand(0);
4189   SDValue ShOpHi = Op.getOperand(1);
4190   SDValue ShAmt  = Op.getOperand(2);
4191   SDValue ARMcc;
4192   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4193
4194   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4195
4196   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4197                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4198   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4199   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4200                                    DAG.getConstant(VTBits, dl, MVT::i32));
4201   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4202   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4203   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4204
4205   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4206   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4207                           ISD::SETGE, ARMcc, DAG, dl);
4208   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4209   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4210                            CCR, Cmp);
4211
4212   SDValue Ops[2] = { Lo, Hi };
4213   return DAG.getMergeValues(Ops, dl);
4214 }
4215
4216 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4217 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4218 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4219                                                SelectionDAG &DAG) const {
4220   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4221   EVT VT = Op.getValueType();
4222   unsigned VTBits = VT.getSizeInBits();
4223   SDLoc dl(Op);
4224   SDValue ShOpLo = Op.getOperand(0);
4225   SDValue ShOpHi = Op.getOperand(1);
4226   SDValue ShAmt  = Op.getOperand(2);
4227   SDValue ARMcc;
4228
4229   assert(Op.getOpcode() == ISD::SHL_PARTS);
4230   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4231                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4232   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4233   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4234                                    DAG.getConstant(VTBits, dl, MVT::i32));
4235   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4236   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4237
4238   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4239   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4240   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4241                           ISD::SETGE, ARMcc, DAG, dl);
4242   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4243   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4244                            CCR, Cmp);
4245
4246   SDValue Ops[2] = { Lo, Hi };
4247   return DAG.getMergeValues(Ops, dl);
4248 }
4249
4250 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4251                                             SelectionDAG &DAG) const {
4252   // The rounding mode is in bits 23:22 of the FPSCR.
4253   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4254   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4255   // so that the shift + and get folded into a bitfield extract.
4256   SDLoc dl(Op);
4257   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4258                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4259                                               MVT::i32));
4260   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4261                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4262   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4263                               DAG.getConstant(22, dl, MVT::i32));
4264   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4265                      DAG.getConstant(3, dl, MVT::i32));
4266 }
4267
4268 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4269                          const ARMSubtarget *ST) {
4270   SDLoc dl(N);
4271   EVT VT = N->getValueType(0);
4272   if (VT.isVector()) {
4273     assert(ST->hasNEON());
4274
4275     // Compute the least significant set bit: LSB = X & -X
4276     SDValue X = N->getOperand(0);
4277     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4278     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4279
4280     EVT ElemTy = VT.getVectorElementType();
4281
4282     if (ElemTy == MVT::i8) {
4283       // Compute with: cttz(x) = ctpop(lsb - 1)
4284       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4285                                 DAG.getTargetConstant(1, dl, ElemTy));
4286       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4287       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4288     }
4289
4290     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4291         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4292       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4293       unsigned NumBits = ElemTy.getSizeInBits();
4294       SDValue WidthMinus1 =
4295           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4296                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4297       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4298       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4299     }
4300
4301     // Compute with: cttz(x) = ctpop(lsb - 1)
4302
4303     // Since we can only compute the number of bits in a byte with vcnt.8, we
4304     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4305     // and i64.
4306
4307     // Compute LSB - 1.
4308     SDValue Bits;
4309     if (ElemTy == MVT::i64) {
4310       // Load constant 0xffff'ffff'ffff'ffff to register.
4311       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4312                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4313       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4314     } else {
4315       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4316                                 DAG.getTargetConstant(1, dl, ElemTy));
4317       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4318     }
4319
4320     // Count #bits with vcnt.8.
4321     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4322     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4323     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4324
4325     // Gather the #bits with vpaddl (pairwise add.)
4326     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4327     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4328         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4329         Cnt8);
4330     if (ElemTy == MVT::i16)
4331       return Cnt16;
4332
4333     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4334     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4335         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4336         Cnt16);
4337     if (ElemTy == MVT::i32)
4338       return Cnt32;
4339
4340     assert(ElemTy == MVT::i64);
4341     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4342         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4343         Cnt32);
4344     return Cnt64;
4345   }
4346
4347   if (!ST->hasV6T2Ops())
4348     return SDValue();
4349
4350   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4351   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4352 }
4353
4354 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4355 /// for each 16-bit element from operand, repeated.  The basic idea is to
4356 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4357 ///
4358 /// Trace for v4i16:
4359 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4360 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4361 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4362 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4363 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4364 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4365 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4366 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4367 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4368   EVT VT = N->getValueType(0);
4369   SDLoc DL(N);
4370
4371   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4372   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4373   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4374   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4375   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4376   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4377 }
4378
4379 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4380 /// bit-count for each 16-bit element from the operand.  We need slightly
4381 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4382 /// 64/128-bit registers.
4383 ///
4384 /// Trace for v4i16:
4385 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4386 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4387 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4388 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4389 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4390   EVT VT = N->getValueType(0);
4391   SDLoc DL(N);
4392
4393   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4394   if (VT.is64BitVector()) {
4395     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4396     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4397                        DAG.getIntPtrConstant(0, DL));
4398   } else {
4399     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4400                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4401     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4402   }
4403 }
4404
4405 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4406 /// bit-count for each 32-bit element from the operand.  The idea here is
4407 /// to split the vector into 16-bit elements, leverage the 16-bit count
4408 /// routine, and then combine the results.
4409 ///
4410 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4411 /// input    = [v0    v1    ] (vi: 32-bit elements)
4412 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4413 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4414 /// vrev: N0 = [k1 k0 k3 k2 ]
4415 ///            [k0 k1 k2 k3 ]
4416 ///       N1 =+[k1 k0 k3 k2 ]
4417 ///            [k0 k2 k1 k3 ]
4418 ///       N2 =+[k1 k3 k0 k2 ]
4419 ///            [k0    k2    k1    k3    ]
4420 /// Extended =+[k1    k3    k0    k2    ]
4421 ///            [k0    k2    ]
4422 /// Extracted=+[k1    k3    ]
4423 ///
4424 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4425   EVT VT = N->getValueType(0);
4426   SDLoc DL(N);
4427
4428   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4429
4430   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4431   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4432   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4433   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4434   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4435
4436   if (VT.is64BitVector()) {
4437     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4438     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4439                        DAG.getIntPtrConstant(0, DL));
4440   } else {
4441     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4442                                     DAG.getIntPtrConstant(0, DL));
4443     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4444   }
4445 }
4446
4447 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4448                           const ARMSubtarget *ST) {
4449   EVT VT = N->getValueType(0);
4450
4451   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4452   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4453           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4454          "Unexpected type for custom ctpop lowering");
4455
4456   if (VT.getVectorElementType() == MVT::i32)
4457     return lowerCTPOP32BitElements(N, DAG);
4458   else
4459     return lowerCTPOP16BitElements(N, DAG);
4460 }
4461
4462 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4463                           const ARMSubtarget *ST) {
4464   EVT VT = N->getValueType(0);
4465   SDLoc dl(N);
4466
4467   if (!VT.isVector())
4468     return SDValue();
4469
4470   // Lower vector shifts on NEON to use VSHL.
4471   assert(ST->hasNEON() && "unexpected vector shift");
4472
4473   // Left shifts translate directly to the vshiftu intrinsic.
4474   if (N->getOpcode() == ISD::SHL)
4475     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4476                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4477                                        MVT::i32),
4478                        N->getOperand(0), N->getOperand(1));
4479
4480   assert((N->getOpcode() == ISD::SRA ||
4481           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4482
4483   // NEON uses the same intrinsics for both left and right shifts.  For
4484   // right shifts, the shift amounts are negative, so negate the vector of
4485   // shift amounts.
4486   EVT ShiftVT = N->getOperand(1).getValueType();
4487   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4488                                      getZeroVector(ShiftVT, DAG, dl),
4489                                      N->getOperand(1));
4490   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4491                              Intrinsic::arm_neon_vshifts :
4492                              Intrinsic::arm_neon_vshiftu);
4493   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4494                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4495                      N->getOperand(0), NegatedCount);
4496 }
4497
4498 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4499                                 const ARMSubtarget *ST) {
4500   EVT VT = N->getValueType(0);
4501   SDLoc dl(N);
4502
4503   // We can get here for a node like i32 = ISD::SHL i32, i64
4504   if (VT != MVT::i64)
4505     return SDValue();
4506
4507   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4508          "Unknown shift to lower!");
4509
4510   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4511   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4512       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4513     return SDValue();
4514
4515   // If we are in thumb mode, we don't have RRX.
4516   if (ST->isThumb1Only()) return SDValue();
4517
4518   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4519   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4520                            DAG.getConstant(0, dl, MVT::i32));
4521   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4522                            DAG.getConstant(1, dl, MVT::i32));
4523
4524   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4525   // captures the result into a carry flag.
4526   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4527   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4528
4529   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4530   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4531
4532   // Merge the pieces into a single i64 value.
4533  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4534 }
4535
4536 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4537   SDValue TmpOp0, TmpOp1;
4538   bool Invert = false;
4539   bool Swap = false;
4540   unsigned Opc = 0;
4541
4542   SDValue Op0 = Op.getOperand(0);
4543   SDValue Op1 = Op.getOperand(1);
4544   SDValue CC = Op.getOperand(2);
4545   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4546   EVT VT = Op.getValueType();
4547   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4548   SDLoc dl(Op);
4549
4550   if (CmpVT.getVectorElementType() == MVT::i64)
4551     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4552     // but it's possible that our operands are 64-bit but our result is 32-bit.
4553     // Bail in this case.
4554     return SDValue();
4555
4556   if (Op1.getValueType().isFloatingPoint()) {
4557     switch (SetCCOpcode) {
4558     default: llvm_unreachable("Illegal FP comparison");
4559     case ISD::SETUNE:
4560     case ISD::SETNE:  Invert = true; // Fallthrough
4561     case ISD::SETOEQ:
4562     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4563     case ISD::SETOLT:
4564     case ISD::SETLT: Swap = true; // Fallthrough
4565     case ISD::SETOGT:
4566     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4567     case ISD::SETOLE:
4568     case ISD::SETLE:  Swap = true; // Fallthrough
4569     case ISD::SETOGE:
4570     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4571     case ISD::SETUGE: Swap = true; // Fallthrough
4572     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4573     case ISD::SETUGT: Swap = true; // Fallthrough
4574     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4575     case ISD::SETUEQ: Invert = true; // Fallthrough
4576     case ISD::SETONE:
4577       // Expand this to (OLT | OGT).
4578       TmpOp0 = Op0;
4579       TmpOp1 = Op1;
4580       Opc = ISD::OR;
4581       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4582       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4583       break;
4584     case ISD::SETUO: Invert = true; // Fallthrough
4585     case ISD::SETO:
4586       // Expand this to (OLT | OGE).
4587       TmpOp0 = Op0;
4588       TmpOp1 = Op1;
4589       Opc = ISD::OR;
4590       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4591       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4592       break;
4593     }
4594   } else {
4595     // Integer comparisons.
4596     switch (SetCCOpcode) {
4597     default: llvm_unreachable("Illegal integer comparison");
4598     case ISD::SETNE:  Invert = true;
4599     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4600     case ISD::SETLT:  Swap = true;
4601     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4602     case ISD::SETLE:  Swap = true;
4603     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4604     case ISD::SETULT: Swap = true;
4605     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4606     case ISD::SETULE: Swap = true;
4607     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4608     }
4609
4610     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4611     if (Opc == ARMISD::VCEQ) {
4612
4613       SDValue AndOp;
4614       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4615         AndOp = Op0;
4616       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4617         AndOp = Op1;
4618
4619       // Ignore bitconvert.
4620       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4621         AndOp = AndOp.getOperand(0);
4622
4623       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4624         Opc = ARMISD::VTST;
4625         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4626         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4627         Invert = !Invert;
4628       }
4629     }
4630   }
4631
4632   if (Swap)
4633     std::swap(Op0, Op1);
4634
4635   // If one of the operands is a constant vector zero, attempt to fold the
4636   // comparison to a specialized compare-against-zero form.
4637   SDValue SingleOp;
4638   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4639     SingleOp = Op0;
4640   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4641     if (Opc == ARMISD::VCGE)
4642       Opc = ARMISD::VCLEZ;
4643     else if (Opc == ARMISD::VCGT)
4644       Opc = ARMISD::VCLTZ;
4645     SingleOp = Op1;
4646   }
4647
4648   SDValue Result;
4649   if (SingleOp.getNode()) {
4650     switch (Opc) {
4651     case ARMISD::VCEQ:
4652       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4653     case ARMISD::VCGE:
4654       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4655     case ARMISD::VCLEZ:
4656       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4657     case ARMISD::VCGT:
4658       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4659     case ARMISD::VCLTZ:
4660       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4661     default:
4662       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4663     }
4664   } else {
4665      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4666   }
4667
4668   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4669
4670   if (Invert)
4671     Result = DAG.getNOT(dl, Result, VT);
4672
4673   return Result;
4674 }
4675
4676 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4677 /// valid vector constant for a NEON instruction with a "modified immediate"
4678 /// operand (e.g., VMOV).  If so, return the encoded value.
4679 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4680                                  unsigned SplatBitSize, SelectionDAG &DAG,
4681                                  SDLoc dl, EVT &VT, bool is128Bits,
4682                                  NEONModImmType type) {
4683   unsigned OpCmode, Imm;
4684
4685   // SplatBitSize is set to the smallest size that splats the vector, so a
4686   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4687   // immediate instructions others than VMOV do not support the 8-bit encoding
4688   // of a zero vector, and the default encoding of zero is supposed to be the
4689   // 32-bit version.
4690   if (SplatBits == 0)
4691     SplatBitSize = 32;
4692
4693   switch (SplatBitSize) {
4694   case 8:
4695     if (type != VMOVModImm)
4696       return SDValue();
4697     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4698     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4699     OpCmode = 0xe;
4700     Imm = SplatBits;
4701     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4702     break;
4703
4704   case 16:
4705     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4706     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4707     if ((SplatBits & ~0xff) == 0) {
4708       // Value = 0x00nn: Op=x, Cmode=100x.
4709       OpCmode = 0x8;
4710       Imm = SplatBits;
4711       break;
4712     }
4713     if ((SplatBits & ~0xff00) == 0) {
4714       // Value = 0xnn00: Op=x, Cmode=101x.
4715       OpCmode = 0xa;
4716       Imm = SplatBits >> 8;
4717       break;
4718     }
4719     return SDValue();
4720
4721   case 32:
4722     // NEON's 32-bit VMOV supports splat values where:
4723     // * only one byte is nonzero, or
4724     // * the least significant byte is 0xff and the second byte is nonzero, or
4725     // * the least significant 2 bytes are 0xff and the third is nonzero.
4726     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4727     if ((SplatBits & ~0xff) == 0) {
4728       // Value = 0x000000nn: Op=x, Cmode=000x.
4729       OpCmode = 0;
4730       Imm = SplatBits;
4731       break;
4732     }
4733     if ((SplatBits & ~0xff00) == 0) {
4734       // Value = 0x0000nn00: Op=x, Cmode=001x.
4735       OpCmode = 0x2;
4736       Imm = SplatBits >> 8;
4737       break;
4738     }
4739     if ((SplatBits & ~0xff0000) == 0) {
4740       // Value = 0x00nn0000: Op=x, Cmode=010x.
4741       OpCmode = 0x4;
4742       Imm = SplatBits >> 16;
4743       break;
4744     }
4745     if ((SplatBits & ~0xff000000) == 0) {
4746       // Value = 0xnn000000: Op=x, Cmode=011x.
4747       OpCmode = 0x6;
4748       Imm = SplatBits >> 24;
4749       break;
4750     }
4751
4752     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4753     if (type == OtherModImm) return SDValue();
4754
4755     if ((SplatBits & ~0xffff) == 0 &&
4756         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4757       // Value = 0x0000nnff: Op=x, Cmode=1100.
4758       OpCmode = 0xc;
4759       Imm = SplatBits >> 8;
4760       break;
4761     }
4762
4763     if ((SplatBits & ~0xffffff) == 0 &&
4764         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4765       // Value = 0x00nnffff: Op=x, Cmode=1101.
4766       OpCmode = 0xd;
4767       Imm = SplatBits >> 16;
4768       break;
4769     }
4770
4771     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4772     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4773     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4774     // and fall through here to test for a valid 64-bit splat.  But, then the
4775     // caller would also need to check and handle the change in size.
4776     return SDValue();
4777
4778   case 64: {
4779     if (type != VMOVModImm)
4780       return SDValue();
4781     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4782     uint64_t BitMask = 0xff;
4783     uint64_t Val = 0;
4784     unsigned ImmMask = 1;
4785     Imm = 0;
4786     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4787       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4788         Val |= BitMask;
4789         Imm |= ImmMask;
4790       } else if ((SplatBits & BitMask) != 0) {
4791         return SDValue();
4792       }
4793       BitMask <<= 8;
4794       ImmMask <<= 1;
4795     }
4796
4797     if (DAG.getDataLayout().isBigEndian())
4798       // swap higher and lower 32 bit word
4799       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4800
4801     // Op=1, Cmode=1110.
4802     OpCmode = 0x1e;
4803     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4804     break;
4805   }
4806
4807   default:
4808     llvm_unreachable("unexpected size for isNEONModifiedImm");
4809   }
4810
4811   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4812   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4813 }
4814
4815 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4816                                            const ARMSubtarget *ST) const {
4817   if (!ST->hasVFP3())
4818     return SDValue();
4819
4820   bool IsDouble = Op.getValueType() == MVT::f64;
4821   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4822
4823   // Use the default (constant pool) lowering for double constants when we have
4824   // an SP-only FPU
4825   if (IsDouble && Subtarget->isFPOnlySP())
4826     return SDValue();
4827
4828   // Try splatting with a VMOV.f32...
4829   APFloat FPVal = CFP->getValueAPF();
4830   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4831
4832   if (ImmVal != -1) {
4833     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4834       // We have code in place to select a valid ConstantFP already, no need to
4835       // do any mangling.
4836       return Op;
4837     }
4838
4839     // It's a float and we are trying to use NEON operations where
4840     // possible. Lower it to a splat followed by an extract.
4841     SDLoc DL(Op);
4842     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4843     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4844                                       NewVal);
4845     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4846                        DAG.getConstant(0, DL, MVT::i32));
4847   }
4848
4849   // The rest of our options are NEON only, make sure that's allowed before
4850   // proceeding..
4851   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4852     return SDValue();
4853
4854   EVT VMovVT;
4855   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4856
4857   // It wouldn't really be worth bothering for doubles except for one very
4858   // important value, which does happen to match: 0.0. So make sure we don't do
4859   // anything stupid.
4860   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4861     return SDValue();
4862
4863   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4864   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4865                                      VMovVT, false, VMOVModImm);
4866   if (NewVal != SDValue()) {
4867     SDLoc DL(Op);
4868     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4869                                       NewVal);
4870     if (IsDouble)
4871       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4872
4873     // It's a float: cast and extract a vector element.
4874     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4875                                        VecConstant);
4876     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4877                        DAG.getConstant(0, DL, MVT::i32));
4878   }
4879
4880   // Finally, try a VMVN.i32
4881   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4882                              false, VMVNModImm);
4883   if (NewVal != SDValue()) {
4884     SDLoc DL(Op);
4885     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4886
4887     if (IsDouble)
4888       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4889
4890     // It's a float: cast and extract a vector element.
4891     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4892                                        VecConstant);
4893     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4894                        DAG.getConstant(0, DL, MVT::i32));
4895   }
4896
4897   return SDValue();
4898 }
4899
4900 // check if an VEXT instruction can handle the shuffle mask when the
4901 // vector sources of the shuffle are the same.
4902 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4903   unsigned NumElts = VT.getVectorNumElements();
4904
4905   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4906   if (M[0] < 0)
4907     return false;
4908
4909   Imm = M[0];
4910
4911   // If this is a VEXT shuffle, the immediate value is the index of the first
4912   // element.  The other shuffle indices must be the successive elements after
4913   // the first one.
4914   unsigned ExpectedElt = Imm;
4915   for (unsigned i = 1; i < NumElts; ++i) {
4916     // Increment the expected index.  If it wraps around, just follow it
4917     // back to index zero and keep going.
4918     ++ExpectedElt;
4919     if (ExpectedElt == NumElts)
4920       ExpectedElt = 0;
4921
4922     if (M[i] < 0) continue; // ignore UNDEF indices
4923     if (ExpectedElt != static_cast<unsigned>(M[i]))
4924       return false;
4925   }
4926
4927   return true;
4928 }
4929
4930
4931 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4932                        bool &ReverseVEXT, unsigned &Imm) {
4933   unsigned NumElts = VT.getVectorNumElements();
4934   ReverseVEXT = false;
4935
4936   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4937   if (M[0] < 0)
4938     return false;
4939
4940   Imm = M[0];
4941
4942   // If this is a VEXT shuffle, the immediate value is the index of the first
4943   // element.  The other shuffle indices must be the successive elements after
4944   // the first one.
4945   unsigned ExpectedElt = Imm;
4946   for (unsigned i = 1; i < NumElts; ++i) {
4947     // Increment the expected index.  If it wraps around, it may still be
4948     // a VEXT but the source vectors must be swapped.
4949     ExpectedElt += 1;
4950     if (ExpectedElt == NumElts * 2) {
4951       ExpectedElt = 0;
4952       ReverseVEXT = true;
4953     }
4954
4955     if (M[i] < 0) continue; // ignore UNDEF indices
4956     if (ExpectedElt != static_cast<unsigned>(M[i]))
4957       return false;
4958   }
4959
4960   // Adjust the index value if the source operands will be swapped.
4961   if (ReverseVEXT)
4962     Imm -= NumElts;
4963
4964   return true;
4965 }
4966
4967 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4968 /// instruction with the specified blocksize.  (The order of the elements
4969 /// within each block of the vector is reversed.)
4970 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4971   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4972          "Only possible block sizes for VREV are: 16, 32, 64");
4973
4974   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4975   if (EltSz == 64)
4976     return false;
4977
4978   unsigned NumElts = VT.getVectorNumElements();
4979   unsigned BlockElts = M[0] + 1;
4980   // If the first shuffle index is UNDEF, be optimistic.
4981   if (M[0] < 0)
4982     BlockElts = BlockSize / EltSz;
4983
4984   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4985     return false;
4986
4987   for (unsigned i = 0; i < NumElts; ++i) {
4988     if (M[i] < 0) continue; // ignore UNDEF indices
4989     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4990       return false;
4991   }
4992
4993   return true;
4994 }
4995
4996 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4997   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4998   // range, then 0 is placed into the resulting vector. So pretty much any mask
4999   // of 8 elements can work here.
5000   return VT == MVT::v8i8 && M.size() == 8;
5001 }
5002
5003 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5004 // checking that pairs of elements in the shuffle mask represent the same index
5005 // in each vector, incrementing the expected index by 2 at each step.
5006 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5007 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5008 //  v2={e,f,g,h}
5009 // WhichResult gives the offset for each element in the mask based on which
5010 // of the two results it belongs to.
5011 //
5012 // The transpose can be represented either as:
5013 // result1 = shufflevector v1, v2, result1_shuffle_mask
5014 // result2 = shufflevector v1, v2, result2_shuffle_mask
5015 // where v1/v2 and the shuffle masks have the same number of elements
5016 // (here WhichResult (see below) indicates which result is being checked)
5017 //
5018 // or as:
5019 // results = shufflevector v1, v2, shuffle_mask
5020 // where both results are returned in one vector and the shuffle mask has twice
5021 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5022 // want to check the low half and high half of the shuffle mask as if it were
5023 // the other case
5024 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5025   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5026   if (EltSz == 64)
5027     return false;
5028
5029   unsigned NumElts = VT.getVectorNumElements();
5030   if (M.size() != NumElts && M.size() != NumElts*2)
5031     return false;
5032
5033   // If the mask is twice as long as the input vector then we need to check the
5034   // upper and lower parts of the mask with a matching value for WhichResult
5035   // FIXME: A mask with only even values will be rejected in case the first
5036   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5037   // M[0] is used to determine WhichResult
5038   for (unsigned i = 0; i < M.size(); i += NumElts) {
5039     if (M.size() == NumElts * 2)
5040       WhichResult = i / NumElts;
5041     else
5042       WhichResult = M[i] == 0 ? 0 : 1;
5043     for (unsigned j = 0; j < NumElts; j += 2) {
5044       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5045           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5046         return false;
5047     }
5048   }
5049
5050   if (M.size() == NumElts*2)
5051     WhichResult = 0;
5052
5053   return true;
5054 }
5055
5056 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5057 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5058 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5059 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5060   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5061   if (EltSz == 64)
5062     return false;
5063
5064   unsigned NumElts = VT.getVectorNumElements();
5065   if (M.size() != NumElts && M.size() != NumElts*2)
5066     return false;
5067
5068   for (unsigned i = 0; i < M.size(); i += NumElts) {
5069     if (M.size() == NumElts * 2)
5070       WhichResult = i / NumElts;
5071     else
5072       WhichResult = M[i] == 0 ? 0 : 1;
5073     for (unsigned j = 0; j < NumElts; j += 2) {
5074       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5075           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5076         return false;
5077     }
5078   }
5079
5080   if (M.size() == NumElts*2)
5081     WhichResult = 0;
5082
5083   return true;
5084 }
5085
5086 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5087 // that the mask elements are either all even and in steps of size 2 or all odd
5088 // and in steps of size 2.
5089 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5090 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5091 //  v2={e,f,g,h}
5092 // Requires similar checks to that of isVTRNMask with
5093 // respect the how results are returned.
5094 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5095   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5096   if (EltSz == 64)
5097     return false;
5098
5099   unsigned NumElts = VT.getVectorNumElements();
5100   if (M.size() != NumElts && M.size() != NumElts*2)
5101     return false;
5102
5103   for (unsigned i = 0; i < M.size(); i += NumElts) {
5104     WhichResult = M[i] == 0 ? 0 : 1;
5105     for (unsigned j = 0; j < NumElts; ++j) {
5106       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5107         return false;
5108     }
5109   }
5110
5111   if (M.size() == NumElts*2)
5112     WhichResult = 0;
5113
5114   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5115   if (VT.is64BitVector() && EltSz == 32)
5116     return false;
5117
5118   return true;
5119 }
5120
5121 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5122 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5123 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5124 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5125   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5126   if (EltSz == 64)
5127     return false;
5128
5129   unsigned NumElts = VT.getVectorNumElements();
5130   if (M.size() != NumElts && M.size() != NumElts*2)
5131     return false;
5132
5133   unsigned Half = NumElts / 2;
5134   for (unsigned i = 0; i < M.size(); i += NumElts) {
5135     WhichResult = M[i] == 0 ? 0 : 1;
5136     for (unsigned j = 0; j < NumElts; j += Half) {
5137       unsigned Idx = WhichResult;
5138       for (unsigned k = 0; k < Half; ++k) {
5139         int MIdx = M[i + j + k];
5140         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5141           return false;
5142         Idx += 2;
5143       }
5144     }
5145   }
5146
5147   if (M.size() == NumElts*2)
5148     WhichResult = 0;
5149
5150   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5151   if (VT.is64BitVector() && EltSz == 32)
5152     return false;
5153
5154   return true;
5155 }
5156
5157 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5158 // that pairs of elements of the shufflemask represent the same index in each
5159 // vector incrementing sequentially through the vectors.
5160 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5161 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5162 //  v2={e,f,g,h}
5163 // Requires similar checks to that of isVTRNMask with respect the how results
5164 // are returned.
5165 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5166   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5167   if (EltSz == 64)
5168     return false;
5169
5170   unsigned NumElts = VT.getVectorNumElements();
5171   if (M.size() != NumElts && M.size() != NumElts*2)
5172     return false;
5173
5174   for (unsigned i = 0; i < M.size(); i += NumElts) {
5175     WhichResult = M[i] == 0 ? 0 : 1;
5176     unsigned Idx = WhichResult * NumElts / 2;
5177     for (unsigned j = 0; j < NumElts; j += 2) {
5178       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5179           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5180         return false;
5181       Idx += 1;
5182     }
5183   }
5184
5185   if (M.size() == NumElts*2)
5186     WhichResult = 0;
5187
5188   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5189   if (VT.is64BitVector() && EltSz == 32)
5190     return false;
5191
5192   return true;
5193 }
5194
5195 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5196 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5197 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5198 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5199   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5200   if (EltSz == 64)
5201     return false;
5202
5203   unsigned NumElts = VT.getVectorNumElements();
5204   if (M.size() != NumElts && M.size() != NumElts*2)
5205     return false;
5206
5207   for (unsigned i = 0; i < M.size(); i += NumElts) {
5208     WhichResult = M[i] == 0 ? 0 : 1;
5209     unsigned Idx = WhichResult * NumElts / 2;
5210     for (unsigned j = 0; j < NumElts; j += 2) {
5211       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5212           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5213         return false;
5214       Idx += 1;
5215     }
5216   }
5217
5218   if (M.size() == NumElts*2)
5219     WhichResult = 0;
5220
5221   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5222   if (VT.is64BitVector() && EltSz == 32)
5223     return false;
5224
5225   return true;
5226 }
5227
5228 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5229 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5230 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5231                                            unsigned &WhichResult,
5232                                            bool &isV_UNDEF) {
5233   isV_UNDEF = false;
5234   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5235     return ARMISD::VTRN;
5236   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5237     return ARMISD::VUZP;
5238   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5239     return ARMISD::VZIP;
5240
5241   isV_UNDEF = true;
5242   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5243     return ARMISD::VTRN;
5244   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5245     return ARMISD::VUZP;
5246   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5247     return ARMISD::VZIP;
5248
5249   return 0;
5250 }
5251
5252 /// \return true if this is a reverse operation on an vector.
5253 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5254   unsigned NumElts = VT.getVectorNumElements();
5255   // Make sure the mask has the right size.
5256   if (NumElts != M.size())
5257       return false;
5258
5259   // Look for <15, ..., 3, -1, 1, 0>.
5260   for (unsigned i = 0; i != NumElts; ++i)
5261     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5262       return false;
5263
5264   return true;
5265 }
5266
5267 // If N is an integer constant that can be moved into a register in one
5268 // instruction, return an SDValue of such a constant (will become a MOV
5269 // instruction).  Otherwise return null.
5270 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5271                                      const ARMSubtarget *ST, SDLoc dl) {
5272   uint64_t Val;
5273   if (!isa<ConstantSDNode>(N))
5274     return SDValue();
5275   Val = cast<ConstantSDNode>(N)->getZExtValue();
5276
5277   if (ST->isThumb1Only()) {
5278     if (Val <= 255 || ~Val <= 255)
5279       return DAG.getConstant(Val, dl, MVT::i32);
5280   } else {
5281     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5282       return DAG.getConstant(Val, dl, MVT::i32);
5283   }
5284   return SDValue();
5285 }
5286
5287 // If this is a case we can't handle, return null and let the default
5288 // expansion code take care of it.
5289 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5290                                              const ARMSubtarget *ST) const {
5291   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5292   SDLoc dl(Op);
5293   EVT VT = Op.getValueType();
5294
5295   APInt SplatBits, SplatUndef;
5296   unsigned SplatBitSize;
5297   bool HasAnyUndefs;
5298   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5299     if (SplatBitSize <= 64) {
5300       // Check if an immediate VMOV works.
5301       EVT VmovVT;
5302       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5303                                       SplatUndef.getZExtValue(), SplatBitSize,
5304                                       DAG, dl, VmovVT, VT.is128BitVector(),
5305                                       VMOVModImm);
5306       if (Val.getNode()) {
5307         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5308         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5309       }
5310
5311       // Try an immediate VMVN.
5312       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5313       Val = isNEONModifiedImm(NegatedImm,
5314                                       SplatUndef.getZExtValue(), SplatBitSize,
5315                                       DAG, dl, VmovVT, VT.is128BitVector(),
5316                                       VMVNModImm);
5317       if (Val.getNode()) {
5318         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5319         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5320       }
5321
5322       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5323       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5324         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5325         if (ImmVal != -1) {
5326           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5327           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5328         }
5329       }
5330     }
5331   }
5332
5333   // Scan through the operands to see if only one value is used.
5334   //
5335   // As an optimisation, even if more than one value is used it may be more
5336   // profitable to splat with one value then change some lanes.
5337   //
5338   // Heuristically we decide to do this if the vector has a "dominant" value,
5339   // defined as splatted to more than half of the lanes.
5340   unsigned NumElts = VT.getVectorNumElements();
5341   bool isOnlyLowElement = true;
5342   bool usesOnlyOneValue = true;
5343   bool hasDominantValue = false;
5344   bool isConstant = true;
5345
5346   // Map of the number of times a particular SDValue appears in the
5347   // element list.
5348   DenseMap<SDValue, unsigned> ValueCounts;
5349   SDValue Value;
5350   for (unsigned i = 0; i < NumElts; ++i) {
5351     SDValue V = Op.getOperand(i);
5352     if (V.getOpcode() == ISD::UNDEF)
5353       continue;
5354     if (i > 0)
5355       isOnlyLowElement = false;
5356     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5357       isConstant = false;
5358
5359     ValueCounts.insert(std::make_pair(V, 0));
5360     unsigned &Count = ValueCounts[V];
5361
5362     // Is this value dominant? (takes up more than half of the lanes)
5363     if (++Count > (NumElts / 2)) {
5364       hasDominantValue = true;
5365       Value = V;
5366     }
5367   }
5368   if (ValueCounts.size() != 1)
5369     usesOnlyOneValue = false;
5370   if (!Value.getNode() && ValueCounts.size() > 0)
5371     Value = ValueCounts.begin()->first;
5372
5373   if (ValueCounts.size() == 0)
5374     return DAG.getUNDEF(VT);
5375
5376   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5377   // Keep going if we are hitting this case.
5378   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5379     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5380
5381   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5382
5383   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5384   // i32 and try again.
5385   if (hasDominantValue && EltSize <= 32) {
5386     if (!isConstant) {
5387       SDValue N;
5388
5389       // If we are VDUPing a value that comes directly from a vector, that will
5390       // cause an unnecessary move to and from a GPR, where instead we could
5391       // just use VDUPLANE. We can only do this if the lane being extracted
5392       // is at a constant index, as the VDUP from lane instructions only have
5393       // constant-index forms.
5394       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5395           isa<ConstantSDNode>(Value->getOperand(1))) {
5396         // We need to create a new undef vector to use for the VDUPLANE if the
5397         // size of the vector from which we get the value is different than the
5398         // size of the vector that we need to create. We will insert the element
5399         // such that the register coalescer will remove unnecessary copies.
5400         if (VT != Value->getOperand(0).getValueType()) {
5401           ConstantSDNode *constIndex;
5402           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5403           assert(constIndex && "The index is not a constant!");
5404           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5405                              VT.getVectorNumElements();
5406           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5407                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5408                         Value, DAG.getConstant(index, dl, MVT::i32)),
5409                            DAG.getConstant(index, dl, MVT::i32));
5410         } else
5411           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5412                         Value->getOperand(0), Value->getOperand(1));
5413       } else
5414         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5415
5416       if (!usesOnlyOneValue) {
5417         // The dominant value was splatted as 'N', but we now have to insert
5418         // all differing elements.
5419         for (unsigned I = 0; I < NumElts; ++I) {
5420           if (Op.getOperand(I) == Value)
5421             continue;
5422           SmallVector<SDValue, 3> Ops;
5423           Ops.push_back(N);
5424           Ops.push_back(Op.getOperand(I));
5425           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5426           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5427         }
5428       }
5429       return N;
5430     }
5431     if (VT.getVectorElementType().isFloatingPoint()) {
5432       SmallVector<SDValue, 8> Ops;
5433       for (unsigned i = 0; i < NumElts; ++i)
5434         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5435                                   Op.getOperand(i)));
5436       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5437       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5438       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5439       if (Val.getNode())
5440         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5441     }
5442     if (usesOnlyOneValue) {
5443       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5444       if (isConstant && Val.getNode())
5445         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5446     }
5447   }
5448
5449   // If all elements are constants and the case above didn't get hit, fall back
5450   // to the default expansion, which will generate a load from the constant
5451   // pool.
5452   if (isConstant)
5453     return SDValue();
5454
5455   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5456   if (NumElts >= 4) {
5457     SDValue shuffle = ReconstructShuffle(Op, DAG);
5458     if (shuffle != SDValue())
5459       return shuffle;
5460   }
5461
5462   // Vectors with 32- or 64-bit elements can be built by directly assigning
5463   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5464   // will be legalized.
5465   if (EltSize >= 32) {
5466     // Do the expansion with floating-point types, since that is what the VFP
5467     // registers are defined to use, and since i64 is not legal.
5468     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5469     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5470     SmallVector<SDValue, 8> Ops;
5471     for (unsigned i = 0; i < NumElts; ++i)
5472       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5473     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5474     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5475   }
5476
5477   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5478   // know the default expansion would otherwise fall back on something even
5479   // worse. For a vector with one or two non-undef values, that's
5480   // scalar_to_vector for the elements followed by a shuffle (provided the
5481   // shuffle is valid for the target) and materialization element by element
5482   // on the stack followed by a load for everything else.
5483   if (!isConstant && !usesOnlyOneValue) {
5484     SDValue Vec = DAG.getUNDEF(VT);
5485     for (unsigned i = 0 ; i < NumElts; ++i) {
5486       SDValue V = Op.getOperand(i);
5487       if (V.getOpcode() == ISD::UNDEF)
5488         continue;
5489       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5490       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5491     }
5492     return Vec;
5493   }
5494
5495   return SDValue();
5496 }
5497
5498 // Gather data to see if the operation can be modelled as a
5499 // shuffle in combination with VEXTs.
5500 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5501                                               SelectionDAG &DAG) const {
5502   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5503   SDLoc dl(Op);
5504   EVT VT = Op.getValueType();
5505   unsigned NumElts = VT.getVectorNumElements();
5506
5507   struct ShuffleSourceInfo {
5508     SDValue Vec;
5509     unsigned MinElt;
5510     unsigned MaxElt;
5511
5512     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5513     // be compatible with the shuffle we intend to construct. As a result
5514     // ShuffleVec will be some sliding window into the original Vec.
5515     SDValue ShuffleVec;
5516
5517     // Code should guarantee that element i in Vec starts at element "WindowBase
5518     // + i * WindowScale in ShuffleVec".
5519     int WindowBase;
5520     int WindowScale;
5521
5522     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5523     ShuffleSourceInfo(SDValue Vec)
5524         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5525           WindowScale(1) {}
5526   };
5527
5528   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5529   // node.
5530   SmallVector<ShuffleSourceInfo, 2> Sources;
5531   for (unsigned i = 0; i < NumElts; ++i) {
5532     SDValue V = Op.getOperand(i);
5533     if (V.getOpcode() == ISD::UNDEF)
5534       continue;
5535     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5536       // A shuffle can only come from building a vector from various
5537       // elements of other vectors.
5538       return SDValue();
5539     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5540       // Furthermore, shuffles require a constant mask, whereas extractelts
5541       // accept variable indices.
5542       return SDValue();
5543     }
5544
5545     // Add this element source to the list if it's not already there.
5546     SDValue SourceVec = V.getOperand(0);
5547     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5548     if (Source == Sources.end())
5549       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5550
5551     // Update the minimum and maximum lane number seen.
5552     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5553     Source->MinElt = std::min(Source->MinElt, EltNo);
5554     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5555   }
5556
5557   // Currently only do something sane when at most two source vectors
5558   // are involved.
5559   if (Sources.size() > 2)
5560     return SDValue();
5561
5562   // Find out the smallest element size among result and two sources, and use
5563   // it as element size to build the shuffle_vector.
5564   EVT SmallestEltTy = VT.getVectorElementType();
5565   for (auto &Source : Sources) {
5566     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5567     if (SrcEltTy.bitsLT(SmallestEltTy))
5568       SmallestEltTy = SrcEltTy;
5569   }
5570   unsigned ResMultiplier =
5571       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5572   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5573   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5574
5575   // If the source vector is too wide or too narrow, we may nevertheless be able
5576   // to construct a compatible shuffle either by concatenating it with UNDEF or
5577   // extracting a suitable range of elements.
5578   for (auto &Src : Sources) {
5579     EVT SrcVT = Src.ShuffleVec.getValueType();
5580
5581     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5582       continue;
5583
5584     // This stage of the search produces a source with the same element type as
5585     // the original, but with a total width matching the BUILD_VECTOR output.
5586     EVT EltVT = SrcVT.getVectorElementType();
5587     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5588     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5589
5590     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5591       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5592         return SDValue();
5593       // We can pad out the smaller vector for free, so if it's part of a
5594       // shuffle...
5595       Src.ShuffleVec =
5596           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5597                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5598       continue;
5599     }
5600
5601     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5602       return SDValue();
5603
5604     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5605       // Span too large for a VEXT to cope
5606       return SDValue();
5607     }
5608
5609     if (Src.MinElt >= NumSrcElts) {
5610       // The extraction can just take the second half
5611       Src.ShuffleVec =
5612           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5613                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5614       Src.WindowBase = -NumSrcElts;
5615     } else if (Src.MaxElt < NumSrcElts) {
5616       // The extraction can just take the first half
5617       Src.ShuffleVec =
5618           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5619                       DAG.getConstant(0, dl, MVT::i32));
5620     } else {
5621       // An actual VEXT is needed
5622       SDValue VEXTSrc1 =
5623           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5624                       DAG.getConstant(0, dl, MVT::i32));
5625       SDValue VEXTSrc2 =
5626           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5627                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5628
5629       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5630                                    VEXTSrc2,
5631                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5632       Src.WindowBase = -Src.MinElt;
5633     }
5634   }
5635
5636   // Another possible incompatibility occurs from the vector element types. We
5637   // can fix this by bitcasting the source vectors to the same type we intend
5638   // for the shuffle.
5639   for (auto &Src : Sources) {
5640     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5641     if (SrcEltTy == SmallestEltTy)
5642       continue;
5643     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5644     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5645     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5646     Src.WindowBase *= Src.WindowScale;
5647   }
5648
5649   // Final sanity check before we try to actually produce a shuffle.
5650   DEBUG(
5651     for (auto Src : Sources)
5652       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5653   );
5654
5655   // The stars all align, our next step is to produce the mask for the shuffle.
5656   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5657   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5658   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5659     SDValue Entry = Op.getOperand(i);
5660     if (Entry.getOpcode() == ISD::UNDEF)
5661       continue;
5662
5663     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5664     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5665
5666     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5667     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5668     // segment.
5669     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5670     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5671                                VT.getVectorElementType().getSizeInBits());
5672     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5673
5674     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5675     // starting at the appropriate offset.
5676     int *LaneMask = &Mask[i * ResMultiplier];
5677
5678     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5679     ExtractBase += NumElts * (Src - Sources.begin());
5680     for (int j = 0; j < LanesDefined; ++j)
5681       LaneMask[j] = ExtractBase + j;
5682   }
5683
5684   // Final check before we try to produce nonsense...
5685   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5686     return SDValue();
5687
5688   // We can't handle more than two sources. This should have already
5689   // been checked before this point.
5690   assert(Sources.size() <= 2 && "Too many sources!");
5691
5692   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5693   for (unsigned i = 0; i < Sources.size(); ++i)
5694     ShuffleOps[i] = Sources[i].ShuffleVec;
5695
5696   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5697                                          ShuffleOps[1], &Mask[0]);
5698   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5699 }
5700
5701 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5702 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5703 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5704 /// are assumed to be legal.
5705 bool
5706 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5707                                       EVT VT) const {
5708   if (VT.getVectorNumElements() == 4 &&
5709       (VT.is128BitVector() || VT.is64BitVector())) {
5710     unsigned PFIndexes[4];
5711     for (unsigned i = 0; i != 4; ++i) {
5712       if (M[i] < 0)
5713         PFIndexes[i] = 8;
5714       else
5715         PFIndexes[i] = M[i];
5716     }
5717
5718     // Compute the index in the perfect shuffle table.
5719     unsigned PFTableIndex =
5720       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5721     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5722     unsigned Cost = (PFEntry >> 30);
5723
5724     if (Cost <= 4)
5725       return true;
5726   }
5727
5728   bool ReverseVEXT, isV_UNDEF;
5729   unsigned Imm, WhichResult;
5730
5731   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5732   return (EltSize >= 32 ||
5733           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5734           isVREVMask(M, VT, 64) ||
5735           isVREVMask(M, VT, 32) ||
5736           isVREVMask(M, VT, 16) ||
5737           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5738           isVTBLMask(M, VT) ||
5739           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5740           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5741 }
5742
5743 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5744 /// the specified operations to build the shuffle.
5745 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5746                                       SDValue RHS, SelectionDAG &DAG,
5747                                       SDLoc dl) {
5748   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5749   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5750   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5751
5752   enum {
5753     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5754     OP_VREV,
5755     OP_VDUP0,
5756     OP_VDUP1,
5757     OP_VDUP2,
5758     OP_VDUP3,
5759     OP_VEXT1,
5760     OP_VEXT2,
5761     OP_VEXT3,
5762     OP_VUZPL, // VUZP, left result
5763     OP_VUZPR, // VUZP, right result
5764     OP_VZIPL, // VZIP, left result
5765     OP_VZIPR, // VZIP, right result
5766     OP_VTRNL, // VTRN, left result
5767     OP_VTRNR  // VTRN, right result
5768   };
5769
5770   if (OpNum == OP_COPY) {
5771     if (LHSID == (1*9+2)*9+3) return LHS;
5772     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5773     return RHS;
5774   }
5775
5776   SDValue OpLHS, OpRHS;
5777   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5778   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5779   EVT VT = OpLHS.getValueType();
5780
5781   switch (OpNum) {
5782   default: llvm_unreachable("Unknown shuffle opcode!");
5783   case OP_VREV:
5784     // VREV divides the vector in half and swaps within the half.
5785     if (VT.getVectorElementType() == MVT::i32 ||
5786         VT.getVectorElementType() == MVT::f32)
5787       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5788     // vrev <4 x i16> -> VREV32
5789     if (VT.getVectorElementType() == MVT::i16)
5790       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5791     // vrev <4 x i8> -> VREV16
5792     assert(VT.getVectorElementType() == MVT::i8);
5793     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5794   case OP_VDUP0:
5795   case OP_VDUP1:
5796   case OP_VDUP2:
5797   case OP_VDUP3:
5798     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5799                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5800   case OP_VEXT1:
5801   case OP_VEXT2:
5802   case OP_VEXT3:
5803     return DAG.getNode(ARMISD::VEXT, dl, VT,
5804                        OpLHS, OpRHS,
5805                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5806   case OP_VUZPL:
5807   case OP_VUZPR:
5808     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5809                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5810   case OP_VZIPL:
5811   case OP_VZIPR:
5812     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5813                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5814   case OP_VTRNL:
5815   case OP_VTRNR:
5816     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5817                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5818   }
5819 }
5820
5821 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5822                                        ArrayRef<int> ShuffleMask,
5823                                        SelectionDAG &DAG) {
5824   // Check to see if we can use the VTBL instruction.
5825   SDValue V1 = Op.getOperand(0);
5826   SDValue V2 = Op.getOperand(1);
5827   SDLoc DL(Op);
5828
5829   SmallVector<SDValue, 8> VTBLMask;
5830   for (ArrayRef<int>::iterator
5831          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5832     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5833
5834   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5835     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5836                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5837
5838   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5839                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5840 }
5841
5842 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5843                                                       SelectionDAG &DAG) {
5844   SDLoc DL(Op);
5845   SDValue OpLHS = Op.getOperand(0);
5846   EVT VT = OpLHS.getValueType();
5847
5848   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5849          "Expect an v8i16/v16i8 type");
5850   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5851   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5852   // extract the first 8 bytes into the top double word and the last 8 bytes
5853   // into the bottom double word. The v8i16 case is similar.
5854   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5855   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5856                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5857 }
5858
5859 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5860   SDValue V1 = Op.getOperand(0);
5861   SDValue V2 = Op.getOperand(1);
5862   SDLoc dl(Op);
5863   EVT VT = Op.getValueType();
5864   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5865
5866   // Convert shuffles that are directly supported on NEON to target-specific
5867   // DAG nodes, instead of keeping them as shuffles and matching them again
5868   // during code selection.  This is more efficient and avoids the possibility
5869   // of inconsistencies between legalization and selection.
5870   // FIXME: floating-point vectors should be canonicalized to integer vectors
5871   // of the same time so that they get CSEd properly.
5872   ArrayRef<int> ShuffleMask = SVN->getMask();
5873
5874   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5875   if (EltSize <= 32) {
5876     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5877       int Lane = SVN->getSplatIndex();
5878       // If this is undef splat, generate it via "just" vdup, if possible.
5879       if (Lane == -1) Lane = 0;
5880
5881       // Test if V1 is a SCALAR_TO_VECTOR.
5882       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5883         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5884       }
5885       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5886       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5887       // reaches it).
5888       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5889           !isa<ConstantSDNode>(V1.getOperand(0))) {
5890         bool IsScalarToVector = true;
5891         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5892           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5893             IsScalarToVector = false;
5894             break;
5895           }
5896         if (IsScalarToVector)
5897           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5898       }
5899       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5900                          DAG.getConstant(Lane, dl, MVT::i32));
5901     }
5902
5903     bool ReverseVEXT;
5904     unsigned Imm;
5905     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5906       if (ReverseVEXT)
5907         std::swap(V1, V2);
5908       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5909                          DAG.getConstant(Imm, dl, MVT::i32));
5910     }
5911
5912     if (isVREVMask(ShuffleMask, VT, 64))
5913       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5914     if (isVREVMask(ShuffleMask, VT, 32))
5915       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5916     if (isVREVMask(ShuffleMask, VT, 16))
5917       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5918
5919     if (V2->getOpcode() == ISD::UNDEF &&
5920         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5921       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5922                          DAG.getConstant(Imm, dl, MVT::i32));
5923     }
5924
5925     // Check for Neon shuffles that modify both input vectors in place.
5926     // If both results are used, i.e., if there are two shuffles with the same
5927     // source operands and with masks corresponding to both results of one of
5928     // these operations, DAG memoization will ensure that a single node is
5929     // used for both shuffles.
5930     unsigned WhichResult;
5931     bool isV_UNDEF;
5932     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5933             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5934       if (isV_UNDEF)
5935         V2 = V1;
5936       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5937           .getValue(WhichResult);
5938     }
5939
5940     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5941     // shuffles that produce a result larger than their operands with:
5942     //   shuffle(concat(v1, undef), concat(v2, undef))
5943     // ->
5944     //   shuffle(concat(v1, v2), undef)
5945     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5946     //
5947     // This is useful in the general case, but there are special cases where
5948     // native shuffles produce larger results: the two-result ops.
5949     //
5950     // Look through the concat when lowering them:
5951     //   shuffle(concat(v1, v2), undef)
5952     // ->
5953     //   concat(VZIP(v1, v2):0, :1)
5954     //
5955     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5956         V2->getOpcode() == ISD::UNDEF) {
5957       SDValue SubV1 = V1->getOperand(0);
5958       SDValue SubV2 = V1->getOperand(1);
5959       EVT SubVT = SubV1.getValueType();
5960
5961       // We expect these to have been canonicalized to -1.
5962       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5963         return i < (int)VT.getVectorNumElements();
5964       }) && "Unexpected shuffle index into UNDEF operand!");
5965
5966       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5967               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5968         if (isV_UNDEF)
5969           SubV2 = SubV1;
5970         assert((WhichResult == 0) &&
5971                "In-place shuffle of concat can only have one result!");
5972         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5973                                   SubV1, SubV2);
5974         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5975                            Res.getValue(1));
5976       }
5977     }
5978   }
5979
5980   // If the shuffle is not directly supported and it has 4 elements, use
5981   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5982   unsigned NumElts = VT.getVectorNumElements();
5983   if (NumElts == 4) {
5984     unsigned PFIndexes[4];
5985     for (unsigned i = 0; i != 4; ++i) {
5986       if (ShuffleMask[i] < 0)
5987         PFIndexes[i] = 8;
5988       else
5989         PFIndexes[i] = ShuffleMask[i];
5990     }
5991
5992     // Compute the index in the perfect shuffle table.
5993     unsigned PFTableIndex =
5994       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5995     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5996     unsigned Cost = (PFEntry >> 30);
5997
5998     if (Cost <= 4)
5999       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6000   }
6001
6002   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6003   if (EltSize >= 32) {
6004     // Do the expansion with floating-point types, since that is what the VFP
6005     // registers are defined to use, and since i64 is not legal.
6006     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6007     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6008     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6009     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6010     SmallVector<SDValue, 8> Ops;
6011     for (unsigned i = 0; i < NumElts; ++i) {
6012       if (ShuffleMask[i] < 0)
6013         Ops.push_back(DAG.getUNDEF(EltVT));
6014       else
6015         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6016                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6017                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6018                                                   dl, MVT::i32)));
6019     }
6020     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6021     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6022   }
6023
6024   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6025     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6026
6027   if (VT == MVT::v8i8) {
6028     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6029     if (NewOp.getNode())
6030       return NewOp;
6031   }
6032
6033   return SDValue();
6034 }
6035
6036 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6037   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6038   SDValue Lane = Op.getOperand(2);
6039   if (!isa<ConstantSDNode>(Lane))
6040     return SDValue();
6041
6042   return Op;
6043 }
6044
6045 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6046   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6047   SDValue Lane = Op.getOperand(1);
6048   if (!isa<ConstantSDNode>(Lane))
6049     return SDValue();
6050
6051   SDValue Vec = Op.getOperand(0);
6052   if (Op.getValueType() == MVT::i32 &&
6053       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6054     SDLoc dl(Op);
6055     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6056   }
6057
6058   return Op;
6059 }
6060
6061 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6062   // The only time a CONCAT_VECTORS operation can have legal types is when
6063   // two 64-bit vectors are concatenated to a 128-bit vector.
6064   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6065          "unexpected CONCAT_VECTORS");
6066   SDLoc dl(Op);
6067   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6068   SDValue Op0 = Op.getOperand(0);
6069   SDValue Op1 = Op.getOperand(1);
6070   if (Op0.getOpcode() != ISD::UNDEF)
6071     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6072                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6073                       DAG.getIntPtrConstant(0, dl));
6074   if (Op1.getOpcode() != ISD::UNDEF)
6075     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6076                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6077                       DAG.getIntPtrConstant(1, dl));
6078   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6079 }
6080
6081 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6082 /// element has been zero/sign-extended, depending on the isSigned parameter,
6083 /// from an integer type half its size.
6084 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6085                                    bool isSigned) {
6086   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6087   EVT VT = N->getValueType(0);
6088   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6089     SDNode *BVN = N->getOperand(0).getNode();
6090     if (BVN->getValueType(0) != MVT::v4i32 ||
6091         BVN->getOpcode() != ISD::BUILD_VECTOR)
6092       return false;
6093     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6094     unsigned HiElt = 1 - LoElt;
6095     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6096     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6097     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6098     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6099     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6100       return false;
6101     if (isSigned) {
6102       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6103           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6104         return true;
6105     } else {
6106       if (Hi0->isNullValue() && Hi1->isNullValue())
6107         return true;
6108     }
6109     return false;
6110   }
6111
6112   if (N->getOpcode() != ISD::BUILD_VECTOR)
6113     return false;
6114
6115   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6116     SDNode *Elt = N->getOperand(i).getNode();
6117     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6118       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6119       unsigned HalfSize = EltSize / 2;
6120       if (isSigned) {
6121         if (!isIntN(HalfSize, C->getSExtValue()))
6122           return false;
6123       } else {
6124         if (!isUIntN(HalfSize, C->getZExtValue()))
6125           return false;
6126       }
6127       continue;
6128     }
6129     return false;
6130   }
6131
6132   return true;
6133 }
6134
6135 /// isSignExtended - Check if a node is a vector value that is sign-extended
6136 /// or a constant BUILD_VECTOR with sign-extended elements.
6137 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6138   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6139     return true;
6140   if (isExtendedBUILD_VECTOR(N, DAG, true))
6141     return true;
6142   return false;
6143 }
6144
6145 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6146 /// or a constant BUILD_VECTOR with zero-extended elements.
6147 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6148   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6149     return true;
6150   if (isExtendedBUILD_VECTOR(N, DAG, false))
6151     return true;
6152   return false;
6153 }
6154
6155 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6156   if (OrigVT.getSizeInBits() >= 64)
6157     return OrigVT;
6158
6159   assert(OrigVT.isSimple() && "Expecting a simple value type");
6160
6161   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6162   switch (OrigSimpleTy) {
6163   default: llvm_unreachable("Unexpected Vector Type");
6164   case MVT::v2i8:
6165   case MVT::v2i16:
6166      return MVT::v2i32;
6167   case MVT::v4i8:
6168     return  MVT::v4i16;
6169   }
6170 }
6171
6172 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6173 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6174 /// We insert the required extension here to get the vector to fill a D register.
6175 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6176                                             const EVT &OrigTy,
6177                                             const EVT &ExtTy,
6178                                             unsigned ExtOpcode) {
6179   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6180   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6181   // 64-bits we need to insert a new extension so that it will be 64-bits.
6182   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6183   if (OrigTy.getSizeInBits() >= 64)
6184     return N;
6185
6186   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6187   EVT NewVT = getExtensionTo64Bits(OrigTy);
6188
6189   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6190 }
6191
6192 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6193 /// does not do any sign/zero extension. If the original vector is less
6194 /// than 64 bits, an appropriate extension will be added after the load to
6195 /// reach a total size of 64 bits. We have to add the extension separately
6196 /// because ARM does not have a sign/zero extending load for vectors.
6197 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6198   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6199
6200   // The load already has the right type.
6201   if (ExtendedTy == LD->getMemoryVT())
6202     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6203                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6204                 LD->isNonTemporal(), LD->isInvariant(),
6205                 LD->getAlignment());
6206
6207   // We need to create a zextload/sextload. We cannot just create a load
6208   // followed by a zext/zext node because LowerMUL is also run during normal
6209   // operation legalization where we can't create illegal types.
6210   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6211                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6212                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6213                         LD->isNonTemporal(), LD->getAlignment());
6214 }
6215
6216 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6217 /// extending load, or BUILD_VECTOR with extended elements, return the
6218 /// unextended value. The unextended vector should be 64 bits so that it can
6219 /// be used as an operand to a VMULL instruction. If the original vector size
6220 /// before extension is less than 64 bits we add a an extension to resize
6221 /// the vector to 64 bits.
6222 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6223   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6224     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6225                                         N->getOperand(0)->getValueType(0),
6226                                         N->getValueType(0),
6227                                         N->getOpcode());
6228
6229   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6230     return SkipLoadExtensionForVMULL(LD, DAG);
6231
6232   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6233   // have been legalized as a BITCAST from v4i32.
6234   if (N->getOpcode() == ISD::BITCAST) {
6235     SDNode *BVN = N->getOperand(0).getNode();
6236     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6237            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6238     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6239     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6240                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6241   }
6242   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6243   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6244   EVT VT = N->getValueType(0);
6245   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6246   unsigned NumElts = VT.getVectorNumElements();
6247   MVT TruncVT = MVT::getIntegerVT(EltSize);
6248   SmallVector<SDValue, 8> Ops;
6249   SDLoc dl(N);
6250   for (unsigned i = 0; i != NumElts; ++i) {
6251     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6252     const APInt &CInt = C->getAPIntValue();
6253     // Element types smaller than 32 bits are not legal, so use i32 elements.
6254     // The values are implicitly truncated so sext vs. zext doesn't matter.
6255     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6256   }
6257   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6258                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6259 }
6260
6261 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6262   unsigned Opcode = N->getOpcode();
6263   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6264     SDNode *N0 = N->getOperand(0).getNode();
6265     SDNode *N1 = N->getOperand(1).getNode();
6266     return N0->hasOneUse() && N1->hasOneUse() &&
6267       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6268   }
6269   return false;
6270 }
6271
6272 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6273   unsigned Opcode = N->getOpcode();
6274   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6275     SDNode *N0 = N->getOperand(0).getNode();
6276     SDNode *N1 = N->getOperand(1).getNode();
6277     return N0->hasOneUse() && N1->hasOneUse() &&
6278       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6279   }
6280   return false;
6281 }
6282
6283 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6284   // Multiplications are only custom-lowered for 128-bit vectors so that
6285   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6286   EVT VT = Op.getValueType();
6287   assert(VT.is128BitVector() && VT.isInteger() &&
6288          "unexpected type for custom-lowering ISD::MUL");
6289   SDNode *N0 = Op.getOperand(0).getNode();
6290   SDNode *N1 = Op.getOperand(1).getNode();
6291   unsigned NewOpc = 0;
6292   bool isMLA = false;
6293   bool isN0SExt = isSignExtended(N0, DAG);
6294   bool isN1SExt = isSignExtended(N1, DAG);
6295   if (isN0SExt && isN1SExt)
6296     NewOpc = ARMISD::VMULLs;
6297   else {
6298     bool isN0ZExt = isZeroExtended(N0, DAG);
6299     bool isN1ZExt = isZeroExtended(N1, DAG);
6300     if (isN0ZExt && isN1ZExt)
6301       NewOpc = ARMISD::VMULLu;
6302     else if (isN1SExt || isN1ZExt) {
6303       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6304       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6305       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6306         NewOpc = ARMISD::VMULLs;
6307         isMLA = true;
6308       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6309         NewOpc = ARMISD::VMULLu;
6310         isMLA = true;
6311       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6312         std::swap(N0, N1);
6313         NewOpc = ARMISD::VMULLu;
6314         isMLA = true;
6315       }
6316     }
6317
6318     if (!NewOpc) {
6319       if (VT == MVT::v2i64)
6320         // Fall through to expand this.  It is not legal.
6321         return SDValue();
6322       else
6323         // Other vector multiplications are legal.
6324         return Op;
6325     }
6326   }
6327
6328   // Legalize to a VMULL instruction.
6329   SDLoc DL(Op);
6330   SDValue Op0;
6331   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6332   if (!isMLA) {
6333     Op0 = SkipExtensionForVMULL(N0, DAG);
6334     assert(Op0.getValueType().is64BitVector() &&
6335            Op1.getValueType().is64BitVector() &&
6336            "unexpected types for extended operands to VMULL");
6337     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6338   }
6339
6340   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6341   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6342   //   vmull q0, d4, d6
6343   //   vmlal q0, d5, d6
6344   // is faster than
6345   //   vaddl q0, d4, d5
6346   //   vmovl q1, d6
6347   //   vmul  q0, q0, q1
6348   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6349   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6350   EVT Op1VT = Op1.getValueType();
6351   return DAG.getNode(N0->getOpcode(), DL, VT,
6352                      DAG.getNode(NewOpc, DL, VT,
6353                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6354                      DAG.getNode(NewOpc, DL, VT,
6355                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6356 }
6357
6358 static SDValue
6359 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6360   // TODO: Should this propagate fast-math-flags?
6361
6362   // Convert to float
6363   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6364   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6365   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6366   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6367   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6368   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6369   // Get reciprocal estimate.
6370   // float4 recip = vrecpeq_f32(yf);
6371   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6372                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6373                    Y);
6374   // Because char has a smaller range than uchar, we can actually get away
6375   // without any newton steps.  This requires that we use a weird bias
6376   // of 0xb000, however (again, this has been exhaustively tested).
6377   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6378   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6379   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6380   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6381   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6382   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6383   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6384   // Convert back to short.
6385   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6386   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6387   return X;
6388 }
6389
6390 static SDValue
6391 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6392   // TODO: Should this propagate fast-math-flags?
6393
6394   SDValue N2;
6395   // Convert to float.
6396   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6397   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6398   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6399   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6400   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6401   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6402
6403   // Use reciprocal estimate and one refinement step.
6404   // float4 recip = vrecpeq_f32(yf);
6405   // recip *= vrecpsq_f32(yf, recip);
6406   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6407                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6408                    N1);
6409   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6410                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6411                    N1, N2);
6412   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6413   // Because short has a smaller range than ushort, we can actually get away
6414   // with only a single newton step.  This requires that we use a weird bias
6415   // of 89, however (again, this has been exhaustively tested).
6416   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6417   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6418   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6419   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6420   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6421   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6422   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6423   // Convert back to integer and return.
6424   // return vmovn_s32(vcvt_s32_f32(result));
6425   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6426   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6427   return N0;
6428 }
6429
6430 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6431   EVT VT = Op.getValueType();
6432   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6433          "unexpected type for custom-lowering ISD::SDIV");
6434
6435   SDLoc dl(Op);
6436   SDValue N0 = Op.getOperand(0);
6437   SDValue N1 = Op.getOperand(1);
6438   SDValue N2, N3;
6439
6440   if (VT == MVT::v8i8) {
6441     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6442     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6443
6444     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6445                      DAG.getIntPtrConstant(4, dl));
6446     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6447                      DAG.getIntPtrConstant(4, dl));
6448     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6449                      DAG.getIntPtrConstant(0, dl));
6450     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6451                      DAG.getIntPtrConstant(0, dl));
6452
6453     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6454     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6455
6456     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6457     N0 = LowerCONCAT_VECTORS(N0, DAG);
6458
6459     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6460     return N0;
6461   }
6462   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6463 }
6464
6465 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6466   // TODO: Should this propagate fast-math-flags?
6467   EVT VT = Op.getValueType();
6468   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6469          "unexpected type for custom-lowering ISD::UDIV");
6470
6471   SDLoc dl(Op);
6472   SDValue N0 = Op.getOperand(0);
6473   SDValue N1 = Op.getOperand(1);
6474   SDValue N2, N3;
6475
6476   if (VT == MVT::v8i8) {
6477     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6478     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6479
6480     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6481                      DAG.getIntPtrConstant(4, dl));
6482     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6483                      DAG.getIntPtrConstant(4, dl));
6484     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6485                      DAG.getIntPtrConstant(0, dl));
6486     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6487                      DAG.getIntPtrConstant(0, dl));
6488
6489     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6490     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6491
6492     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6493     N0 = LowerCONCAT_VECTORS(N0, DAG);
6494
6495     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6496                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6497                                      MVT::i32),
6498                      N0);
6499     return N0;
6500   }
6501
6502   // v4i16 sdiv ... Convert to float.
6503   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6504   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6505   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6506   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6507   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6508   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6509
6510   // Use reciprocal estimate and two refinement steps.
6511   // float4 recip = vrecpeq_f32(yf);
6512   // recip *= vrecpsq_f32(yf, recip);
6513   // recip *= vrecpsq_f32(yf, recip);
6514   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6515                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6516                    BN1);
6517   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6518                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6519                    BN1, N2);
6520   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6521   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6522                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6523                    BN1, N2);
6524   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6525   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6526   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6527   // and that it will never cause us to return an answer too large).
6528   // float4 result = as_float4(as_int4(xf*recip) + 2);
6529   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6530   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6531   N1 = DAG.getConstant(2, dl, MVT::i32);
6532   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6533   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6534   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6535   // Convert back to integer and return.
6536   // return vmovn_u32(vcvt_s32_f32(result));
6537   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6538   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6539   return N0;
6540 }
6541
6542 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6543   EVT VT = Op.getNode()->getValueType(0);
6544   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6545
6546   unsigned Opc;
6547   bool ExtraOp = false;
6548   switch (Op.getOpcode()) {
6549   default: llvm_unreachable("Invalid code");
6550   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6551   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6552   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6553   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6554   }
6555
6556   if (!ExtraOp)
6557     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6558                        Op.getOperand(1));
6559   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6560                      Op.getOperand(1), Op.getOperand(2));
6561 }
6562
6563 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6564   assert(Subtarget->isTargetDarwin());
6565
6566   // For iOS, we want to call an alternative entry point: __sincos_stret,
6567   // return values are passed via sret.
6568   SDLoc dl(Op);
6569   SDValue Arg = Op.getOperand(0);
6570   EVT ArgVT = Arg.getValueType();
6571   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6572   auto PtrVT = getPointerTy(DAG.getDataLayout());
6573
6574   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6575
6576   // Pair of floats / doubles used to pass the result.
6577   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6578
6579   // Create stack object for sret.
6580   auto &DL = DAG.getDataLayout();
6581   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6582   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6583   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6584   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6585
6586   ArgListTy Args;
6587   ArgListEntry Entry;
6588
6589   Entry.Node = SRet;
6590   Entry.Ty = RetTy->getPointerTo();
6591   Entry.isSExt = false;
6592   Entry.isZExt = false;
6593   Entry.isSRet = true;
6594   Args.push_back(Entry);
6595
6596   Entry.Node = Arg;
6597   Entry.Ty = ArgTy;
6598   Entry.isSExt = false;
6599   Entry.isZExt = false;
6600   Args.push_back(Entry);
6601
6602   const char *LibcallName =
6603       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6604   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6605
6606   TargetLowering::CallLoweringInfo CLI(DAG);
6607   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6608     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6609                std::move(Args), 0)
6610     .setDiscardResult();
6611
6612   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6613
6614   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6615                                 MachinePointerInfo(), false, false, false, 0);
6616
6617   // Address of cos field.
6618   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6619                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6620   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6621                                 MachinePointerInfo(), false, false, false, 0);
6622
6623   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6624   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6625                      LoadSin.getValue(0), LoadCos.getValue(0));
6626 }
6627
6628 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6629                                                   bool Signed,
6630                                                   SDValue &Chain) const {
6631   EVT VT = Op.getValueType();
6632   assert((VT == MVT::i32 || VT == MVT::i64) &&
6633          "unexpected type for custom lowering DIV");
6634   SDLoc dl(Op);
6635
6636   const auto &DL = DAG.getDataLayout();
6637   const auto &TLI = DAG.getTargetLoweringInfo();
6638
6639   const char *Name = nullptr;
6640   if (Signed)
6641     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6642   else
6643     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6644
6645   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6646
6647   ARMTargetLowering::ArgListTy Args;
6648
6649   for (auto AI : {1, 0}) {
6650     ArgListEntry Arg;
6651     Arg.Node = Op.getOperand(AI);
6652     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6653     Args.push_back(Arg);
6654   }
6655
6656   CallLoweringInfo CLI(DAG);
6657   CLI.setDebugLoc(dl)
6658     .setChain(Chain)
6659     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6660                ES, std::move(Args), 0);
6661
6662   return LowerCallTo(CLI).first;
6663 }
6664
6665 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6666                                             bool Signed) const {
6667   assert(Op.getValueType() == MVT::i32 &&
6668          "unexpected type for custom lowering DIV");
6669   SDLoc dl(Op);
6670
6671   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6672                                DAG.getEntryNode(), Op.getOperand(1));
6673
6674   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6675 }
6676
6677 void ARMTargetLowering::ExpandDIV_Windows(
6678     SDValue Op, SelectionDAG &DAG, bool Signed,
6679     SmallVectorImpl<SDValue> &Results) const {
6680   const auto &DL = DAG.getDataLayout();
6681   const auto &TLI = DAG.getTargetLoweringInfo();
6682
6683   assert(Op.getValueType() == MVT::i64 &&
6684          "unexpected type for custom lowering DIV");
6685   SDLoc dl(Op);
6686
6687   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6688                            DAG.getConstant(0, dl, MVT::i32));
6689   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6690                            DAG.getConstant(1, dl, MVT::i32));
6691   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6692
6693   SDValue DBZCHK =
6694       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6695
6696   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6697
6698   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6699   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6700                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6701   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6702
6703   Results.push_back(Lower);
6704   Results.push_back(Upper);
6705 }
6706
6707 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6708   // Monotonic load/store is legal for all targets
6709   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6710     return Op;
6711
6712   // Acquire/Release load/store is not legal for targets without a
6713   // dmb or equivalent available.
6714   return SDValue();
6715 }
6716
6717 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6718                                     SmallVectorImpl<SDValue> &Results,
6719                                     SelectionDAG &DAG,
6720                                     const ARMSubtarget *Subtarget) {
6721   SDLoc DL(N);
6722   // Under Power Management extensions, the cycle-count is:
6723   //    mrc p15, #0, <Rt>, c9, c13, #0
6724   SDValue Ops[] = { N->getOperand(0), // Chain
6725                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6726                     DAG.getConstant(15, DL, MVT::i32),
6727                     DAG.getConstant(0, DL, MVT::i32),
6728                     DAG.getConstant(9, DL, MVT::i32),
6729                     DAG.getConstant(13, DL, MVT::i32),
6730                     DAG.getConstant(0, DL, MVT::i32)
6731   };
6732
6733   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6734                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6735   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6736                                 DAG.getConstant(0, DL, MVT::i32)));
6737   Results.push_back(Cycles32.getValue(1));
6738 }
6739
6740 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6741   switch (Op.getOpcode()) {
6742   default: llvm_unreachable("Don't know how to custom lower this!");
6743   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6744   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6745   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6746   case ISD::GlobalAddress:
6747     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6748     default: llvm_unreachable("unknown object format");
6749     case Triple::COFF:
6750       return LowerGlobalAddressWindows(Op, DAG);
6751     case Triple::ELF:
6752       return LowerGlobalAddressELF(Op, DAG);
6753     case Triple::MachO:
6754       return LowerGlobalAddressDarwin(Op, DAG);
6755     }
6756   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6757   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6758   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6759   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6760   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6761   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6762   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6763   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6764   case ISD::SINT_TO_FP:
6765   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6766   case ISD::FP_TO_SINT:
6767   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6768   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6769   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6770   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6771   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6772   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6773   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6774   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6775                                                                Subtarget);
6776   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6777   case ISD::SHL:
6778   case ISD::SRL:
6779   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6780   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6781   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6782   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6783   case ISD::SRL_PARTS:
6784   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6785   case ISD::CTTZ:
6786   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6787   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6788   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6789   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6790   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6791   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6792   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6793   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6794   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6795   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6796   case ISD::MUL:           return LowerMUL(Op, DAG);
6797   case ISD::SDIV:
6798     if (Subtarget->isTargetWindows())
6799       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6800     return LowerSDIV(Op, DAG);
6801   case ISD::UDIV:
6802     if (Subtarget->isTargetWindows())
6803       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6804     return LowerUDIV(Op, DAG);
6805   case ISD::ADDC:
6806   case ISD::ADDE:
6807   case ISD::SUBC:
6808   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6809   case ISD::SADDO:
6810   case ISD::UADDO:
6811   case ISD::SSUBO:
6812   case ISD::USUBO:
6813     return LowerXALUO(Op, DAG);
6814   case ISD::ATOMIC_LOAD:
6815   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6816   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6817   case ISD::SDIVREM:
6818   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6819   case ISD::DYNAMIC_STACKALLOC:
6820     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6821       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6822     llvm_unreachable("Don't know how to custom lower this!");
6823   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6824   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6825   case ARMISD::WIN__DBZCHK: return SDValue();
6826   }
6827 }
6828
6829 /// ReplaceNodeResults - Replace the results of node with an illegal result
6830 /// type with new values built out of custom code.
6831 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6832                                            SmallVectorImpl<SDValue> &Results,
6833                                            SelectionDAG &DAG) const {
6834   SDValue Res;
6835   switch (N->getOpcode()) {
6836   default:
6837     llvm_unreachable("Don't know how to custom expand this!");
6838   case ISD::READ_REGISTER:
6839     ExpandREAD_REGISTER(N, Results, DAG);
6840     break;
6841   case ISD::BITCAST:
6842     Res = ExpandBITCAST(N, DAG);
6843     break;
6844   case ISD::SRL:
6845   case ISD::SRA:
6846     Res = Expand64BitShift(N, DAG, Subtarget);
6847     break;
6848   case ISD::SREM:
6849   case ISD::UREM:
6850     Res = LowerREM(N, DAG);
6851     break;
6852   case ISD::READCYCLECOUNTER:
6853     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6854     return;
6855   case ISD::UDIV:
6856   case ISD::SDIV:
6857     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6858     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6859                              Results);
6860   }
6861   if (Res.getNode())
6862     Results.push_back(Res);
6863 }
6864
6865 //===----------------------------------------------------------------------===//
6866 //                           ARM Scheduler Hooks
6867 //===----------------------------------------------------------------------===//
6868
6869 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6870 /// registers the function context.
6871 void ARMTargetLowering::
6872 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6873                        MachineBasicBlock *DispatchBB, int FI) const {
6874   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6875   DebugLoc dl = MI->getDebugLoc();
6876   MachineFunction *MF = MBB->getParent();
6877   MachineRegisterInfo *MRI = &MF->getRegInfo();
6878   MachineConstantPool *MCP = MF->getConstantPool();
6879   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6880   const Function *F = MF->getFunction();
6881
6882   bool isThumb = Subtarget->isThumb();
6883   bool isThumb2 = Subtarget->isThumb2();
6884
6885   unsigned PCLabelId = AFI->createPICLabelUId();
6886   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6887   ARMConstantPoolValue *CPV =
6888     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6889   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6890
6891   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6892                                            : &ARM::GPRRegClass;
6893
6894   // Grab constant pool and fixed stack memory operands.
6895   MachineMemOperand *CPMMO =
6896       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6897                                MachineMemOperand::MOLoad, 4, 4);
6898
6899   MachineMemOperand *FIMMOSt =
6900       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6901                                MachineMemOperand::MOStore, 4, 4);
6902
6903   // Load the address of the dispatch MBB into the jump buffer.
6904   if (isThumb2) {
6905     // Incoming value: jbuf
6906     //   ldr.n  r5, LCPI1_1
6907     //   orr    r5, r5, #1
6908     //   add    r5, pc
6909     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6910     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6911     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6912                    .addConstantPoolIndex(CPI)
6913                    .addMemOperand(CPMMO));
6914     // Set the low bit because of thumb mode.
6915     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6916     AddDefaultCC(
6917       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6918                      .addReg(NewVReg1, RegState::Kill)
6919                      .addImm(0x01)));
6920     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6921     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6922       .addReg(NewVReg2, RegState::Kill)
6923       .addImm(PCLabelId);
6924     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6925                    .addReg(NewVReg3, RegState::Kill)
6926                    .addFrameIndex(FI)
6927                    .addImm(36)  // &jbuf[1] :: pc
6928                    .addMemOperand(FIMMOSt));
6929   } else if (isThumb) {
6930     // Incoming value: jbuf
6931     //   ldr.n  r1, LCPI1_4
6932     //   add    r1, pc
6933     //   mov    r2, #1
6934     //   orrs   r1, r2
6935     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6936     //   str    r1, [r2]
6937     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6938     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6939                    .addConstantPoolIndex(CPI)
6940                    .addMemOperand(CPMMO));
6941     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6942     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6943       .addReg(NewVReg1, RegState::Kill)
6944       .addImm(PCLabelId);
6945     // Set the low bit because of thumb mode.
6946     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6947     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6948                    .addReg(ARM::CPSR, RegState::Define)
6949                    .addImm(1));
6950     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6951     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6952                    .addReg(ARM::CPSR, RegState::Define)
6953                    .addReg(NewVReg2, RegState::Kill)
6954                    .addReg(NewVReg3, RegState::Kill));
6955     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6956     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6957             .addFrameIndex(FI)
6958             .addImm(36); // &jbuf[1] :: pc
6959     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6960                    .addReg(NewVReg4, RegState::Kill)
6961                    .addReg(NewVReg5, RegState::Kill)
6962                    .addImm(0)
6963                    .addMemOperand(FIMMOSt));
6964   } else {
6965     // Incoming value: jbuf
6966     //   ldr  r1, LCPI1_1
6967     //   add  r1, pc, r1
6968     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6969     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6970     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6971                    .addConstantPoolIndex(CPI)
6972                    .addImm(0)
6973                    .addMemOperand(CPMMO));
6974     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6975     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6976                    .addReg(NewVReg1, RegState::Kill)
6977                    .addImm(PCLabelId));
6978     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6979                    .addReg(NewVReg2, RegState::Kill)
6980                    .addFrameIndex(FI)
6981                    .addImm(36)  // &jbuf[1] :: pc
6982                    .addMemOperand(FIMMOSt));
6983   }
6984 }
6985
6986 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6987                                               MachineBasicBlock *MBB) const {
6988   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6989   DebugLoc dl = MI->getDebugLoc();
6990   MachineFunction *MF = MBB->getParent();
6991   MachineRegisterInfo *MRI = &MF->getRegInfo();
6992   MachineFrameInfo *MFI = MF->getFrameInfo();
6993   int FI = MFI->getFunctionContextIndex();
6994
6995   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6996                                                         : &ARM::GPRnopcRegClass;
6997
6998   // Get a mapping of the call site numbers to all of the landing pads they're
6999   // associated with.
7000   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7001   unsigned MaxCSNum = 0;
7002   MachineModuleInfo &MMI = MF->getMMI();
7003   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7004        ++BB) {
7005     if (!BB->isEHPad()) continue;
7006
7007     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7008     // pad.
7009     for (MachineBasicBlock::iterator
7010            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7011       if (!II->isEHLabel()) continue;
7012
7013       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7014       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7015
7016       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7017       for (SmallVectorImpl<unsigned>::iterator
7018              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7019            CSI != CSE; ++CSI) {
7020         CallSiteNumToLPad[*CSI].push_back(&*BB);
7021         MaxCSNum = std::max(MaxCSNum, *CSI);
7022       }
7023       break;
7024     }
7025   }
7026
7027   // Get an ordered list of the machine basic blocks for the jump table.
7028   std::vector<MachineBasicBlock*> LPadList;
7029   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7030   LPadList.reserve(CallSiteNumToLPad.size());
7031   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7032     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7033     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7034            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7035       LPadList.push_back(*II);
7036       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7037     }
7038   }
7039
7040   assert(!LPadList.empty() &&
7041          "No landing pad destinations for the dispatch jump table!");
7042
7043   // Create the jump table and associated information.
7044   MachineJumpTableInfo *JTI =
7045     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7046   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7047   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7048
7049   // Create the MBBs for the dispatch code.
7050
7051   // Shove the dispatch's address into the return slot in the function context.
7052   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7053   DispatchBB->setIsEHPad();
7054
7055   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7056   unsigned trap_opcode;
7057   if (Subtarget->isThumb())
7058     trap_opcode = ARM::tTRAP;
7059   else
7060     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7061
7062   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7063   DispatchBB->addSuccessor(TrapBB);
7064
7065   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7066   DispatchBB->addSuccessor(DispContBB);
7067
7068   // Insert and MBBs.
7069   MF->insert(MF->end(), DispatchBB);
7070   MF->insert(MF->end(), DispContBB);
7071   MF->insert(MF->end(), TrapBB);
7072
7073   // Insert code into the entry block that creates and registers the function
7074   // context.
7075   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7076
7077   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7078       MachinePointerInfo::getFixedStack(*MF, FI),
7079       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7080
7081   MachineInstrBuilder MIB;
7082   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7083
7084   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7085   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7086
7087   // Add a register mask with no preserved registers.  This results in all
7088   // registers being marked as clobbered.
7089   MIB.addRegMask(RI.getNoPreservedMask());
7090
7091   unsigned NumLPads = LPadList.size();
7092   if (Subtarget->isThumb2()) {
7093     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7094     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7095                    .addFrameIndex(FI)
7096                    .addImm(4)
7097                    .addMemOperand(FIMMOLd));
7098
7099     if (NumLPads < 256) {
7100       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7101                      .addReg(NewVReg1)
7102                      .addImm(LPadList.size()));
7103     } else {
7104       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7105       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7106                      .addImm(NumLPads & 0xFFFF));
7107
7108       unsigned VReg2 = VReg1;
7109       if ((NumLPads & 0xFFFF0000) != 0) {
7110         VReg2 = MRI->createVirtualRegister(TRC);
7111         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7112                        .addReg(VReg1)
7113                        .addImm(NumLPads >> 16));
7114       }
7115
7116       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7117                      .addReg(NewVReg1)
7118                      .addReg(VReg2));
7119     }
7120
7121     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7122       .addMBB(TrapBB)
7123       .addImm(ARMCC::HI)
7124       .addReg(ARM::CPSR);
7125
7126     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7127     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7128                    .addJumpTableIndex(MJTI));
7129
7130     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7131     AddDefaultCC(
7132       AddDefaultPred(
7133         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7134         .addReg(NewVReg3, RegState::Kill)
7135         .addReg(NewVReg1)
7136         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7137
7138     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7139       .addReg(NewVReg4, RegState::Kill)
7140       .addReg(NewVReg1)
7141       .addJumpTableIndex(MJTI);
7142   } else if (Subtarget->isThumb()) {
7143     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7144     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7145                    .addFrameIndex(FI)
7146                    .addImm(1)
7147                    .addMemOperand(FIMMOLd));
7148
7149     if (NumLPads < 256) {
7150       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7151                      .addReg(NewVReg1)
7152                      .addImm(NumLPads));
7153     } else {
7154       MachineConstantPool *ConstantPool = MF->getConstantPool();
7155       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7156       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7157
7158       // MachineConstantPool wants an explicit alignment.
7159       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7160       if (Align == 0)
7161         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7162       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7163
7164       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7165       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7166                      .addReg(VReg1, RegState::Define)
7167                      .addConstantPoolIndex(Idx));
7168       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7169                      .addReg(NewVReg1)
7170                      .addReg(VReg1));
7171     }
7172
7173     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7174       .addMBB(TrapBB)
7175       .addImm(ARMCC::HI)
7176       .addReg(ARM::CPSR);
7177
7178     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7179     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7180                    .addReg(ARM::CPSR, RegState::Define)
7181                    .addReg(NewVReg1)
7182                    .addImm(2));
7183
7184     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7185     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7186                    .addJumpTableIndex(MJTI));
7187
7188     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7189     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7190                    .addReg(ARM::CPSR, RegState::Define)
7191                    .addReg(NewVReg2, RegState::Kill)
7192                    .addReg(NewVReg3));
7193
7194     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7195         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7196
7197     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7198     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7199                    .addReg(NewVReg4, RegState::Kill)
7200                    .addImm(0)
7201                    .addMemOperand(JTMMOLd));
7202
7203     unsigned NewVReg6 = NewVReg5;
7204     if (RelocM == Reloc::PIC_) {
7205       NewVReg6 = MRI->createVirtualRegister(TRC);
7206       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7207                      .addReg(ARM::CPSR, RegState::Define)
7208                      .addReg(NewVReg5, RegState::Kill)
7209                      .addReg(NewVReg3));
7210     }
7211
7212     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7213       .addReg(NewVReg6, RegState::Kill)
7214       .addJumpTableIndex(MJTI);
7215   } else {
7216     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7217     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7218                    .addFrameIndex(FI)
7219                    .addImm(4)
7220                    .addMemOperand(FIMMOLd));
7221
7222     if (NumLPads < 256) {
7223       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7224                      .addReg(NewVReg1)
7225                      .addImm(NumLPads));
7226     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7227       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7228       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7229                      .addImm(NumLPads & 0xFFFF));
7230
7231       unsigned VReg2 = VReg1;
7232       if ((NumLPads & 0xFFFF0000) != 0) {
7233         VReg2 = MRI->createVirtualRegister(TRC);
7234         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7235                        .addReg(VReg1)
7236                        .addImm(NumLPads >> 16));
7237       }
7238
7239       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7240                      .addReg(NewVReg1)
7241                      .addReg(VReg2));
7242     } else {
7243       MachineConstantPool *ConstantPool = MF->getConstantPool();
7244       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7245       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7246
7247       // MachineConstantPool wants an explicit alignment.
7248       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7249       if (Align == 0)
7250         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7251       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7252
7253       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7254       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7255                      .addReg(VReg1, RegState::Define)
7256                      .addConstantPoolIndex(Idx)
7257                      .addImm(0));
7258       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7259                      .addReg(NewVReg1)
7260                      .addReg(VReg1, RegState::Kill));
7261     }
7262
7263     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7264       .addMBB(TrapBB)
7265       .addImm(ARMCC::HI)
7266       .addReg(ARM::CPSR);
7267
7268     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7269     AddDefaultCC(
7270       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7271                      .addReg(NewVReg1)
7272                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7273     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7274     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7275                    .addJumpTableIndex(MJTI));
7276
7277     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7278         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7279     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7280     AddDefaultPred(
7281       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7282       .addReg(NewVReg3, RegState::Kill)
7283       .addReg(NewVReg4)
7284       .addImm(0)
7285       .addMemOperand(JTMMOLd));
7286
7287     if (RelocM == Reloc::PIC_) {
7288       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7289         .addReg(NewVReg5, RegState::Kill)
7290         .addReg(NewVReg4)
7291         .addJumpTableIndex(MJTI);
7292     } else {
7293       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7294         .addReg(NewVReg5, RegState::Kill)
7295         .addJumpTableIndex(MJTI);
7296     }
7297   }
7298
7299   // Add the jump table entries as successors to the MBB.
7300   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7301   for (std::vector<MachineBasicBlock*>::iterator
7302          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7303     MachineBasicBlock *CurMBB = *I;
7304     if (SeenMBBs.insert(CurMBB).second)
7305       DispContBB->addSuccessor(CurMBB);
7306   }
7307
7308   // N.B. the order the invoke BBs are processed in doesn't matter here.
7309   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7310   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7311   for (MachineBasicBlock *BB : InvokeBBs) {
7312
7313     // Remove the landing pad successor from the invoke block and replace it
7314     // with the new dispatch block.
7315     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7316                                                   BB->succ_end());
7317     while (!Successors.empty()) {
7318       MachineBasicBlock *SMBB = Successors.pop_back_val();
7319       if (SMBB->isEHPad()) {
7320         BB->removeSuccessor(SMBB);
7321         MBBLPads.push_back(SMBB);
7322       }
7323     }
7324
7325     BB->addSuccessor(DispatchBB);
7326
7327     // Find the invoke call and mark all of the callee-saved registers as
7328     // 'implicit defined' so that they're spilled. This prevents code from
7329     // moving instructions to before the EH block, where they will never be
7330     // executed.
7331     for (MachineBasicBlock::reverse_iterator
7332            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7333       if (!II->isCall()) continue;
7334
7335       DenseMap<unsigned, bool> DefRegs;
7336       for (MachineInstr::mop_iterator
7337              OI = II->operands_begin(), OE = II->operands_end();
7338            OI != OE; ++OI) {
7339         if (!OI->isReg()) continue;
7340         DefRegs[OI->getReg()] = true;
7341       }
7342
7343       MachineInstrBuilder MIB(*MF, &*II);
7344
7345       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7346         unsigned Reg = SavedRegs[i];
7347         if (Subtarget->isThumb2() &&
7348             !ARM::tGPRRegClass.contains(Reg) &&
7349             !ARM::hGPRRegClass.contains(Reg))
7350           continue;
7351         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7352           continue;
7353         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7354           continue;
7355         if (!DefRegs[Reg])
7356           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7357       }
7358
7359       break;
7360     }
7361   }
7362
7363   // Mark all former landing pads as non-landing pads. The dispatch is the only
7364   // landing pad now.
7365   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7366          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7367     (*I)->setIsEHPad(false);
7368
7369   // The instruction is gone now.
7370   MI->eraseFromParent();
7371 }
7372
7373 static
7374 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7375   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7376        E = MBB->succ_end(); I != E; ++I)
7377     if (*I != Succ)
7378       return *I;
7379   llvm_unreachable("Expecting a BB with two successors!");
7380 }
7381
7382 /// Return the load opcode for a given load size. If load size >= 8,
7383 /// neon opcode will be returned.
7384 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7385   if (LdSize >= 8)
7386     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7387                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7388   if (IsThumb1)
7389     return LdSize == 4 ? ARM::tLDRi
7390                        : LdSize == 2 ? ARM::tLDRHi
7391                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7392   if (IsThumb2)
7393     return LdSize == 4 ? ARM::t2LDR_POST
7394                        : LdSize == 2 ? ARM::t2LDRH_POST
7395                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7396   return LdSize == 4 ? ARM::LDR_POST_IMM
7397                      : LdSize == 2 ? ARM::LDRH_POST
7398                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7399 }
7400
7401 /// Return the store opcode for a given store size. If store size >= 8,
7402 /// neon opcode will be returned.
7403 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7404   if (StSize >= 8)
7405     return StSize == 16 ? ARM::VST1q32wb_fixed
7406                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7407   if (IsThumb1)
7408     return StSize == 4 ? ARM::tSTRi
7409                        : StSize == 2 ? ARM::tSTRHi
7410                                      : StSize == 1 ? ARM::tSTRBi : 0;
7411   if (IsThumb2)
7412     return StSize == 4 ? ARM::t2STR_POST
7413                        : StSize == 2 ? ARM::t2STRH_POST
7414                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7415   return StSize == 4 ? ARM::STR_POST_IMM
7416                      : StSize == 2 ? ARM::STRH_POST
7417                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7418 }
7419
7420 /// Emit a post-increment load operation with given size. The instructions
7421 /// will be added to BB at Pos.
7422 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7423                        const TargetInstrInfo *TII, DebugLoc dl,
7424                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7425                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7426   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7427   assert(LdOpc != 0 && "Should have a load opcode");
7428   if (LdSize >= 8) {
7429     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7430                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7431                        .addImm(0));
7432   } else if (IsThumb1) {
7433     // load + update AddrIn
7434     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7435                        .addReg(AddrIn).addImm(0));
7436     MachineInstrBuilder MIB =
7437         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7438     MIB = AddDefaultT1CC(MIB);
7439     MIB.addReg(AddrIn).addImm(LdSize);
7440     AddDefaultPred(MIB);
7441   } else if (IsThumb2) {
7442     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7443                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7444                        .addImm(LdSize));
7445   } else { // arm
7446     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7447                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7448                        .addReg(0).addImm(LdSize));
7449   }
7450 }
7451
7452 /// Emit a post-increment store operation with given size. The instructions
7453 /// will be added to BB at Pos.
7454 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7455                        const TargetInstrInfo *TII, DebugLoc dl,
7456                        unsigned StSize, unsigned Data, unsigned AddrIn,
7457                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7458   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7459   assert(StOpc != 0 && "Should have a store opcode");
7460   if (StSize >= 8) {
7461     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7462                        .addReg(AddrIn).addImm(0).addReg(Data));
7463   } else if (IsThumb1) {
7464     // store + update AddrIn
7465     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7466                        .addReg(AddrIn).addImm(0));
7467     MachineInstrBuilder MIB =
7468         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7469     MIB = AddDefaultT1CC(MIB);
7470     MIB.addReg(AddrIn).addImm(StSize);
7471     AddDefaultPred(MIB);
7472   } else if (IsThumb2) {
7473     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7474                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7475   } else { // arm
7476     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7477                        .addReg(Data).addReg(AddrIn).addReg(0)
7478                        .addImm(StSize));
7479   }
7480 }
7481
7482 MachineBasicBlock *
7483 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7484                                    MachineBasicBlock *BB) const {
7485   // This pseudo instruction has 3 operands: dst, src, size
7486   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7487   // Otherwise, we will generate unrolled scalar copies.
7488   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7489   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7490   MachineFunction::iterator It = ++BB->getIterator();
7491
7492   unsigned dest = MI->getOperand(0).getReg();
7493   unsigned src = MI->getOperand(1).getReg();
7494   unsigned SizeVal = MI->getOperand(2).getImm();
7495   unsigned Align = MI->getOperand(3).getImm();
7496   DebugLoc dl = MI->getDebugLoc();
7497
7498   MachineFunction *MF = BB->getParent();
7499   MachineRegisterInfo &MRI = MF->getRegInfo();
7500   unsigned UnitSize = 0;
7501   const TargetRegisterClass *TRC = nullptr;
7502   const TargetRegisterClass *VecTRC = nullptr;
7503
7504   bool IsThumb1 = Subtarget->isThumb1Only();
7505   bool IsThumb2 = Subtarget->isThumb2();
7506
7507   if (Align & 1) {
7508     UnitSize = 1;
7509   } else if (Align & 2) {
7510     UnitSize = 2;
7511   } else {
7512     // Check whether we can use NEON instructions.
7513     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7514         Subtarget->hasNEON()) {
7515       if ((Align % 16 == 0) && SizeVal >= 16)
7516         UnitSize = 16;
7517       else if ((Align % 8 == 0) && SizeVal >= 8)
7518         UnitSize = 8;
7519     }
7520     // Can't use NEON instructions.
7521     if (UnitSize == 0)
7522       UnitSize = 4;
7523   }
7524
7525   // Select the correct opcode and register class for unit size load/store
7526   bool IsNeon = UnitSize >= 8;
7527   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7528   if (IsNeon)
7529     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7530                             : UnitSize == 8 ? &ARM::DPRRegClass
7531                                             : nullptr;
7532
7533   unsigned BytesLeft = SizeVal % UnitSize;
7534   unsigned LoopSize = SizeVal - BytesLeft;
7535
7536   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7537     // Use LDR and STR to copy.
7538     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7539     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7540     unsigned srcIn = src;
7541     unsigned destIn = dest;
7542     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7543       unsigned srcOut = MRI.createVirtualRegister(TRC);
7544       unsigned destOut = MRI.createVirtualRegister(TRC);
7545       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7546       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7547                  IsThumb1, IsThumb2);
7548       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7549                  IsThumb1, IsThumb2);
7550       srcIn = srcOut;
7551       destIn = destOut;
7552     }
7553
7554     // Handle the leftover bytes with LDRB and STRB.
7555     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7556     // [destOut] = STRB_POST(scratch, destIn, 1)
7557     for (unsigned i = 0; i < BytesLeft; i++) {
7558       unsigned srcOut = MRI.createVirtualRegister(TRC);
7559       unsigned destOut = MRI.createVirtualRegister(TRC);
7560       unsigned scratch = MRI.createVirtualRegister(TRC);
7561       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7562                  IsThumb1, IsThumb2);
7563       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7564                  IsThumb1, IsThumb2);
7565       srcIn = srcOut;
7566       destIn = destOut;
7567     }
7568     MI->eraseFromParent();   // The instruction is gone now.
7569     return BB;
7570   }
7571
7572   // Expand the pseudo op to a loop.
7573   // thisMBB:
7574   //   ...
7575   //   movw varEnd, # --> with thumb2
7576   //   movt varEnd, #
7577   //   ldrcp varEnd, idx --> without thumb2
7578   //   fallthrough --> loopMBB
7579   // loopMBB:
7580   //   PHI varPhi, varEnd, varLoop
7581   //   PHI srcPhi, src, srcLoop
7582   //   PHI destPhi, dst, destLoop
7583   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7584   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7585   //   subs varLoop, varPhi, #UnitSize
7586   //   bne loopMBB
7587   //   fallthrough --> exitMBB
7588   // exitMBB:
7589   //   epilogue to handle left-over bytes
7590   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7591   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7592   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7593   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7594   MF->insert(It, loopMBB);
7595   MF->insert(It, exitMBB);
7596
7597   // Transfer the remainder of BB and its successor edges to exitMBB.
7598   exitMBB->splice(exitMBB->begin(), BB,
7599                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7600   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7601
7602   // Load an immediate to varEnd.
7603   unsigned varEnd = MRI.createVirtualRegister(TRC);
7604   if (Subtarget->useMovt(*MF)) {
7605     unsigned Vtmp = varEnd;
7606     if ((LoopSize & 0xFFFF0000) != 0)
7607       Vtmp = MRI.createVirtualRegister(TRC);
7608     AddDefaultPred(BuildMI(BB, dl,
7609                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7610                            Vtmp).addImm(LoopSize & 0xFFFF));
7611
7612     if ((LoopSize & 0xFFFF0000) != 0)
7613       AddDefaultPred(BuildMI(BB, dl,
7614                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7615                              varEnd)
7616                          .addReg(Vtmp)
7617                          .addImm(LoopSize >> 16));
7618   } else {
7619     MachineConstantPool *ConstantPool = MF->getConstantPool();
7620     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7621     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7622
7623     // MachineConstantPool wants an explicit alignment.
7624     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7625     if (Align == 0)
7626       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7627     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7628
7629     if (IsThumb1)
7630       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7631           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7632     else
7633       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7634           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7635   }
7636   BB->addSuccessor(loopMBB);
7637
7638   // Generate the loop body:
7639   //   varPhi = PHI(varLoop, varEnd)
7640   //   srcPhi = PHI(srcLoop, src)
7641   //   destPhi = PHI(destLoop, dst)
7642   MachineBasicBlock *entryBB = BB;
7643   BB = loopMBB;
7644   unsigned varLoop = MRI.createVirtualRegister(TRC);
7645   unsigned varPhi = MRI.createVirtualRegister(TRC);
7646   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7647   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7648   unsigned destLoop = MRI.createVirtualRegister(TRC);
7649   unsigned destPhi = MRI.createVirtualRegister(TRC);
7650
7651   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7652     .addReg(varLoop).addMBB(loopMBB)
7653     .addReg(varEnd).addMBB(entryBB);
7654   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7655     .addReg(srcLoop).addMBB(loopMBB)
7656     .addReg(src).addMBB(entryBB);
7657   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7658     .addReg(destLoop).addMBB(loopMBB)
7659     .addReg(dest).addMBB(entryBB);
7660
7661   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7662   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7663   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7664   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7665              IsThumb1, IsThumb2);
7666   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7667              IsThumb1, IsThumb2);
7668
7669   // Decrement loop variable by UnitSize.
7670   if (IsThumb1) {
7671     MachineInstrBuilder MIB =
7672         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7673     MIB = AddDefaultT1CC(MIB);
7674     MIB.addReg(varPhi).addImm(UnitSize);
7675     AddDefaultPred(MIB);
7676   } else {
7677     MachineInstrBuilder MIB =
7678         BuildMI(*BB, BB->end(), dl,
7679                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7680     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7681     MIB->getOperand(5).setReg(ARM::CPSR);
7682     MIB->getOperand(5).setIsDef(true);
7683   }
7684   BuildMI(*BB, BB->end(), dl,
7685           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7686       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7687
7688   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7689   BB->addSuccessor(loopMBB);
7690   BB->addSuccessor(exitMBB);
7691
7692   // Add epilogue to handle BytesLeft.
7693   BB = exitMBB;
7694   MachineInstr *StartOfExit = exitMBB->begin();
7695
7696   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7697   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7698   unsigned srcIn = srcLoop;
7699   unsigned destIn = destLoop;
7700   for (unsigned i = 0; i < BytesLeft; i++) {
7701     unsigned srcOut = MRI.createVirtualRegister(TRC);
7702     unsigned destOut = MRI.createVirtualRegister(TRC);
7703     unsigned scratch = MRI.createVirtualRegister(TRC);
7704     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7705                IsThumb1, IsThumb2);
7706     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7707                IsThumb1, IsThumb2);
7708     srcIn = srcOut;
7709     destIn = destOut;
7710   }
7711
7712   MI->eraseFromParent();   // The instruction is gone now.
7713   return BB;
7714 }
7715
7716 MachineBasicBlock *
7717 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7718                                        MachineBasicBlock *MBB) const {
7719   const TargetMachine &TM = getTargetMachine();
7720   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7721   DebugLoc DL = MI->getDebugLoc();
7722
7723   assert(Subtarget->isTargetWindows() &&
7724          "__chkstk is only supported on Windows");
7725   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7726
7727   // __chkstk takes the number of words to allocate on the stack in R4, and
7728   // returns the stack adjustment in number of bytes in R4.  This will not
7729   // clober any other registers (other than the obvious lr).
7730   //
7731   // Although, technically, IP should be considered a register which may be
7732   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7733   // thumb-2 environment, so there is no interworking required.  As a result, we
7734   // do not expect a veneer to be emitted by the linker, clobbering IP.
7735   //
7736   // Each module receives its own copy of __chkstk, so no import thunk is
7737   // required, again, ensuring that IP is not clobbered.
7738   //
7739   // Finally, although some linkers may theoretically provide a trampoline for
7740   // out of range calls (which is quite common due to a 32M range limitation of
7741   // branches for Thumb), we can generate the long-call version via
7742   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7743   // IP.
7744
7745   switch (TM.getCodeModel()) {
7746   case CodeModel::Small:
7747   case CodeModel::Medium:
7748   case CodeModel::Default:
7749   case CodeModel::Kernel:
7750     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7751       .addImm((unsigned)ARMCC::AL).addReg(0)
7752       .addExternalSymbol("__chkstk")
7753       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7754       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7755       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7756     break;
7757   case CodeModel::Large:
7758   case CodeModel::JITDefault: {
7759     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7760     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7761
7762     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7763       .addExternalSymbol("__chkstk");
7764     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7765       .addImm((unsigned)ARMCC::AL).addReg(0)
7766       .addReg(Reg, RegState::Kill)
7767       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7768       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7769       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7770     break;
7771   }
7772   }
7773
7774   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7775                                       ARM::SP)
7776                               .addReg(ARM::SP).addReg(ARM::R4)));
7777
7778   MI->eraseFromParent();
7779   return MBB;
7780 }
7781
7782 MachineBasicBlock *
7783 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7784                                        MachineBasicBlock *MBB) const {
7785   DebugLoc DL = MI->getDebugLoc();
7786   MachineFunction *MF = MBB->getParent();
7787   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7788
7789   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7790   MF->push_back(ContBB);
7791   ContBB->splice(ContBB->begin(), MBB,
7792                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7793   MBB->addSuccessor(ContBB);
7794
7795   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7796   MF->push_back(TrapBB);
7797   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7798   MBB->addSuccessor(TrapBB);
7799
7800   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7801       .addReg(MI->getOperand(0).getReg())
7802       .addMBB(TrapBB);
7803
7804   MI->eraseFromParent();
7805   return ContBB;
7806 }
7807
7808 MachineBasicBlock *
7809 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7810                                                MachineBasicBlock *BB) const {
7811   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7812   DebugLoc dl = MI->getDebugLoc();
7813   bool isThumb2 = Subtarget->isThumb2();
7814   switch (MI->getOpcode()) {
7815   default: {
7816     MI->dump();
7817     llvm_unreachable("Unexpected instr type to insert");
7818   }
7819   // The Thumb2 pre-indexed stores have the same MI operands, they just
7820   // define them differently in the .td files from the isel patterns, so
7821   // they need pseudos.
7822   case ARM::t2STR_preidx:
7823     MI->setDesc(TII->get(ARM::t2STR_PRE));
7824     return BB;
7825   case ARM::t2STRB_preidx:
7826     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7827     return BB;
7828   case ARM::t2STRH_preidx:
7829     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7830     return BB;
7831
7832   case ARM::STRi_preidx:
7833   case ARM::STRBi_preidx: {
7834     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7835       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7836     // Decode the offset.
7837     unsigned Offset = MI->getOperand(4).getImm();
7838     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7839     Offset = ARM_AM::getAM2Offset(Offset);
7840     if (isSub)
7841       Offset = -Offset;
7842
7843     MachineMemOperand *MMO = *MI->memoperands_begin();
7844     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7845       .addOperand(MI->getOperand(0))  // Rn_wb
7846       .addOperand(MI->getOperand(1))  // Rt
7847       .addOperand(MI->getOperand(2))  // Rn
7848       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7849       .addOperand(MI->getOperand(5))  // pred
7850       .addOperand(MI->getOperand(6))
7851       .addMemOperand(MMO);
7852     MI->eraseFromParent();
7853     return BB;
7854   }
7855   case ARM::STRr_preidx:
7856   case ARM::STRBr_preidx:
7857   case ARM::STRH_preidx: {
7858     unsigned NewOpc;
7859     switch (MI->getOpcode()) {
7860     default: llvm_unreachable("unexpected opcode!");
7861     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7862     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7863     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7864     }
7865     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7866     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7867       MIB.addOperand(MI->getOperand(i));
7868     MI->eraseFromParent();
7869     return BB;
7870   }
7871
7872   case ARM::tMOVCCr_pseudo: {
7873     // To "insert" a SELECT_CC instruction, we actually have to insert the
7874     // diamond control-flow pattern.  The incoming instruction knows the
7875     // destination vreg to set, the condition code register to branch on, the
7876     // true/false values to select between, and a branch opcode to use.
7877     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7878     MachineFunction::iterator It = ++BB->getIterator();
7879
7880     //  thisMBB:
7881     //  ...
7882     //   TrueVal = ...
7883     //   cmpTY ccX, r1, r2
7884     //   bCC copy1MBB
7885     //   fallthrough --> copy0MBB
7886     MachineBasicBlock *thisMBB  = BB;
7887     MachineFunction *F = BB->getParent();
7888     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7889     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7890     F->insert(It, copy0MBB);
7891     F->insert(It, sinkMBB);
7892
7893     // Transfer the remainder of BB and its successor edges to sinkMBB.
7894     sinkMBB->splice(sinkMBB->begin(), BB,
7895                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7896     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7897
7898     BB->addSuccessor(copy0MBB);
7899     BB->addSuccessor(sinkMBB);
7900
7901     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7902       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7903
7904     //  copy0MBB:
7905     //   %FalseValue = ...
7906     //   # fallthrough to sinkMBB
7907     BB = copy0MBB;
7908
7909     // Update machine-CFG edges
7910     BB->addSuccessor(sinkMBB);
7911
7912     //  sinkMBB:
7913     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7914     //  ...
7915     BB = sinkMBB;
7916     BuildMI(*BB, BB->begin(), dl,
7917             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7918       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7919       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7920
7921     MI->eraseFromParent();   // The pseudo instruction is gone now.
7922     return BB;
7923   }
7924
7925   case ARM::BCCi64:
7926   case ARM::BCCZi64: {
7927     // If there is an unconditional branch to the other successor, remove it.
7928     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7929
7930     // Compare both parts that make up the double comparison separately for
7931     // equality.
7932     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7933
7934     unsigned LHS1 = MI->getOperand(1).getReg();
7935     unsigned LHS2 = MI->getOperand(2).getReg();
7936     if (RHSisZero) {
7937       AddDefaultPred(BuildMI(BB, dl,
7938                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7939                      .addReg(LHS1).addImm(0));
7940       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7941         .addReg(LHS2).addImm(0)
7942         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7943     } else {
7944       unsigned RHS1 = MI->getOperand(3).getReg();
7945       unsigned RHS2 = MI->getOperand(4).getReg();
7946       AddDefaultPred(BuildMI(BB, dl,
7947                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7948                      .addReg(LHS1).addReg(RHS1));
7949       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7950         .addReg(LHS2).addReg(RHS2)
7951         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7952     }
7953
7954     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7955     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7956     if (MI->getOperand(0).getImm() == ARMCC::NE)
7957       std::swap(destMBB, exitMBB);
7958
7959     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7960       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7961     if (isThumb2)
7962       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7963     else
7964       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7965
7966     MI->eraseFromParent();   // The pseudo instruction is gone now.
7967     return BB;
7968   }
7969
7970   case ARM::Int_eh_sjlj_setjmp:
7971   case ARM::Int_eh_sjlj_setjmp_nofp:
7972   case ARM::tInt_eh_sjlj_setjmp:
7973   case ARM::t2Int_eh_sjlj_setjmp:
7974   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7975     return BB;
7976
7977   case ARM::Int_eh_sjlj_setup_dispatch:
7978     EmitSjLjDispatchBlock(MI, BB);
7979     return BB;
7980
7981   case ARM::ABS:
7982   case ARM::t2ABS: {
7983     // To insert an ABS instruction, we have to insert the
7984     // diamond control-flow pattern.  The incoming instruction knows the
7985     // source vreg to test against 0, the destination vreg to set,
7986     // the condition code register to branch on, the
7987     // true/false values to select between, and a branch opcode to use.
7988     // It transforms
7989     //     V1 = ABS V0
7990     // into
7991     //     V2 = MOVS V0
7992     //     BCC                      (branch to SinkBB if V0 >= 0)
7993     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7994     //     SinkBB: V1 = PHI(V2, V3)
7995     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7996     MachineFunction::iterator BBI = ++BB->getIterator();
7997     MachineFunction *Fn = BB->getParent();
7998     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7999     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8000     Fn->insert(BBI, RSBBB);
8001     Fn->insert(BBI, SinkBB);
8002
8003     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8004     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8005     bool ABSSrcKIll = MI->getOperand(1).isKill();
8006     bool isThumb2 = Subtarget->isThumb2();
8007     MachineRegisterInfo &MRI = Fn->getRegInfo();
8008     // In Thumb mode S must not be specified if source register is the SP or
8009     // PC and if destination register is the SP, so restrict register class
8010     unsigned NewRsbDstReg =
8011       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8012
8013     // Transfer the remainder of BB and its successor edges to sinkMBB.
8014     SinkBB->splice(SinkBB->begin(), BB,
8015                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8016     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8017
8018     BB->addSuccessor(RSBBB);
8019     BB->addSuccessor(SinkBB);
8020
8021     // fall through to SinkMBB
8022     RSBBB->addSuccessor(SinkBB);
8023
8024     // insert a cmp at the end of BB
8025     AddDefaultPred(BuildMI(BB, dl,
8026                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8027                    .addReg(ABSSrcReg).addImm(0));
8028
8029     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8030     BuildMI(BB, dl,
8031       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8032       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8033
8034     // insert rsbri in RSBBB
8035     // Note: BCC and rsbri will be converted into predicated rsbmi
8036     // by if-conversion pass
8037     BuildMI(*RSBBB, RSBBB->begin(), dl,
8038       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8039       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8040       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8041
8042     // insert PHI in SinkBB,
8043     // reuse ABSDstReg to not change uses of ABS instruction
8044     BuildMI(*SinkBB, SinkBB->begin(), dl,
8045       TII->get(ARM::PHI), ABSDstReg)
8046       .addReg(NewRsbDstReg).addMBB(RSBBB)
8047       .addReg(ABSSrcReg).addMBB(BB);
8048
8049     // remove ABS instruction
8050     MI->eraseFromParent();
8051
8052     // return last added BB
8053     return SinkBB;
8054   }
8055   case ARM::COPY_STRUCT_BYVAL_I32:
8056     ++NumLoopByVals;
8057     return EmitStructByval(MI, BB);
8058   case ARM::WIN__CHKSTK:
8059     return EmitLowered__chkstk(MI, BB);
8060   case ARM::WIN__DBZCHK:
8061     return EmitLowered__dbzchk(MI, BB);
8062   }
8063 }
8064
8065 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8066 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8067 /// instead of as a custom inserter because we need the use list from the SDNode.
8068 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8069                                    MachineInstr *MI, const SDNode *Node) {
8070   bool isThumb1 = Subtarget->isThumb1Only();
8071
8072   DebugLoc DL = MI->getDebugLoc();
8073   MachineFunction *MF = MI->getParent()->getParent();
8074   MachineRegisterInfo &MRI = MF->getRegInfo();
8075   MachineInstrBuilder MIB(*MF, MI);
8076
8077   // If the new dst/src is unused mark it as dead.
8078   if (!Node->hasAnyUseOfValue(0)) {
8079     MI->getOperand(0).setIsDead(true);
8080   }
8081   if (!Node->hasAnyUseOfValue(1)) {
8082     MI->getOperand(1).setIsDead(true);
8083   }
8084
8085   // The MEMCPY both defines and kills the scratch registers.
8086   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8087     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8088                                                          : &ARM::GPRRegClass);
8089     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8090   }
8091 }
8092
8093 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8094                                                       SDNode *Node) const {
8095   if (MI->getOpcode() == ARM::MEMCPY) {
8096     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8097     return;
8098   }
8099
8100   const MCInstrDesc *MCID = &MI->getDesc();
8101   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8102   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8103   // operand is still set to noreg. If needed, set the optional operand's
8104   // register to CPSR, and remove the redundant implicit def.
8105   //
8106   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8107
8108   // Rename pseudo opcodes.
8109   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8110   if (NewOpc) {
8111     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8112     MCID = &TII->get(NewOpc);
8113
8114     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8115            "converted opcode should be the same except for cc_out");
8116
8117     MI->setDesc(*MCID);
8118
8119     // Add the optional cc_out operand
8120     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8121   }
8122   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8123
8124   // Any ARM instruction that sets the 's' bit should specify an optional
8125   // "cc_out" operand in the last operand position.
8126   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8127     assert(!NewOpc && "Optional cc_out operand required");
8128     return;
8129   }
8130   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8131   // since we already have an optional CPSR def.
8132   bool definesCPSR = false;
8133   bool deadCPSR = false;
8134   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8135        i != e; ++i) {
8136     const MachineOperand &MO = MI->getOperand(i);
8137     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8138       definesCPSR = true;
8139       if (MO.isDead())
8140         deadCPSR = true;
8141       MI->RemoveOperand(i);
8142       break;
8143     }
8144   }
8145   if (!definesCPSR) {
8146     assert(!NewOpc && "Optional cc_out operand required");
8147     return;
8148   }
8149   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8150   if (deadCPSR) {
8151     assert(!MI->getOperand(ccOutIdx).getReg() &&
8152            "expect uninitialized optional cc_out operand");
8153     return;
8154   }
8155
8156   // If this instruction was defined with an optional CPSR def and its dag node
8157   // had a live implicit CPSR def, then activate the optional CPSR def.
8158   MachineOperand &MO = MI->getOperand(ccOutIdx);
8159   MO.setReg(ARM::CPSR);
8160   MO.setIsDef(true);
8161 }
8162
8163 //===----------------------------------------------------------------------===//
8164 //                           ARM Optimization Hooks
8165 //===----------------------------------------------------------------------===//
8166
8167 // Helper function that checks if N is a null or all ones constant.
8168 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8169   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8170   if (!C)
8171     return false;
8172   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8173 }
8174
8175 // Return true if N is conditionally 0 or all ones.
8176 // Detects these expressions where cc is an i1 value:
8177 //
8178 //   (select cc 0, y)   [AllOnes=0]
8179 //   (select cc y, 0)   [AllOnes=0]
8180 //   (zext cc)          [AllOnes=0]
8181 //   (sext cc)          [AllOnes=0/1]
8182 //   (select cc -1, y)  [AllOnes=1]
8183 //   (select cc y, -1)  [AllOnes=1]
8184 //
8185 // Invert is set when N is the null/all ones constant when CC is false.
8186 // OtherOp is set to the alternative value of N.
8187 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8188                                        SDValue &CC, bool &Invert,
8189                                        SDValue &OtherOp,
8190                                        SelectionDAG &DAG) {
8191   switch (N->getOpcode()) {
8192   default: return false;
8193   case ISD::SELECT: {
8194     CC = N->getOperand(0);
8195     SDValue N1 = N->getOperand(1);
8196     SDValue N2 = N->getOperand(2);
8197     if (isZeroOrAllOnes(N1, AllOnes)) {
8198       Invert = false;
8199       OtherOp = N2;
8200       return true;
8201     }
8202     if (isZeroOrAllOnes(N2, AllOnes)) {
8203       Invert = true;
8204       OtherOp = N1;
8205       return true;
8206     }
8207     return false;
8208   }
8209   case ISD::ZERO_EXTEND:
8210     // (zext cc) can never be the all ones value.
8211     if (AllOnes)
8212       return false;
8213     // Fall through.
8214   case ISD::SIGN_EXTEND: {
8215     SDLoc dl(N);
8216     EVT VT = N->getValueType(0);
8217     CC = N->getOperand(0);
8218     if (CC.getValueType() != MVT::i1)
8219       return false;
8220     Invert = !AllOnes;
8221     if (AllOnes)
8222       // When looking for an AllOnes constant, N is an sext, and the 'other'
8223       // value is 0.
8224       OtherOp = DAG.getConstant(0, dl, VT);
8225     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8226       // When looking for a 0 constant, N can be zext or sext.
8227       OtherOp = DAG.getConstant(1, dl, VT);
8228     else
8229       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8230                                 VT);
8231     return true;
8232   }
8233   }
8234 }
8235
8236 // Combine a constant select operand into its use:
8237 //
8238 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8239 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8240 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8241 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8242 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8243 //
8244 // The transform is rejected if the select doesn't have a constant operand that
8245 // is null, or all ones when AllOnes is set.
8246 //
8247 // Also recognize sext/zext from i1:
8248 //
8249 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8250 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8251 //
8252 // These transformations eventually create predicated instructions.
8253 //
8254 // @param N       The node to transform.
8255 // @param Slct    The N operand that is a select.
8256 // @param OtherOp The other N operand (x above).
8257 // @param DCI     Context.
8258 // @param AllOnes Require the select constant to be all ones instead of null.
8259 // @returns The new node, or SDValue() on failure.
8260 static
8261 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8262                             TargetLowering::DAGCombinerInfo &DCI,
8263                             bool AllOnes = false) {
8264   SelectionDAG &DAG = DCI.DAG;
8265   EVT VT = N->getValueType(0);
8266   SDValue NonConstantVal;
8267   SDValue CCOp;
8268   bool SwapSelectOps;
8269   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8270                                   NonConstantVal, DAG))
8271     return SDValue();
8272
8273   // Slct is now know to be the desired identity constant when CC is true.
8274   SDValue TrueVal = OtherOp;
8275   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8276                                  OtherOp, NonConstantVal);
8277   // Unless SwapSelectOps says CC should be false.
8278   if (SwapSelectOps)
8279     std::swap(TrueVal, FalseVal);
8280
8281   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8282                      CCOp, TrueVal, FalseVal);
8283 }
8284
8285 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8286 static
8287 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8288                                        TargetLowering::DAGCombinerInfo &DCI) {
8289   SDValue N0 = N->getOperand(0);
8290   SDValue N1 = N->getOperand(1);
8291   if (N0.getNode()->hasOneUse()) {
8292     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8293     if (Result.getNode())
8294       return Result;
8295   }
8296   if (N1.getNode()->hasOneUse()) {
8297     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8298     if (Result.getNode())
8299       return Result;
8300   }
8301   return SDValue();
8302 }
8303
8304 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8305 // (only after legalization).
8306 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8307                                  TargetLowering::DAGCombinerInfo &DCI,
8308                                  const ARMSubtarget *Subtarget) {
8309
8310   // Only perform optimization if after legalize, and if NEON is available. We
8311   // also expected both operands to be BUILD_VECTORs.
8312   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8313       || N0.getOpcode() != ISD::BUILD_VECTOR
8314       || N1.getOpcode() != ISD::BUILD_VECTOR)
8315     return SDValue();
8316
8317   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8318   EVT VT = N->getValueType(0);
8319   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8320     return SDValue();
8321
8322   // Check that the vector operands are of the right form.
8323   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8324   // operands, where N is the size of the formed vector.
8325   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8326   // index such that we have a pair wise add pattern.
8327
8328   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8329   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8330     return SDValue();
8331   SDValue Vec = N0->getOperand(0)->getOperand(0);
8332   SDNode *V = Vec.getNode();
8333   unsigned nextIndex = 0;
8334
8335   // For each operands to the ADD which are BUILD_VECTORs,
8336   // check to see if each of their operands are an EXTRACT_VECTOR with
8337   // the same vector and appropriate index.
8338   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8339     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8340         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8341
8342       SDValue ExtVec0 = N0->getOperand(i);
8343       SDValue ExtVec1 = N1->getOperand(i);
8344
8345       // First operand is the vector, verify its the same.
8346       if (V != ExtVec0->getOperand(0).getNode() ||
8347           V != ExtVec1->getOperand(0).getNode())
8348         return SDValue();
8349
8350       // Second is the constant, verify its correct.
8351       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8352       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8353
8354       // For the constant, we want to see all the even or all the odd.
8355       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8356           || C1->getZExtValue() != nextIndex+1)
8357         return SDValue();
8358
8359       // Increment index.
8360       nextIndex+=2;
8361     } else
8362       return SDValue();
8363   }
8364
8365   // Create VPADDL node.
8366   SelectionDAG &DAG = DCI.DAG;
8367   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8368
8369   SDLoc dl(N);
8370
8371   // Build operand list.
8372   SmallVector<SDValue, 8> Ops;
8373   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8374                                 TLI.getPointerTy(DAG.getDataLayout())));
8375
8376   // Input is the vector.
8377   Ops.push_back(Vec);
8378
8379   // Get widened type and narrowed type.
8380   MVT widenType;
8381   unsigned numElem = VT.getVectorNumElements();
8382   
8383   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8384   switch (inputLaneType.getSimpleVT().SimpleTy) {
8385     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8386     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8387     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8388     default:
8389       llvm_unreachable("Invalid vector element type for padd optimization.");
8390   }
8391
8392   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8393   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8394   return DAG.getNode(ExtOp, dl, VT, tmp);
8395 }
8396
8397 static SDValue findMUL_LOHI(SDValue V) {
8398   if (V->getOpcode() == ISD::UMUL_LOHI ||
8399       V->getOpcode() == ISD::SMUL_LOHI)
8400     return V;
8401   return SDValue();
8402 }
8403
8404 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8405                                      TargetLowering::DAGCombinerInfo &DCI,
8406                                      const ARMSubtarget *Subtarget) {
8407
8408   if (Subtarget->isThumb1Only()) return SDValue();
8409
8410   // Only perform the checks after legalize when the pattern is available.
8411   if (DCI.isBeforeLegalize()) return SDValue();
8412
8413   // Look for multiply add opportunities.
8414   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8415   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8416   // a glue link from the first add to the second add.
8417   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8418   // a S/UMLAL instruction.
8419   //                  UMUL_LOHI
8420   //                 / :lo    \ :hi
8421   //                /          \          [no multiline comment]
8422   //    loAdd ->  ADDE         |
8423   //                 \ :glue  /
8424   //                  \      /
8425   //                    ADDC   <- hiAdd
8426   //
8427   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8428   SDValue AddcOp0 = AddcNode->getOperand(0);
8429   SDValue AddcOp1 = AddcNode->getOperand(1);
8430
8431   // Check if the two operands are from the same mul_lohi node.
8432   if (AddcOp0.getNode() == AddcOp1.getNode())
8433     return SDValue();
8434
8435   assert(AddcNode->getNumValues() == 2 &&
8436          AddcNode->getValueType(0) == MVT::i32 &&
8437          "Expect ADDC with two result values. First: i32");
8438
8439   // Check that we have a glued ADDC node.
8440   if (AddcNode->getValueType(1) != MVT::Glue)
8441     return SDValue();
8442
8443   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8444   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8445       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8446       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8447       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8448     return SDValue();
8449
8450   // Look for the glued ADDE.
8451   SDNode* AddeNode = AddcNode->getGluedUser();
8452   if (!AddeNode)
8453     return SDValue();
8454
8455   // Make sure it is really an ADDE.
8456   if (AddeNode->getOpcode() != ISD::ADDE)
8457     return SDValue();
8458
8459   assert(AddeNode->getNumOperands() == 3 &&
8460          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8461          "ADDE node has the wrong inputs");
8462
8463   // Check for the triangle shape.
8464   SDValue AddeOp0 = AddeNode->getOperand(0);
8465   SDValue AddeOp1 = AddeNode->getOperand(1);
8466
8467   // Make sure that the ADDE operands are not coming from the same node.
8468   if (AddeOp0.getNode() == AddeOp1.getNode())
8469     return SDValue();
8470
8471   // Find the MUL_LOHI node walking up ADDE's operands.
8472   bool IsLeftOperandMUL = false;
8473   SDValue MULOp = findMUL_LOHI(AddeOp0);
8474   if (MULOp == SDValue())
8475    MULOp = findMUL_LOHI(AddeOp1);
8476   else
8477     IsLeftOperandMUL = true;
8478   if (MULOp == SDValue())
8479     return SDValue();
8480
8481   // Figure out the right opcode.
8482   unsigned Opc = MULOp->getOpcode();
8483   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8484
8485   // Figure out the high and low input values to the MLAL node.
8486   SDValue* HiAdd = nullptr;
8487   SDValue* LoMul = nullptr;
8488   SDValue* LowAdd = nullptr;
8489
8490   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8491   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8492     return SDValue();
8493
8494   if (IsLeftOperandMUL)
8495     HiAdd = &AddeOp1;
8496   else
8497     HiAdd = &AddeOp0;
8498
8499
8500   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8501   // whose low result is fed to the ADDC we are checking.
8502
8503   if (AddcOp0 == MULOp.getValue(0)) {
8504     LoMul = &AddcOp0;
8505     LowAdd = &AddcOp1;
8506   }
8507   if (AddcOp1 == MULOp.getValue(0)) {
8508     LoMul = &AddcOp1;
8509     LowAdd = &AddcOp0;
8510   }
8511
8512   if (!LoMul)
8513     return SDValue();
8514
8515   // Create the merged node.
8516   SelectionDAG &DAG = DCI.DAG;
8517
8518   // Build operand list.
8519   SmallVector<SDValue, 8> Ops;
8520   Ops.push_back(LoMul->getOperand(0));
8521   Ops.push_back(LoMul->getOperand(1));
8522   Ops.push_back(*LowAdd);
8523   Ops.push_back(*HiAdd);
8524
8525   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8526                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8527
8528   // Replace the ADDs' nodes uses by the MLA node's values.
8529   SDValue HiMLALResult(MLALNode.getNode(), 1);
8530   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8531
8532   SDValue LoMLALResult(MLALNode.getNode(), 0);
8533   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8534
8535   // Return original node to notify the driver to stop replacing.
8536   SDValue resNode(AddcNode, 0);
8537   return resNode;
8538 }
8539
8540 /// PerformADDCCombine - Target-specific dag combine transform from
8541 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8542 static SDValue PerformADDCCombine(SDNode *N,
8543                                  TargetLowering::DAGCombinerInfo &DCI,
8544                                  const ARMSubtarget *Subtarget) {
8545
8546   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8547
8548 }
8549
8550 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8551 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8552 /// called with the default operands, and if that fails, with commuted
8553 /// operands.
8554 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8555                                           TargetLowering::DAGCombinerInfo &DCI,
8556                                           const ARMSubtarget *Subtarget){
8557
8558   // Attempt to create vpaddl for this add.
8559   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8560   if (Result.getNode())
8561     return Result;
8562
8563   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8564   if (N0.getNode()->hasOneUse()) {
8565     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8566     if (Result.getNode()) return Result;
8567   }
8568   return SDValue();
8569 }
8570
8571 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8572 ///
8573 static SDValue PerformADDCombine(SDNode *N,
8574                                  TargetLowering::DAGCombinerInfo &DCI,
8575                                  const ARMSubtarget *Subtarget) {
8576   SDValue N0 = N->getOperand(0);
8577   SDValue N1 = N->getOperand(1);
8578
8579   // First try with the default operand order.
8580   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8581   if (Result.getNode())
8582     return Result;
8583
8584   // If that didn't work, try again with the operands commuted.
8585   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8586 }
8587
8588 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8589 ///
8590 static SDValue PerformSUBCombine(SDNode *N,
8591                                  TargetLowering::DAGCombinerInfo &DCI) {
8592   SDValue N0 = N->getOperand(0);
8593   SDValue N1 = N->getOperand(1);
8594
8595   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8596   if (N1.getNode()->hasOneUse()) {
8597     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8598     if (Result.getNode()) return Result;
8599   }
8600
8601   return SDValue();
8602 }
8603
8604 /// PerformVMULCombine
8605 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8606 /// special multiplier accumulator forwarding.
8607 ///   vmul d3, d0, d2
8608 ///   vmla d3, d1, d2
8609 /// is faster than
8610 ///   vadd d3, d0, d1
8611 ///   vmul d3, d3, d2
8612 //  However, for (A + B) * (A + B),
8613 //    vadd d2, d0, d1
8614 //    vmul d3, d0, d2
8615 //    vmla d3, d1, d2
8616 //  is slower than
8617 //    vadd d2, d0, d1
8618 //    vmul d3, d2, d2
8619 static SDValue PerformVMULCombine(SDNode *N,
8620                                   TargetLowering::DAGCombinerInfo &DCI,
8621                                   const ARMSubtarget *Subtarget) {
8622   if (!Subtarget->hasVMLxForwarding())
8623     return SDValue();
8624
8625   SelectionDAG &DAG = DCI.DAG;
8626   SDValue N0 = N->getOperand(0);
8627   SDValue N1 = N->getOperand(1);
8628   unsigned Opcode = N0.getOpcode();
8629   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8630       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8631     Opcode = N1.getOpcode();
8632     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8633         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8634       return SDValue();
8635     std::swap(N0, N1);
8636   }
8637
8638   if (N0 == N1)
8639     return SDValue();
8640
8641   EVT VT = N->getValueType(0);
8642   SDLoc DL(N);
8643   SDValue N00 = N0->getOperand(0);
8644   SDValue N01 = N0->getOperand(1);
8645   return DAG.getNode(Opcode, DL, VT,
8646                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8647                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8648 }
8649
8650 static SDValue PerformMULCombine(SDNode *N,
8651                                  TargetLowering::DAGCombinerInfo &DCI,
8652                                  const ARMSubtarget *Subtarget) {
8653   SelectionDAG &DAG = DCI.DAG;
8654
8655   if (Subtarget->isThumb1Only())
8656     return SDValue();
8657
8658   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8659     return SDValue();
8660
8661   EVT VT = N->getValueType(0);
8662   if (VT.is64BitVector() || VT.is128BitVector())
8663     return PerformVMULCombine(N, DCI, Subtarget);
8664   if (VT != MVT::i32)
8665     return SDValue();
8666
8667   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8668   if (!C)
8669     return SDValue();
8670
8671   int64_t MulAmt = C->getSExtValue();
8672   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8673
8674   ShiftAmt = ShiftAmt & (32 - 1);
8675   SDValue V = N->getOperand(0);
8676   SDLoc DL(N);
8677
8678   SDValue Res;
8679   MulAmt >>= ShiftAmt;
8680
8681   if (MulAmt >= 0) {
8682     if (isPowerOf2_32(MulAmt - 1)) {
8683       // (mul x, 2^N + 1) => (add (shl x, N), x)
8684       Res = DAG.getNode(ISD::ADD, DL, VT,
8685                         V,
8686                         DAG.getNode(ISD::SHL, DL, VT,
8687                                     V,
8688                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8689                                                     MVT::i32)));
8690     } else if (isPowerOf2_32(MulAmt + 1)) {
8691       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8692       Res = DAG.getNode(ISD::SUB, DL, VT,
8693                         DAG.getNode(ISD::SHL, DL, VT,
8694                                     V,
8695                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8696                                                     MVT::i32)),
8697                         V);
8698     } else
8699       return SDValue();
8700   } else {
8701     uint64_t MulAmtAbs = -MulAmt;
8702     if (isPowerOf2_32(MulAmtAbs + 1)) {
8703       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8704       Res = DAG.getNode(ISD::SUB, DL, VT,
8705                         V,
8706                         DAG.getNode(ISD::SHL, DL, VT,
8707                                     V,
8708                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8709                                                     MVT::i32)));
8710     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8711       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8712       Res = DAG.getNode(ISD::ADD, DL, VT,
8713                         V,
8714                         DAG.getNode(ISD::SHL, DL, VT,
8715                                     V,
8716                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8717                                                     MVT::i32)));
8718       Res = DAG.getNode(ISD::SUB, DL, VT,
8719                         DAG.getConstant(0, DL, MVT::i32), Res);
8720
8721     } else
8722       return SDValue();
8723   }
8724
8725   if (ShiftAmt != 0)
8726     Res = DAG.getNode(ISD::SHL, DL, VT,
8727                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8728
8729   // Do not add new nodes to DAG combiner worklist.
8730   DCI.CombineTo(N, Res, false);
8731   return SDValue();
8732 }
8733
8734 static SDValue PerformANDCombine(SDNode *N,
8735                                  TargetLowering::DAGCombinerInfo &DCI,
8736                                  const ARMSubtarget *Subtarget) {
8737
8738   // Attempt to use immediate-form VBIC
8739   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8740   SDLoc dl(N);
8741   EVT VT = N->getValueType(0);
8742   SelectionDAG &DAG = DCI.DAG;
8743
8744   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8745     return SDValue();
8746
8747   APInt SplatBits, SplatUndef;
8748   unsigned SplatBitSize;
8749   bool HasAnyUndefs;
8750   if (BVN &&
8751       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8752     if (SplatBitSize <= 64) {
8753       EVT VbicVT;
8754       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8755                                       SplatUndef.getZExtValue(), SplatBitSize,
8756                                       DAG, dl, VbicVT, VT.is128BitVector(),
8757                                       OtherModImm);
8758       if (Val.getNode()) {
8759         SDValue Input =
8760           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8761         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8762         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8763       }
8764     }
8765   }
8766
8767   if (!Subtarget->isThumb1Only()) {
8768     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8769     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8770     if (Result.getNode())
8771       return Result;
8772   }
8773
8774   return SDValue();
8775 }
8776
8777 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8778 static SDValue PerformORCombine(SDNode *N,
8779                                 TargetLowering::DAGCombinerInfo &DCI,
8780                                 const ARMSubtarget *Subtarget) {
8781   // Attempt to use immediate-form VORR
8782   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8783   SDLoc dl(N);
8784   EVT VT = N->getValueType(0);
8785   SelectionDAG &DAG = DCI.DAG;
8786
8787   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8788     return SDValue();
8789
8790   APInt SplatBits, SplatUndef;
8791   unsigned SplatBitSize;
8792   bool HasAnyUndefs;
8793   if (BVN && Subtarget->hasNEON() &&
8794       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8795     if (SplatBitSize <= 64) {
8796       EVT VorrVT;
8797       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8798                                       SplatUndef.getZExtValue(), SplatBitSize,
8799                                       DAG, dl, VorrVT, VT.is128BitVector(),
8800                                       OtherModImm);
8801       if (Val.getNode()) {
8802         SDValue Input =
8803           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8804         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8805         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8806       }
8807     }
8808   }
8809
8810   if (!Subtarget->isThumb1Only()) {
8811     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8812     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8813     if (Result.getNode())
8814       return Result;
8815   }
8816
8817   // The code below optimizes (or (and X, Y), Z).
8818   // The AND operand needs to have a single user to make these optimizations
8819   // profitable.
8820   SDValue N0 = N->getOperand(0);
8821   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8822     return SDValue();
8823   SDValue N1 = N->getOperand(1);
8824
8825   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8826   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8827       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8828     APInt SplatUndef;
8829     unsigned SplatBitSize;
8830     bool HasAnyUndefs;
8831
8832     APInt SplatBits0, SplatBits1;
8833     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8834     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8835     // Ensure that the second operand of both ands are constants
8836     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8837                                       HasAnyUndefs) && !HasAnyUndefs) {
8838         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8839                                           HasAnyUndefs) && !HasAnyUndefs) {
8840             // Ensure that the bit width of the constants are the same and that
8841             // the splat arguments are logical inverses as per the pattern we
8842             // are trying to simplify.
8843             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8844                 SplatBits0 == ~SplatBits1) {
8845                 // Canonicalize the vector type to make instruction selection
8846                 // simpler.
8847                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8848                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8849                                              N0->getOperand(1),
8850                                              N0->getOperand(0),
8851                                              N1->getOperand(0));
8852                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8853             }
8854         }
8855     }
8856   }
8857
8858   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8859   // reasonable.
8860
8861   // BFI is only available on V6T2+
8862   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8863     return SDValue();
8864
8865   SDLoc DL(N);
8866   // 1) or (and A, mask), val => ARMbfi A, val, mask
8867   //      iff (val & mask) == val
8868   //
8869   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8870   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8871   //          && mask == ~mask2
8872   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8873   //          && ~mask == mask2
8874   //  (i.e., copy a bitfield value into another bitfield of the same width)
8875
8876   if (VT != MVT::i32)
8877     return SDValue();
8878
8879   SDValue N00 = N0.getOperand(0);
8880
8881   // The value and the mask need to be constants so we can verify this is
8882   // actually a bitfield set. If the mask is 0xffff, we can do better
8883   // via a movt instruction, so don't use BFI in that case.
8884   SDValue MaskOp = N0.getOperand(1);
8885   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8886   if (!MaskC)
8887     return SDValue();
8888   unsigned Mask = MaskC->getZExtValue();
8889   if (Mask == 0xffff)
8890     return SDValue();
8891   SDValue Res;
8892   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8893   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8894   if (N1C) {
8895     unsigned Val = N1C->getZExtValue();
8896     if ((Val & ~Mask) != Val)
8897       return SDValue();
8898
8899     if (ARM::isBitFieldInvertedMask(Mask)) {
8900       Val >>= countTrailingZeros(~Mask);
8901
8902       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8903                         DAG.getConstant(Val, DL, MVT::i32),
8904                         DAG.getConstant(Mask, DL, MVT::i32));
8905
8906       // Do not add new nodes to DAG combiner worklist.
8907       DCI.CombineTo(N, Res, false);
8908       return SDValue();
8909     }
8910   } else if (N1.getOpcode() == ISD::AND) {
8911     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8912     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8913     if (!N11C)
8914       return SDValue();
8915     unsigned Mask2 = N11C->getZExtValue();
8916
8917     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8918     // as is to match.
8919     if (ARM::isBitFieldInvertedMask(Mask) &&
8920         (Mask == ~Mask2)) {
8921       // The pack halfword instruction works better for masks that fit it,
8922       // so use that when it's available.
8923       if (Subtarget->hasT2ExtractPack() &&
8924           (Mask == 0xffff || Mask == 0xffff0000))
8925         return SDValue();
8926       // 2a
8927       unsigned amt = countTrailingZeros(Mask2);
8928       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8929                         DAG.getConstant(amt, DL, MVT::i32));
8930       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8931                         DAG.getConstant(Mask, DL, MVT::i32));
8932       // Do not add new nodes to DAG combiner worklist.
8933       DCI.CombineTo(N, Res, false);
8934       return SDValue();
8935     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8936                (~Mask == Mask2)) {
8937       // The pack halfword instruction works better for masks that fit it,
8938       // so use that when it's available.
8939       if (Subtarget->hasT2ExtractPack() &&
8940           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8941         return SDValue();
8942       // 2b
8943       unsigned lsb = countTrailingZeros(Mask);
8944       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8945                         DAG.getConstant(lsb, DL, MVT::i32));
8946       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8947                         DAG.getConstant(Mask2, DL, MVT::i32));
8948       // Do not add new nodes to DAG combiner worklist.
8949       DCI.CombineTo(N, Res, false);
8950       return SDValue();
8951     }
8952   }
8953
8954   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8955       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8956       ARM::isBitFieldInvertedMask(~Mask)) {
8957     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8958     // where lsb(mask) == #shamt and masked bits of B are known zero.
8959     SDValue ShAmt = N00.getOperand(1);
8960     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8961     unsigned LSB = countTrailingZeros(Mask);
8962     if (ShAmtC != LSB)
8963       return SDValue();
8964
8965     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8966                       DAG.getConstant(~Mask, DL, MVT::i32));
8967
8968     // Do not add new nodes to DAG combiner worklist.
8969     DCI.CombineTo(N, Res, false);
8970   }
8971
8972   return SDValue();
8973 }
8974
8975 static SDValue PerformXORCombine(SDNode *N,
8976                                  TargetLowering::DAGCombinerInfo &DCI,
8977                                  const ARMSubtarget *Subtarget) {
8978   EVT VT = N->getValueType(0);
8979   SelectionDAG &DAG = DCI.DAG;
8980
8981   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8982     return SDValue();
8983
8984   if (!Subtarget->isThumb1Only()) {
8985     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8986     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8987     if (Result.getNode())
8988       return Result;
8989   }
8990
8991   return SDValue();
8992 }
8993
8994 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8995 /// the bits being cleared by the AND are not demanded by the BFI.
8996 static SDValue PerformBFICombine(SDNode *N,
8997                                  TargetLowering::DAGCombinerInfo &DCI) {
8998   SDValue N1 = N->getOperand(1);
8999   if (N1.getOpcode() == ISD::AND) {
9000     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9001     if (!N11C)
9002       return SDValue();
9003     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9004     unsigned LSB = countTrailingZeros(~InvMask);
9005     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9006     assert(Width <
9007                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9008            "undefined behavior");
9009     unsigned Mask = (1u << Width) - 1;
9010     unsigned Mask2 = N11C->getZExtValue();
9011     if ((Mask & (~Mask2)) == 0)
9012       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9013                              N->getOperand(0), N1.getOperand(0),
9014                              N->getOperand(2));
9015   }
9016   return SDValue();
9017 }
9018
9019 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9020 /// ARMISD::VMOVRRD.
9021 static SDValue PerformVMOVRRDCombine(SDNode *N,
9022                                      TargetLowering::DAGCombinerInfo &DCI,
9023                                      const ARMSubtarget *Subtarget) {
9024   // vmovrrd(vmovdrr x, y) -> x,y
9025   SDValue InDouble = N->getOperand(0);
9026   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9027     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9028
9029   // vmovrrd(load f64) -> (load i32), (load i32)
9030   SDNode *InNode = InDouble.getNode();
9031   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9032       InNode->getValueType(0) == MVT::f64 &&
9033       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9034       !cast<LoadSDNode>(InNode)->isVolatile()) {
9035     // TODO: Should this be done for non-FrameIndex operands?
9036     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9037
9038     SelectionDAG &DAG = DCI.DAG;
9039     SDLoc DL(LD);
9040     SDValue BasePtr = LD->getBasePtr();
9041     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9042                                  LD->getPointerInfo(), LD->isVolatile(),
9043                                  LD->isNonTemporal(), LD->isInvariant(),
9044                                  LD->getAlignment());
9045
9046     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9047                                     DAG.getConstant(4, DL, MVT::i32));
9048     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9049                                  LD->getPointerInfo(), LD->isVolatile(),
9050                                  LD->isNonTemporal(), LD->isInvariant(),
9051                                  std::min(4U, LD->getAlignment() / 2));
9052
9053     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9054     if (DCI.DAG.getDataLayout().isBigEndian())
9055       std::swap (NewLD1, NewLD2);
9056     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9057     return Result;
9058   }
9059
9060   return SDValue();
9061 }
9062
9063 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9064 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9065 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9066   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9067   SDValue Op0 = N->getOperand(0);
9068   SDValue Op1 = N->getOperand(1);
9069   if (Op0.getOpcode() == ISD::BITCAST)
9070     Op0 = Op0.getOperand(0);
9071   if (Op1.getOpcode() == ISD::BITCAST)
9072     Op1 = Op1.getOperand(0);
9073   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9074       Op0.getNode() == Op1.getNode() &&
9075       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9076     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9077                        N->getValueType(0), Op0.getOperand(0));
9078   return SDValue();
9079 }
9080
9081 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9082 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9083 /// i64 vector to have f64 elements, since the value can then be loaded
9084 /// directly into a VFP register.
9085 static bool hasNormalLoadOperand(SDNode *N) {
9086   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9087   for (unsigned i = 0; i < NumElts; ++i) {
9088     SDNode *Elt = N->getOperand(i).getNode();
9089     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9090       return true;
9091   }
9092   return false;
9093 }
9094
9095 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9096 /// ISD::BUILD_VECTOR.
9097 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9098                                           TargetLowering::DAGCombinerInfo &DCI,
9099                                           const ARMSubtarget *Subtarget) {
9100   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9101   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9102   // into a pair of GPRs, which is fine when the value is used as a scalar,
9103   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9104   SelectionDAG &DAG = DCI.DAG;
9105   if (N->getNumOperands() == 2) {
9106     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9107     if (RV.getNode())
9108       return RV;
9109   }
9110
9111   // Load i64 elements as f64 values so that type legalization does not split
9112   // them up into i32 values.
9113   EVT VT = N->getValueType(0);
9114   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9115     return SDValue();
9116   SDLoc dl(N);
9117   SmallVector<SDValue, 8> Ops;
9118   unsigned NumElts = VT.getVectorNumElements();
9119   for (unsigned i = 0; i < NumElts; ++i) {
9120     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9121     Ops.push_back(V);
9122     // Make the DAGCombiner fold the bitcast.
9123     DCI.AddToWorklist(V.getNode());
9124   }
9125   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9126   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9127   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9128 }
9129
9130 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9131 static SDValue
9132 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9133   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9134   // At that time, we may have inserted bitcasts from integer to float.
9135   // If these bitcasts have survived DAGCombine, change the lowering of this
9136   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9137   // force to use floating point types.
9138
9139   // Make sure we can change the type of the vector.
9140   // This is possible iff:
9141   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9142   //    1.1. Vector is used only once.
9143   //    1.2. Use is a bit convert to an integer type.
9144   // 2. The size of its operands are 32-bits (64-bits are not legal).
9145   EVT VT = N->getValueType(0);
9146   EVT EltVT = VT.getVectorElementType();
9147
9148   // Check 1.1. and 2.
9149   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9150     return SDValue();
9151
9152   // By construction, the input type must be float.
9153   assert(EltVT == MVT::f32 && "Unexpected type!");
9154
9155   // Check 1.2.
9156   SDNode *Use = *N->use_begin();
9157   if (Use->getOpcode() != ISD::BITCAST ||
9158       Use->getValueType(0).isFloatingPoint())
9159     return SDValue();
9160
9161   // Check profitability.
9162   // Model is, if more than half of the relevant operands are bitcast from
9163   // i32, turn the build_vector into a sequence of insert_vector_elt.
9164   // Relevant operands are everything that is not statically
9165   // (i.e., at compile time) bitcasted.
9166   unsigned NumOfBitCastedElts = 0;
9167   unsigned NumElts = VT.getVectorNumElements();
9168   unsigned NumOfRelevantElts = NumElts;
9169   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9170     SDValue Elt = N->getOperand(Idx);
9171     if (Elt->getOpcode() == ISD::BITCAST) {
9172       // Assume only bit cast to i32 will go away.
9173       if (Elt->getOperand(0).getValueType() == MVT::i32)
9174         ++NumOfBitCastedElts;
9175     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9176       // Constants are statically casted, thus do not count them as
9177       // relevant operands.
9178       --NumOfRelevantElts;
9179   }
9180
9181   // Check if more than half of the elements require a non-free bitcast.
9182   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9183     return SDValue();
9184
9185   SelectionDAG &DAG = DCI.DAG;
9186   // Create the new vector type.
9187   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9188   // Check if the type is legal.
9189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9190   if (!TLI.isTypeLegal(VecVT))
9191     return SDValue();
9192
9193   // Combine:
9194   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9195   // => BITCAST INSERT_VECTOR_ELT
9196   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9197   //                      (BITCAST EN), N.
9198   SDValue Vec = DAG.getUNDEF(VecVT);
9199   SDLoc dl(N);
9200   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9201     SDValue V = N->getOperand(Idx);
9202     if (V.getOpcode() == ISD::UNDEF)
9203       continue;
9204     if (V.getOpcode() == ISD::BITCAST &&
9205         V->getOperand(0).getValueType() == MVT::i32)
9206       // Fold obvious case.
9207       V = V.getOperand(0);
9208     else {
9209       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9210       // Make the DAGCombiner fold the bitcasts.
9211       DCI.AddToWorklist(V.getNode());
9212     }
9213     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9214     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9215   }
9216   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9217   // Make the DAGCombiner fold the bitcasts.
9218   DCI.AddToWorklist(Vec.getNode());
9219   return Vec;
9220 }
9221
9222 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9223 /// ISD::INSERT_VECTOR_ELT.
9224 static SDValue PerformInsertEltCombine(SDNode *N,
9225                                        TargetLowering::DAGCombinerInfo &DCI) {
9226   // Bitcast an i64 load inserted into a vector to f64.
9227   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9228   EVT VT = N->getValueType(0);
9229   SDNode *Elt = N->getOperand(1).getNode();
9230   if (VT.getVectorElementType() != MVT::i64 ||
9231       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9232     return SDValue();
9233
9234   SelectionDAG &DAG = DCI.DAG;
9235   SDLoc dl(N);
9236   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9237                                  VT.getVectorNumElements());
9238   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9239   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9240   // Make the DAGCombiner fold the bitcasts.
9241   DCI.AddToWorklist(Vec.getNode());
9242   DCI.AddToWorklist(V.getNode());
9243   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9244                                Vec, V, N->getOperand(2));
9245   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9246 }
9247
9248 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9249 /// ISD::VECTOR_SHUFFLE.
9250 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9251   // The LLVM shufflevector instruction does not require the shuffle mask
9252   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9253   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9254   // operands do not match the mask length, they are extended by concatenating
9255   // them with undef vectors.  That is probably the right thing for other
9256   // targets, but for NEON it is better to concatenate two double-register
9257   // size vector operands into a single quad-register size vector.  Do that
9258   // transformation here:
9259   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9260   //   shuffle(concat(v1, v2), undef)
9261   SDValue Op0 = N->getOperand(0);
9262   SDValue Op1 = N->getOperand(1);
9263   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9264       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9265       Op0.getNumOperands() != 2 ||
9266       Op1.getNumOperands() != 2)
9267     return SDValue();
9268   SDValue Concat0Op1 = Op0.getOperand(1);
9269   SDValue Concat1Op1 = Op1.getOperand(1);
9270   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9271       Concat1Op1.getOpcode() != ISD::UNDEF)
9272     return SDValue();
9273   // Skip the transformation if any of the types are illegal.
9274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9275   EVT VT = N->getValueType(0);
9276   if (!TLI.isTypeLegal(VT) ||
9277       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9278       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9279     return SDValue();
9280
9281   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9282                                   Op0.getOperand(0), Op1.getOperand(0));
9283   // Translate the shuffle mask.
9284   SmallVector<int, 16> NewMask;
9285   unsigned NumElts = VT.getVectorNumElements();
9286   unsigned HalfElts = NumElts/2;
9287   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9288   for (unsigned n = 0; n < NumElts; ++n) {
9289     int MaskElt = SVN->getMaskElt(n);
9290     int NewElt = -1;
9291     if (MaskElt < (int)HalfElts)
9292       NewElt = MaskElt;
9293     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9294       NewElt = HalfElts + MaskElt - NumElts;
9295     NewMask.push_back(NewElt);
9296   }
9297   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9298                               DAG.getUNDEF(VT), NewMask.data());
9299 }
9300
9301 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9302 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9303 /// base address updates.
9304 /// For generic load/stores, the memory type is assumed to be a vector.
9305 /// The caller is assumed to have checked legality.
9306 static SDValue CombineBaseUpdate(SDNode *N,
9307                                  TargetLowering::DAGCombinerInfo &DCI) {
9308   SelectionDAG &DAG = DCI.DAG;
9309   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9310                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9311   const bool isStore = N->getOpcode() == ISD::STORE;
9312   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9313   SDValue Addr = N->getOperand(AddrOpIdx);
9314   MemSDNode *MemN = cast<MemSDNode>(N);
9315   SDLoc dl(N);
9316
9317   // Search for a use of the address operand that is an increment.
9318   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9319          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9320     SDNode *User = *UI;
9321     if (User->getOpcode() != ISD::ADD ||
9322         UI.getUse().getResNo() != Addr.getResNo())
9323       continue;
9324
9325     // Check that the add is independent of the load/store.  Otherwise, folding
9326     // it would create a cycle.
9327     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9328       continue;
9329
9330     // Find the new opcode for the updating load/store.
9331     bool isLoadOp = true;
9332     bool isLaneOp = false;
9333     unsigned NewOpc = 0;
9334     unsigned NumVecs = 0;
9335     if (isIntrinsic) {
9336       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9337       switch (IntNo) {
9338       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9339       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9340         NumVecs = 1; break;
9341       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9342         NumVecs = 2; break;
9343       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9344         NumVecs = 3; break;
9345       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9346         NumVecs = 4; break;
9347       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9348         NumVecs = 2; isLaneOp = true; break;
9349       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9350         NumVecs = 3; isLaneOp = true; break;
9351       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9352         NumVecs = 4; isLaneOp = true; break;
9353       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9354         NumVecs = 1; isLoadOp = false; break;
9355       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9356         NumVecs = 2; isLoadOp = false; break;
9357       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9358         NumVecs = 3; isLoadOp = false; break;
9359       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9360         NumVecs = 4; isLoadOp = false; break;
9361       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9362         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9363       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9364         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9365       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9366         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9367       }
9368     } else {
9369       isLaneOp = true;
9370       switch (N->getOpcode()) {
9371       default: llvm_unreachable("unexpected opcode for Neon base update");
9372       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9373       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9374       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9375       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9376         NumVecs = 1; isLaneOp = false; break;
9377       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9378         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9379       }
9380     }
9381
9382     // Find the size of memory referenced by the load/store.
9383     EVT VecTy;
9384     if (isLoadOp) {
9385       VecTy = N->getValueType(0);
9386     } else if (isIntrinsic) {
9387       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9388     } else {
9389       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9390       VecTy = N->getOperand(1).getValueType();
9391     }
9392
9393     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9394     if (isLaneOp)
9395       NumBytes /= VecTy.getVectorNumElements();
9396
9397     // If the increment is a constant, it must match the memory ref size.
9398     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9399     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9400       uint64_t IncVal = CInc->getZExtValue();
9401       if (IncVal != NumBytes)
9402         continue;
9403     } else if (NumBytes >= 3 * 16) {
9404       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9405       // separate instructions that make it harder to use a non-constant update.
9406       continue;
9407     }
9408
9409     // OK, we found an ADD we can fold into the base update.
9410     // Now, create a _UPD node, taking care of not breaking alignment.
9411
9412     EVT AlignedVecTy = VecTy;
9413     unsigned Alignment = MemN->getAlignment();
9414
9415     // If this is a less-than-standard-aligned load/store, change the type to
9416     // match the standard alignment.
9417     // The alignment is overlooked when selecting _UPD variants; and it's
9418     // easier to introduce bitcasts here than fix that.
9419     // There are 3 ways to get to this base-update combine:
9420     // - intrinsics: they are assumed to be properly aligned (to the standard
9421     //   alignment of the memory type), so we don't need to do anything.
9422     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9423     //   intrinsics, so, likewise, there's nothing to do.
9424     // - generic load/store instructions: the alignment is specified as an
9425     //   explicit operand, rather than implicitly as the standard alignment
9426     //   of the memory type (like the intrisics).  We need to change the
9427     //   memory type to match the explicit alignment.  That way, we don't
9428     //   generate non-standard-aligned ARMISD::VLDx nodes.
9429     if (isa<LSBaseSDNode>(N)) {
9430       if (Alignment == 0)
9431         Alignment = 1;
9432       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9433         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9434         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9435         assert(!isLaneOp && "Unexpected generic load/store lane.");
9436         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9437         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9438       }
9439       // Don't set an explicit alignment on regular load/stores that we want
9440       // to transform to VLD/VST 1_UPD nodes.
9441       // This matches the behavior of regular load/stores, which only get an
9442       // explicit alignment if the MMO alignment is larger than the standard
9443       // alignment of the memory type.
9444       // Intrinsics, however, always get an explicit alignment, set to the
9445       // alignment of the MMO.
9446       Alignment = 1;
9447     }
9448
9449     // Create the new updating load/store node.
9450     // First, create an SDVTList for the new updating node's results.
9451     EVT Tys[6];
9452     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9453     unsigned n;
9454     for (n = 0; n < NumResultVecs; ++n)
9455       Tys[n] = AlignedVecTy;
9456     Tys[n++] = MVT::i32;
9457     Tys[n] = MVT::Other;
9458     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9459
9460     // Then, gather the new node's operands.
9461     SmallVector<SDValue, 8> Ops;
9462     Ops.push_back(N->getOperand(0)); // incoming chain
9463     Ops.push_back(N->getOperand(AddrOpIdx));
9464     Ops.push_back(Inc);
9465
9466     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9467       // Try to match the intrinsic's signature
9468       Ops.push_back(StN->getValue());
9469     } else {
9470       // Loads (and of course intrinsics) match the intrinsics' signature,
9471       // so just add all but the alignment operand.
9472       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9473         Ops.push_back(N->getOperand(i));
9474     }
9475
9476     // For all node types, the alignment operand is always the last one.
9477     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9478
9479     // If this is a non-standard-aligned STORE, the penultimate operand is the
9480     // stored value.  Bitcast it to the aligned type.
9481     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9482       SDValue &StVal = Ops[Ops.size()-2];
9483       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9484     }
9485
9486     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9487                                            Ops, AlignedVecTy,
9488                                            MemN->getMemOperand());
9489
9490     // Update the uses.
9491     SmallVector<SDValue, 5> NewResults;
9492     for (unsigned i = 0; i < NumResultVecs; ++i)
9493       NewResults.push_back(SDValue(UpdN.getNode(), i));
9494
9495     // If this is an non-standard-aligned LOAD, the first result is the loaded
9496     // value.  Bitcast it to the expected result type.
9497     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9498       SDValue &LdVal = NewResults[0];
9499       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9500     }
9501
9502     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9503     DCI.CombineTo(N, NewResults);
9504     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9505
9506     break;
9507   }
9508   return SDValue();
9509 }
9510
9511 static SDValue PerformVLDCombine(SDNode *N,
9512                                  TargetLowering::DAGCombinerInfo &DCI) {
9513   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9514     return SDValue();
9515
9516   return CombineBaseUpdate(N, DCI);
9517 }
9518
9519 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9520 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9521 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9522 /// return true.
9523 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9524   SelectionDAG &DAG = DCI.DAG;
9525   EVT VT = N->getValueType(0);
9526   // vldN-dup instructions only support 64-bit vectors for N > 1.
9527   if (!VT.is64BitVector())
9528     return false;
9529
9530   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9531   SDNode *VLD = N->getOperand(0).getNode();
9532   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9533     return false;
9534   unsigned NumVecs = 0;
9535   unsigned NewOpc = 0;
9536   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9537   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9538     NumVecs = 2;
9539     NewOpc = ARMISD::VLD2DUP;
9540   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9541     NumVecs = 3;
9542     NewOpc = ARMISD::VLD3DUP;
9543   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9544     NumVecs = 4;
9545     NewOpc = ARMISD::VLD4DUP;
9546   } else {
9547     return false;
9548   }
9549
9550   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9551   // numbers match the load.
9552   unsigned VLDLaneNo =
9553     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9554   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9555        UI != UE; ++UI) {
9556     // Ignore uses of the chain result.
9557     if (UI.getUse().getResNo() == NumVecs)
9558       continue;
9559     SDNode *User = *UI;
9560     if (User->getOpcode() != ARMISD::VDUPLANE ||
9561         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9562       return false;
9563   }
9564
9565   // Create the vldN-dup node.
9566   EVT Tys[5];
9567   unsigned n;
9568   for (n = 0; n < NumVecs; ++n)
9569     Tys[n] = VT;
9570   Tys[n] = MVT::Other;
9571   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9572   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9573   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9574   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9575                                            Ops, VLDMemInt->getMemoryVT(),
9576                                            VLDMemInt->getMemOperand());
9577
9578   // Update the uses.
9579   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9580        UI != UE; ++UI) {
9581     unsigned ResNo = UI.getUse().getResNo();
9582     // Ignore uses of the chain result.
9583     if (ResNo == NumVecs)
9584       continue;
9585     SDNode *User = *UI;
9586     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9587   }
9588
9589   // Now the vldN-lane intrinsic is dead except for its chain result.
9590   // Update uses of the chain.
9591   std::vector<SDValue> VLDDupResults;
9592   for (unsigned n = 0; n < NumVecs; ++n)
9593     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9594   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9595   DCI.CombineTo(VLD, VLDDupResults);
9596
9597   return true;
9598 }
9599
9600 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9601 /// ARMISD::VDUPLANE.
9602 static SDValue PerformVDUPLANECombine(SDNode *N,
9603                                       TargetLowering::DAGCombinerInfo &DCI) {
9604   SDValue Op = N->getOperand(0);
9605
9606   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9607   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9608   if (CombineVLDDUP(N, DCI))
9609     return SDValue(N, 0);
9610
9611   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9612   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9613   while (Op.getOpcode() == ISD::BITCAST)
9614     Op = Op.getOperand(0);
9615   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9616     return SDValue();
9617
9618   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9619   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9620   // The canonical VMOV for a zero vector uses a 32-bit element size.
9621   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9622   unsigned EltBits;
9623   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9624     EltSize = 8;
9625   EVT VT = N->getValueType(0);
9626   if (EltSize > VT.getVectorElementType().getSizeInBits())
9627     return SDValue();
9628
9629   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9630 }
9631
9632 static SDValue PerformLOADCombine(SDNode *N,
9633                                   TargetLowering::DAGCombinerInfo &DCI) {
9634   EVT VT = N->getValueType(0);
9635
9636   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9637   if (ISD::isNormalLoad(N) && VT.isVector() &&
9638       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9639     return CombineBaseUpdate(N, DCI);
9640
9641   return SDValue();
9642 }
9643
9644 /// PerformSTORECombine - Target-specific dag combine xforms for
9645 /// ISD::STORE.
9646 static SDValue PerformSTORECombine(SDNode *N,
9647                                    TargetLowering::DAGCombinerInfo &DCI) {
9648   StoreSDNode *St = cast<StoreSDNode>(N);
9649   if (St->isVolatile())
9650     return SDValue();
9651
9652   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9653   // pack all of the elements in one place.  Next, store to memory in fewer
9654   // chunks.
9655   SDValue StVal = St->getValue();
9656   EVT VT = StVal.getValueType();
9657   if (St->isTruncatingStore() && VT.isVector()) {
9658     SelectionDAG &DAG = DCI.DAG;
9659     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9660     EVT StVT = St->getMemoryVT();
9661     unsigned NumElems = VT.getVectorNumElements();
9662     assert(StVT != VT && "Cannot truncate to the same type");
9663     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9664     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9665
9666     // From, To sizes and ElemCount must be pow of two
9667     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9668
9669     // We are going to use the original vector elt for storing.
9670     // Accumulated smaller vector elements must be a multiple of the store size.
9671     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9672
9673     unsigned SizeRatio  = FromEltSz / ToEltSz;
9674     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9675
9676     // Create a type on which we perform the shuffle.
9677     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9678                                      NumElems*SizeRatio);
9679     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9680
9681     SDLoc DL(St);
9682     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9683     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9684     for (unsigned i = 0; i < NumElems; ++i)
9685       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9686                           ? (i + 1) * SizeRatio - 1
9687                           : i * SizeRatio;
9688
9689     // Can't shuffle using an illegal type.
9690     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9691
9692     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9693                                 DAG.getUNDEF(WideVec.getValueType()),
9694                                 ShuffleVec.data());
9695     // At this point all of the data is stored at the bottom of the
9696     // register. We now need to save it to mem.
9697
9698     // Find the largest store unit
9699     MVT StoreType = MVT::i8;
9700     for (MVT Tp : MVT::integer_valuetypes()) {
9701       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9702         StoreType = Tp;
9703     }
9704     // Didn't find a legal store type.
9705     if (!TLI.isTypeLegal(StoreType))
9706       return SDValue();
9707
9708     // Bitcast the original vector into a vector of store-size units
9709     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9710             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9711     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9712     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9713     SmallVector<SDValue, 8> Chains;
9714     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9715                                         TLI.getPointerTy(DAG.getDataLayout()));
9716     SDValue BasePtr = St->getBasePtr();
9717
9718     // Perform one or more big stores into memory.
9719     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9720     for (unsigned I = 0; I < E; I++) {
9721       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9722                                    StoreType, ShuffWide,
9723                                    DAG.getIntPtrConstant(I, DL));
9724       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9725                                 St->getPointerInfo(), St->isVolatile(),
9726                                 St->isNonTemporal(), St->getAlignment());
9727       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9728                             Increment);
9729       Chains.push_back(Ch);
9730     }
9731     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9732   }
9733
9734   if (!ISD::isNormalStore(St))
9735     return SDValue();
9736
9737   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9738   // ARM stores of arguments in the same cache line.
9739   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9740       StVal.getNode()->hasOneUse()) {
9741     SelectionDAG  &DAG = DCI.DAG;
9742     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9743     SDLoc DL(St);
9744     SDValue BasePtr = St->getBasePtr();
9745     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9746                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9747                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9748                                   St->isNonTemporal(), St->getAlignment());
9749
9750     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9751                                     DAG.getConstant(4, DL, MVT::i32));
9752     return DAG.getStore(NewST1.getValue(0), DL,
9753                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9754                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9755                         St->isNonTemporal(),
9756                         std::min(4U, St->getAlignment() / 2));
9757   }
9758
9759   if (StVal.getValueType() == MVT::i64 &&
9760       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9761
9762     // Bitcast an i64 store extracted from a vector to f64.
9763     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9764     SelectionDAG &DAG = DCI.DAG;
9765     SDLoc dl(StVal);
9766     SDValue IntVec = StVal.getOperand(0);
9767     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9768                                    IntVec.getValueType().getVectorNumElements());
9769     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9770     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9771                                  Vec, StVal.getOperand(1));
9772     dl = SDLoc(N);
9773     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9774     // Make the DAGCombiner fold the bitcasts.
9775     DCI.AddToWorklist(Vec.getNode());
9776     DCI.AddToWorklist(ExtElt.getNode());
9777     DCI.AddToWorklist(V.getNode());
9778     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9779                         St->getPointerInfo(), St->isVolatile(),
9780                         St->isNonTemporal(), St->getAlignment(),
9781                         St->getAAInfo());
9782   }
9783
9784   // If this is a legal vector store, try to combine it into a VST1_UPD.
9785   if (ISD::isNormalStore(N) && VT.isVector() &&
9786       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9787     return CombineBaseUpdate(N, DCI);
9788
9789   return SDValue();
9790 }
9791
9792 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9793 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9794 /// when the VMUL has a constant operand that is a power of 2.
9795 ///
9796 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9797 ///  vmul.f32        d16, d17, d16
9798 ///  vcvt.s32.f32    d16, d16
9799 /// becomes:
9800 ///  vcvt.s32.f32    d16, d16, #3
9801 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9802                                   const ARMSubtarget *Subtarget) {
9803   if (!Subtarget->hasNEON())
9804     return SDValue();
9805
9806   SDValue Op = N->getOperand(0);
9807   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9808     return SDValue();
9809
9810   SDValue ConstVec = Op->getOperand(1);
9811   if (!isa<BuildVectorSDNode>(ConstVec))
9812     return SDValue();
9813
9814   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9815   uint32_t FloatBits = FloatTy.getSizeInBits();
9816   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9817   uint32_t IntBits = IntTy.getSizeInBits();
9818   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9819   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9820     // These instructions only exist converting from f32 to i32. We can handle
9821     // smaller integers by generating an extra truncate, but larger ones would
9822     // be lossy. We also can't handle more then 4 lanes, since these intructions
9823     // only support v2i32/v4i32 types.
9824     return SDValue();
9825   }
9826
9827   BitVector UndefElements;
9828   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9829   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9830   if (C == -1 || C == 0 || C > 32)
9831     return SDValue();
9832
9833   SDLoc dl(N);
9834   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9835   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9836     Intrinsic::arm_neon_vcvtfp2fxu;
9837   SDValue FixConv = DAG.getNode(
9838       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9839       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9840       DAG.getConstant(C, dl, MVT::i32));
9841
9842   if (IntBits < FloatBits)
9843     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9844
9845   return FixConv;
9846 }
9847
9848 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9849 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9850 /// when the VDIV has a constant operand that is a power of 2.
9851 ///
9852 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9853 ///  vcvt.f32.s32    d16, d16
9854 ///  vdiv.f32        d16, d17, d16
9855 /// becomes:
9856 ///  vcvt.f32.s32    d16, d16, #3
9857 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9858                                   const ARMSubtarget *Subtarget) {
9859   if (!Subtarget->hasNEON())
9860     return SDValue();
9861
9862   SDValue Op = N->getOperand(0);
9863   unsigned OpOpcode = Op.getNode()->getOpcode();
9864   if (!N->getValueType(0).isVector() ||
9865       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9866     return SDValue();
9867
9868   SDValue ConstVec = N->getOperand(1);
9869   if (!isa<BuildVectorSDNode>(ConstVec))
9870     return SDValue();
9871
9872   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9873   uint32_t FloatBits = FloatTy.getSizeInBits();
9874   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9875   uint32_t IntBits = IntTy.getSizeInBits();
9876   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9877   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9878     // These instructions only exist converting from i32 to f32. We can handle
9879     // smaller integers by generating an extra extend, but larger ones would
9880     // be lossy. We also can't handle more then 4 lanes, since these intructions
9881     // only support v2i32/v4i32 types.
9882     return SDValue();
9883   }
9884
9885   BitVector UndefElements;
9886   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9887   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9888   if (C == -1 || C == 0 || C > 32)
9889     return SDValue();
9890
9891   SDLoc dl(N);
9892   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9893   SDValue ConvInput = Op.getOperand(0);
9894   if (IntBits < FloatBits)
9895     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9896                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9897                             ConvInput);
9898
9899   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9900     Intrinsic::arm_neon_vcvtfxu2fp;
9901   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9902                      Op.getValueType(),
9903                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9904                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
9905 }
9906
9907 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9908 /// operand of a vector shift operation, where all the elements of the
9909 /// build_vector must have the same constant integer value.
9910 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9911   // Ignore bit_converts.
9912   while (Op.getOpcode() == ISD::BITCAST)
9913     Op = Op.getOperand(0);
9914   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9915   APInt SplatBits, SplatUndef;
9916   unsigned SplatBitSize;
9917   bool HasAnyUndefs;
9918   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9919                                       HasAnyUndefs, ElementBits) ||
9920       SplatBitSize > ElementBits)
9921     return false;
9922   Cnt = SplatBits.getSExtValue();
9923   return true;
9924 }
9925
9926 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9927 /// operand of a vector shift left operation.  That value must be in the range:
9928 ///   0 <= Value < ElementBits for a left shift; or
9929 ///   0 <= Value <= ElementBits for a long left shift.
9930 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9931   assert(VT.isVector() && "vector shift count is not a vector type");
9932   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9933   if (! getVShiftImm(Op, ElementBits, Cnt))
9934     return false;
9935   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9936 }
9937
9938 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9939 /// operand of a vector shift right operation.  For a shift opcode, the value
9940 /// is positive, but for an intrinsic the value count must be negative. The
9941 /// absolute value must be in the range:
9942 ///   1 <= |Value| <= ElementBits for a right shift; or
9943 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9944 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9945                          int64_t &Cnt) {
9946   assert(VT.isVector() && "vector shift count is not a vector type");
9947   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9948   if (! getVShiftImm(Op, ElementBits, Cnt))
9949     return false;
9950   if (!isIntrinsic)
9951     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9952   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9953     Cnt = -Cnt;
9954     return true;
9955   }
9956   return false;
9957 }
9958
9959 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9960 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9961   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9962   switch (IntNo) {
9963   default:
9964     // Don't do anything for most intrinsics.
9965     break;
9966
9967   case Intrinsic::arm_neon_vabds:
9968     if (!N->getValueType(0).isInteger())
9969       return SDValue();
9970     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9971                        N->getOperand(1), N->getOperand(2));
9972   case Intrinsic::arm_neon_vabdu:
9973     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9974                        N->getOperand(1), N->getOperand(2));
9975
9976   // Vector shifts: check for immediate versions and lower them.
9977   // Note: This is done during DAG combining instead of DAG legalizing because
9978   // the build_vectors for 64-bit vector element shift counts are generally
9979   // not legal, and it is hard to see their values after they get legalized to
9980   // loads from a constant pool.
9981   case Intrinsic::arm_neon_vshifts:
9982   case Intrinsic::arm_neon_vshiftu:
9983   case Intrinsic::arm_neon_vrshifts:
9984   case Intrinsic::arm_neon_vrshiftu:
9985   case Intrinsic::arm_neon_vrshiftn:
9986   case Intrinsic::arm_neon_vqshifts:
9987   case Intrinsic::arm_neon_vqshiftu:
9988   case Intrinsic::arm_neon_vqshiftsu:
9989   case Intrinsic::arm_neon_vqshiftns:
9990   case Intrinsic::arm_neon_vqshiftnu:
9991   case Intrinsic::arm_neon_vqshiftnsu:
9992   case Intrinsic::arm_neon_vqrshiftns:
9993   case Intrinsic::arm_neon_vqrshiftnu:
9994   case Intrinsic::arm_neon_vqrshiftnsu: {
9995     EVT VT = N->getOperand(1).getValueType();
9996     int64_t Cnt;
9997     unsigned VShiftOpc = 0;
9998
9999     switch (IntNo) {
10000     case Intrinsic::arm_neon_vshifts:
10001     case Intrinsic::arm_neon_vshiftu:
10002       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10003         VShiftOpc = ARMISD::VSHL;
10004         break;
10005       }
10006       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10007         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10008                      ARMISD::VSHRs : ARMISD::VSHRu);
10009         break;
10010       }
10011       return SDValue();
10012
10013     case Intrinsic::arm_neon_vrshifts:
10014     case Intrinsic::arm_neon_vrshiftu:
10015       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10016         break;
10017       return SDValue();
10018
10019     case Intrinsic::arm_neon_vqshifts:
10020     case Intrinsic::arm_neon_vqshiftu:
10021       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10022         break;
10023       return SDValue();
10024
10025     case Intrinsic::arm_neon_vqshiftsu:
10026       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10027         break;
10028       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10029
10030     case Intrinsic::arm_neon_vrshiftn:
10031     case Intrinsic::arm_neon_vqshiftns:
10032     case Intrinsic::arm_neon_vqshiftnu:
10033     case Intrinsic::arm_neon_vqshiftnsu:
10034     case Intrinsic::arm_neon_vqrshiftns:
10035     case Intrinsic::arm_neon_vqrshiftnu:
10036     case Intrinsic::arm_neon_vqrshiftnsu:
10037       // Narrowing shifts require an immediate right shift.
10038       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10039         break;
10040       llvm_unreachable("invalid shift count for narrowing vector shift "
10041                        "intrinsic");
10042
10043     default:
10044       llvm_unreachable("unhandled vector shift");
10045     }
10046
10047     switch (IntNo) {
10048     case Intrinsic::arm_neon_vshifts:
10049     case Intrinsic::arm_neon_vshiftu:
10050       // Opcode already set above.
10051       break;
10052     case Intrinsic::arm_neon_vrshifts:
10053       VShiftOpc = ARMISD::VRSHRs; break;
10054     case Intrinsic::arm_neon_vrshiftu:
10055       VShiftOpc = ARMISD::VRSHRu; break;
10056     case Intrinsic::arm_neon_vrshiftn:
10057       VShiftOpc = ARMISD::VRSHRN; break;
10058     case Intrinsic::arm_neon_vqshifts:
10059       VShiftOpc = ARMISD::VQSHLs; break;
10060     case Intrinsic::arm_neon_vqshiftu:
10061       VShiftOpc = ARMISD::VQSHLu; break;
10062     case Intrinsic::arm_neon_vqshiftsu:
10063       VShiftOpc = ARMISD::VQSHLsu; break;
10064     case Intrinsic::arm_neon_vqshiftns:
10065       VShiftOpc = ARMISD::VQSHRNs; break;
10066     case Intrinsic::arm_neon_vqshiftnu:
10067       VShiftOpc = ARMISD::VQSHRNu; break;
10068     case Intrinsic::arm_neon_vqshiftnsu:
10069       VShiftOpc = ARMISD::VQSHRNsu; break;
10070     case Intrinsic::arm_neon_vqrshiftns:
10071       VShiftOpc = ARMISD::VQRSHRNs; break;
10072     case Intrinsic::arm_neon_vqrshiftnu:
10073       VShiftOpc = ARMISD::VQRSHRNu; break;
10074     case Intrinsic::arm_neon_vqrshiftnsu:
10075       VShiftOpc = ARMISD::VQRSHRNsu; break;
10076     }
10077
10078     SDLoc dl(N);
10079     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10080                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10081   }
10082
10083   case Intrinsic::arm_neon_vshiftins: {
10084     EVT VT = N->getOperand(1).getValueType();
10085     int64_t Cnt;
10086     unsigned VShiftOpc = 0;
10087
10088     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10089       VShiftOpc = ARMISD::VSLI;
10090     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10091       VShiftOpc = ARMISD::VSRI;
10092     else {
10093       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10094     }
10095
10096     SDLoc dl(N);
10097     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10098                        N->getOperand(1), N->getOperand(2),
10099                        DAG.getConstant(Cnt, dl, MVT::i32));
10100   }
10101
10102   case Intrinsic::arm_neon_vqrshifts:
10103   case Intrinsic::arm_neon_vqrshiftu:
10104     // No immediate versions of these to check for.
10105     break;
10106   }
10107
10108   return SDValue();
10109 }
10110
10111 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10112 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10113 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10114 /// vector element shift counts are generally not legal, and it is hard to see
10115 /// their values after they get legalized to loads from a constant pool.
10116 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10117                                    const ARMSubtarget *ST) {
10118   EVT VT = N->getValueType(0);
10119   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10120     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10121     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10122     SDValue N1 = N->getOperand(1);
10123     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10124       SDValue N0 = N->getOperand(0);
10125       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10126           DAG.MaskedValueIsZero(N0.getOperand(0),
10127                                 APInt::getHighBitsSet(32, 16)))
10128         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10129     }
10130   }
10131
10132   // Nothing to be done for scalar shifts.
10133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10134   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10135     return SDValue();
10136
10137   assert(ST->hasNEON() && "unexpected vector shift");
10138   int64_t Cnt;
10139
10140   switch (N->getOpcode()) {
10141   default: llvm_unreachable("unexpected shift opcode");
10142
10143   case ISD::SHL:
10144     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10145       SDLoc dl(N);
10146       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10147                          DAG.getConstant(Cnt, dl, MVT::i32));
10148     }
10149     break;
10150
10151   case ISD::SRA:
10152   case ISD::SRL:
10153     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10154       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10155                             ARMISD::VSHRs : ARMISD::VSHRu);
10156       SDLoc dl(N);
10157       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10158                          DAG.getConstant(Cnt, dl, MVT::i32));
10159     }
10160   }
10161   return SDValue();
10162 }
10163
10164 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10165 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10166 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10167                                     const ARMSubtarget *ST) {
10168   SDValue N0 = N->getOperand(0);
10169
10170   // Check for sign- and zero-extensions of vector extract operations of 8-
10171   // and 16-bit vector elements.  NEON supports these directly.  They are
10172   // handled during DAG combining because type legalization will promote them
10173   // to 32-bit types and it is messy to recognize the operations after that.
10174   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10175     SDValue Vec = N0.getOperand(0);
10176     SDValue Lane = N0.getOperand(1);
10177     EVT VT = N->getValueType(0);
10178     EVT EltVT = N0.getValueType();
10179     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10180
10181     if (VT == MVT::i32 &&
10182         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10183         TLI.isTypeLegal(Vec.getValueType()) &&
10184         isa<ConstantSDNode>(Lane)) {
10185
10186       unsigned Opc = 0;
10187       switch (N->getOpcode()) {
10188       default: llvm_unreachable("unexpected opcode");
10189       case ISD::SIGN_EXTEND:
10190         Opc = ARMISD::VGETLANEs;
10191         break;
10192       case ISD::ZERO_EXTEND:
10193       case ISD::ANY_EXTEND:
10194         Opc = ARMISD::VGETLANEu;
10195         break;
10196       }
10197       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10198     }
10199   }
10200
10201   return SDValue();
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:
10289     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10290   case ISD::FDIV:
10291     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10292   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10293   case ISD::SHL:
10294   case ISD::SRA:
10295   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10296   case ISD::SIGN_EXTEND:
10297   case ISD::ZERO_EXTEND:
10298   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10299   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10300   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10301   case ARMISD::VLD2DUP:
10302   case ARMISD::VLD3DUP:
10303   case ARMISD::VLD4DUP:
10304     return PerformVLDCombine(N, DCI);
10305   case ARMISD::BUILD_VECTOR:
10306     return PerformARMBUILD_VECTORCombine(N, DCI);
10307   case ISD::INTRINSIC_VOID:
10308   case ISD::INTRINSIC_W_CHAIN:
10309     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10310     case Intrinsic::arm_neon_vld1:
10311     case Intrinsic::arm_neon_vld2:
10312     case Intrinsic::arm_neon_vld3:
10313     case Intrinsic::arm_neon_vld4:
10314     case Intrinsic::arm_neon_vld2lane:
10315     case Intrinsic::arm_neon_vld3lane:
10316     case Intrinsic::arm_neon_vld4lane:
10317     case Intrinsic::arm_neon_vst1:
10318     case Intrinsic::arm_neon_vst2:
10319     case Intrinsic::arm_neon_vst3:
10320     case Intrinsic::arm_neon_vst4:
10321     case Intrinsic::arm_neon_vst2lane:
10322     case Intrinsic::arm_neon_vst3lane:
10323     case Intrinsic::arm_neon_vst4lane:
10324       return PerformVLDCombine(N, DCI);
10325     default: break;
10326     }
10327     break;
10328   }
10329   return SDValue();
10330 }
10331
10332 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10333                                                           EVT VT) const {
10334   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10335 }
10336
10337 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10338                                                        unsigned,
10339                                                        unsigned,
10340                                                        bool *Fast) const {
10341   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10342   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10343
10344   switch (VT.getSimpleVT().SimpleTy) {
10345   default:
10346     return false;
10347   case MVT::i8:
10348   case MVT::i16:
10349   case MVT::i32: {
10350     // Unaligned access can use (for example) LRDB, LRDH, LDR
10351     if (AllowsUnaligned) {
10352       if (Fast)
10353         *Fast = Subtarget->hasV7Ops();
10354       return true;
10355     }
10356     return false;
10357   }
10358   case MVT::f64:
10359   case MVT::v2f64: {
10360     // For any little-endian targets with neon, we can support unaligned ld/st
10361     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10362     // A big-endian target may also explicitly support unaligned accesses
10363     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10364       if (Fast)
10365         *Fast = true;
10366       return true;
10367     }
10368     return false;
10369   }
10370   }
10371 }
10372
10373 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10374                        unsigned AlignCheck) {
10375   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10376           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10377 }
10378
10379 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10380                                            unsigned DstAlign, unsigned SrcAlign,
10381                                            bool IsMemset, bool ZeroMemset,
10382                                            bool MemcpyStrSrc,
10383                                            MachineFunction &MF) const {
10384   const Function *F = MF.getFunction();
10385
10386   // See if we can use NEON instructions for this...
10387   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10388       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10389     bool Fast;
10390     if (Size >= 16 &&
10391         (memOpAlign(SrcAlign, DstAlign, 16) ||
10392          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10393       return MVT::v2f64;
10394     } else if (Size >= 8 &&
10395                (memOpAlign(SrcAlign, DstAlign, 8) ||
10396                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10397                  Fast))) {
10398       return MVT::f64;
10399     }
10400   }
10401
10402   // Lowering to i32/i16 if the size permits.
10403   if (Size >= 4)
10404     return MVT::i32;
10405   else if (Size >= 2)
10406     return MVT::i16;
10407
10408   // Let the target-independent logic figure it out.
10409   return MVT::Other;
10410 }
10411
10412 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10413   if (Val.getOpcode() != ISD::LOAD)
10414     return false;
10415
10416   EVT VT1 = Val.getValueType();
10417   if (!VT1.isSimple() || !VT1.isInteger() ||
10418       !VT2.isSimple() || !VT2.isInteger())
10419     return false;
10420
10421   switch (VT1.getSimpleVT().SimpleTy) {
10422   default: break;
10423   case MVT::i1:
10424   case MVT::i8:
10425   case MVT::i16:
10426     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10427     return true;
10428   }
10429
10430   return false;
10431 }
10432
10433 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10434   EVT VT = ExtVal.getValueType();
10435
10436   if (!isTypeLegal(VT))
10437     return false;
10438
10439   // Don't create a loadext if we can fold the extension into a wide/long
10440   // instruction.
10441   // If there's more than one user instruction, the loadext is desirable no
10442   // matter what.  There can be two uses by the same instruction.
10443   if (ExtVal->use_empty() ||
10444       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10445     return true;
10446
10447   SDNode *U = *ExtVal->use_begin();
10448   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10449        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10450     return false;
10451
10452   return true;
10453 }
10454
10455 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10456   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10457     return false;
10458
10459   if (!isTypeLegal(EVT::getEVT(Ty1)))
10460     return false;
10461
10462   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10463
10464   // Assuming the caller doesn't have a zeroext or signext return parameter,
10465   // truncation all the way down to i1 is valid.
10466   return true;
10467 }
10468
10469
10470 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10471   if (V < 0)
10472     return false;
10473
10474   unsigned Scale = 1;
10475   switch (VT.getSimpleVT().SimpleTy) {
10476   default: return false;
10477   case MVT::i1:
10478   case MVT::i8:
10479     // Scale == 1;
10480     break;
10481   case MVT::i16:
10482     // Scale == 2;
10483     Scale = 2;
10484     break;
10485   case MVT::i32:
10486     // Scale == 4;
10487     Scale = 4;
10488     break;
10489   }
10490
10491   if ((V & (Scale - 1)) != 0)
10492     return false;
10493   V /= Scale;
10494   return V == (V & ((1LL << 5) - 1));
10495 }
10496
10497 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10498                                       const ARMSubtarget *Subtarget) {
10499   bool isNeg = false;
10500   if (V < 0) {
10501     isNeg = true;
10502     V = - V;
10503   }
10504
10505   switch (VT.getSimpleVT().SimpleTy) {
10506   default: return false;
10507   case MVT::i1:
10508   case MVT::i8:
10509   case MVT::i16:
10510   case MVT::i32:
10511     // + imm12 or - imm8
10512     if (isNeg)
10513       return V == (V & ((1LL << 8) - 1));
10514     return V == (V & ((1LL << 12) - 1));
10515   case MVT::f32:
10516   case MVT::f64:
10517     // Same as ARM mode. FIXME: NEON?
10518     if (!Subtarget->hasVFP2())
10519       return false;
10520     if ((V & 3) != 0)
10521       return false;
10522     V >>= 2;
10523     return V == (V & ((1LL << 8) - 1));
10524   }
10525 }
10526
10527 /// isLegalAddressImmediate - Return true if the integer value can be used
10528 /// as the offset of the target addressing mode for load / store of the
10529 /// given type.
10530 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10531                                     const ARMSubtarget *Subtarget) {
10532   if (V == 0)
10533     return true;
10534
10535   if (!VT.isSimple())
10536     return false;
10537
10538   if (Subtarget->isThumb1Only())
10539     return isLegalT1AddressImmediate(V, VT);
10540   else if (Subtarget->isThumb2())
10541     return isLegalT2AddressImmediate(V, VT, Subtarget);
10542
10543   // ARM mode.
10544   if (V < 0)
10545     V = - V;
10546   switch (VT.getSimpleVT().SimpleTy) {
10547   default: return false;
10548   case MVT::i1:
10549   case MVT::i8:
10550   case MVT::i32:
10551     // +- imm12
10552     return V == (V & ((1LL << 12) - 1));
10553   case MVT::i16:
10554     // +- imm8
10555     return V == (V & ((1LL << 8) - 1));
10556   case MVT::f32:
10557   case MVT::f64:
10558     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10559       return false;
10560     if ((V & 3) != 0)
10561       return false;
10562     V >>= 2;
10563     return V == (V & ((1LL << 8) - 1));
10564   }
10565 }
10566
10567 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10568                                                       EVT VT) const {
10569   int Scale = AM.Scale;
10570   if (Scale < 0)
10571     return false;
10572
10573   switch (VT.getSimpleVT().SimpleTy) {
10574   default: return false;
10575   case MVT::i1:
10576   case MVT::i8:
10577   case MVT::i16:
10578   case MVT::i32:
10579     if (Scale == 1)
10580       return true;
10581     // r + r << imm
10582     Scale = Scale & ~1;
10583     return Scale == 2 || Scale == 4 || Scale == 8;
10584   case MVT::i64:
10585     // r + r
10586     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10587       return true;
10588     return false;
10589   case MVT::isVoid:
10590     // Note, we allow "void" uses (basically, uses that aren't loads or
10591     // stores), because arm allows folding a scale into many arithmetic
10592     // operations.  This should be made more precise and revisited later.
10593
10594     // Allow r << imm, but the imm has to be a multiple of two.
10595     if (Scale & 1) return false;
10596     return isPowerOf2_32(Scale);
10597   }
10598 }
10599
10600 /// isLegalAddressingMode - Return true if the addressing mode represented
10601 /// by AM is legal for this target, for a load/store of the specified type.
10602 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10603                                               const AddrMode &AM, Type *Ty,
10604                                               unsigned AS) const {
10605   EVT VT = getValueType(DL, Ty, true);
10606   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10607     return false;
10608
10609   // Can never fold addr of global into load/store.
10610   if (AM.BaseGV)
10611     return false;
10612
10613   switch (AM.Scale) {
10614   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10615     break;
10616   case 1:
10617     if (Subtarget->isThumb1Only())
10618       return false;
10619     // FALL THROUGH.
10620   default:
10621     // ARM doesn't support any R+R*scale+imm addr modes.
10622     if (AM.BaseOffs)
10623       return false;
10624
10625     if (!VT.isSimple())
10626       return false;
10627
10628     if (Subtarget->isThumb2())
10629       return isLegalT2ScaledAddressingMode(AM, VT);
10630
10631     int Scale = AM.Scale;
10632     switch (VT.getSimpleVT().SimpleTy) {
10633     default: return false;
10634     case MVT::i1:
10635     case MVT::i8:
10636     case MVT::i32:
10637       if (Scale < 0) Scale = -Scale;
10638       if (Scale == 1)
10639         return true;
10640       // r + r << imm
10641       return isPowerOf2_32(Scale & ~1);
10642     case MVT::i16:
10643     case MVT::i64:
10644       // r + r
10645       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10646         return true;
10647       return false;
10648
10649     case MVT::isVoid:
10650       // Note, we allow "void" uses (basically, uses that aren't loads or
10651       // stores), because arm allows folding a scale into many arithmetic
10652       // operations.  This should be made more precise and revisited later.
10653
10654       // Allow r << imm, but the imm has to be a multiple of two.
10655       if (Scale & 1) return false;
10656       return isPowerOf2_32(Scale);
10657     }
10658   }
10659   return true;
10660 }
10661
10662 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10663 /// icmp immediate, that is the target has icmp instructions which can compare
10664 /// a register against the immediate without having to materialize the
10665 /// immediate into a register.
10666 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10667   // Thumb2 and ARM modes can use cmn for negative immediates.
10668   if (!Subtarget->isThumb())
10669     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10670   if (Subtarget->isThumb2())
10671     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10672   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10673   return Imm >= 0 && Imm <= 255;
10674 }
10675
10676 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10677 /// *or sub* immediate, that is the target has add or sub instructions which can
10678 /// add a register with the immediate without having to materialize the
10679 /// immediate into a register.
10680 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10681   // Same encoding for add/sub, just flip the sign.
10682   int64_t AbsImm = std::abs(Imm);
10683   if (!Subtarget->isThumb())
10684     return ARM_AM::getSOImmVal(AbsImm) != -1;
10685   if (Subtarget->isThumb2())
10686     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10687   // Thumb1 only has 8-bit unsigned immediate.
10688   return AbsImm >= 0 && AbsImm <= 255;
10689 }
10690
10691 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10692                                       bool isSEXTLoad, SDValue &Base,
10693                                       SDValue &Offset, bool &isInc,
10694                                       SelectionDAG &DAG) {
10695   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10696     return false;
10697
10698   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10699     // AddressingMode 3
10700     Base = Ptr->getOperand(0);
10701     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10702       int RHSC = (int)RHS->getZExtValue();
10703       if (RHSC < 0 && RHSC > -256) {
10704         assert(Ptr->getOpcode() == ISD::ADD);
10705         isInc = false;
10706         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10707         return true;
10708       }
10709     }
10710     isInc = (Ptr->getOpcode() == ISD::ADD);
10711     Offset = Ptr->getOperand(1);
10712     return true;
10713   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10714     // AddressingMode 2
10715     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10716       int RHSC = (int)RHS->getZExtValue();
10717       if (RHSC < 0 && RHSC > -0x1000) {
10718         assert(Ptr->getOpcode() == ISD::ADD);
10719         isInc = false;
10720         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10721         Base = Ptr->getOperand(0);
10722         return true;
10723       }
10724     }
10725
10726     if (Ptr->getOpcode() == ISD::ADD) {
10727       isInc = true;
10728       ARM_AM::ShiftOpc ShOpcVal=
10729         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10730       if (ShOpcVal != ARM_AM::no_shift) {
10731         Base = Ptr->getOperand(1);
10732         Offset = Ptr->getOperand(0);
10733       } else {
10734         Base = Ptr->getOperand(0);
10735         Offset = Ptr->getOperand(1);
10736       }
10737       return true;
10738     }
10739
10740     isInc = (Ptr->getOpcode() == ISD::ADD);
10741     Base = Ptr->getOperand(0);
10742     Offset = Ptr->getOperand(1);
10743     return true;
10744   }
10745
10746   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10747   return false;
10748 }
10749
10750 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10751                                      bool isSEXTLoad, SDValue &Base,
10752                                      SDValue &Offset, bool &isInc,
10753                                      SelectionDAG &DAG) {
10754   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10755     return false;
10756
10757   Base = Ptr->getOperand(0);
10758   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10759     int RHSC = (int)RHS->getZExtValue();
10760     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10761       assert(Ptr->getOpcode() == ISD::ADD);
10762       isInc = false;
10763       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10764       return true;
10765     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10766       isInc = Ptr->getOpcode() == ISD::ADD;
10767       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10768       return true;
10769     }
10770   }
10771
10772   return false;
10773 }
10774
10775 /// getPreIndexedAddressParts - returns true by value, base pointer and
10776 /// offset pointer and addressing mode by reference if the node's address
10777 /// can be legally represented as pre-indexed load / store address.
10778 bool
10779 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10780                                              SDValue &Offset,
10781                                              ISD::MemIndexedMode &AM,
10782                                              SelectionDAG &DAG) const {
10783   if (Subtarget->isThumb1Only())
10784     return false;
10785
10786   EVT VT;
10787   SDValue Ptr;
10788   bool isSEXTLoad = false;
10789   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10790     Ptr = LD->getBasePtr();
10791     VT  = LD->getMemoryVT();
10792     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10793   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10794     Ptr = ST->getBasePtr();
10795     VT  = ST->getMemoryVT();
10796   } else
10797     return false;
10798
10799   bool isInc;
10800   bool isLegal = false;
10801   if (Subtarget->isThumb2())
10802     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10803                                        Offset, isInc, DAG);
10804   else
10805     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10806                                         Offset, isInc, DAG);
10807   if (!isLegal)
10808     return false;
10809
10810   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10811   return true;
10812 }
10813
10814 /// getPostIndexedAddressParts - returns true by value, base pointer and
10815 /// offset pointer and addressing mode by reference if this node can be
10816 /// combined with a load / store to form a post-indexed load / store.
10817 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10818                                                    SDValue &Base,
10819                                                    SDValue &Offset,
10820                                                    ISD::MemIndexedMode &AM,
10821                                                    SelectionDAG &DAG) const {
10822   if (Subtarget->isThumb1Only())
10823     return false;
10824
10825   EVT VT;
10826   SDValue Ptr;
10827   bool isSEXTLoad = false;
10828   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10829     VT  = LD->getMemoryVT();
10830     Ptr = LD->getBasePtr();
10831     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10832   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10833     VT  = ST->getMemoryVT();
10834     Ptr = ST->getBasePtr();
10835   } else
10836     return false;
10837
10838   bool isInc;
10839   bool isLegal = false;
10840   if (Subtarget->isThumb2())
10841     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10842                                        isInc, DAG);
10843   else
10844     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10845                                         isInc, DAG);
10846   if (!isLegal)
10847     return false;
10848
10849   if (Ptr != Base) {
10850     // Swap base ptr and offset to catch more post-index load / store when
10851     // it's legal. In Thumb2 mode, offset must be an immediate.
10852     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10853         !Subtarget->isThumb2())
10854       std::swap(Base, Offset);
10855
10856     // Post-indexed load / store update the base pointer.
10857     if (Ptr != Base)
10858       return false;
10859   }
10860
10861   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10862   return true;
10863 }
10864
10865 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10866                                                       APInt &KnownZero,
10867                                                       APInt &KnownOne,
10868                                                       const SelectionDAG &DAG,
10869                                                       unsigned Depth) const {
10870   unsigned BitWidth = KnownOne.getBitWidth();
10871   KnownZero = KnownOne = APInt(BitWidth, 0);
10872   switch (Op.getOpcode()) {
10873   default: break;
10874   case ARMISD::ADDC:
10875   case ARMISD::ADDE:
10876   case ARMISD::SUBC:
10877   case ARMISD::SUBE:
10878     // These nodes' second result is a boolean
10879     if (Op.getResNo() == 0)
10880       break;
10881     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10882     break;
10883   case ARMISD::CMOV: {
10884     // Bits are known zero/one if known on the LHS and RHS.
10885     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10886     if (KnownZero == 0 && KnownOne == 0) return;
10887
10888     APInt KnownZeroRHS, KnownOneRHS;
10889     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10890     KnownZero &= KnownZeroRHS;
10891     KnownOne  &= KnownOneRHS;
10892     return;
10893   }
10894   case ISD::INTRINSIC_W_CHAIN: {
10895     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10896     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10897     switch (IntID) {
10898     default: return;
10899     case Intrinsic::arm_ldaex:
10900     case Intrinsic::arm_ldrex: {
10901       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10902       unsigned MemBits = VT.getScalarType().getSizeInBits();
10903       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10904       return;
10905     }
10906     }
10907   }
10908   }
10909 }
10910
10911 //===----------------------------------------------------------------------===//
10912 //                           ARM Inline Assembly Support
10913 //===----------------------------------------------------------------------===//
10914
10915 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10916   // Looking for "rev" which is V6+.
10917   if (!Subtarget->hasV6Ops())
10918     return false;
10919
10920   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10921   std::string AsmStr = IA->getAsmString();
10922   SmallVector<StringRef, 4> AsmPieces;
10923   SplitString(AsmStr, AsmPieces, ";\n");
10924
10925   switch (AsmPieces.size()) {
10926   default: return false;
10927   case 1:
10928     AsmStr = AsmPieces[0];
10929     AsmPieces.clear();
10930     SplitString(AsmStr, AsmPieces, " \t,");
10931
10932     // rev $0, $1
10933     if (AsmPieces.size() == 3 &&
10934         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10935         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10936       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10937       if (Ty && Ty->getBitWidth() == 32)
10938         return IntrinsicLowering::LowerToByteSwap(CI);
10939     }
10940     break;
10941   }
10942
10943   return false;
10944 }
10945
10946 /// getConstraintType - Given a constraint letter, return the type of
10947 /// constraint it is for this target.
10948 ARMTargetLowering::ConstraintType
10949 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10950   if (Constraint.size() == 1) {
10951     switch (Constraint[0]) {
10952     default:  break;
10953     case 'l': return C_RegisterClass;
10954     case 'w': return C_RegisterClass;
10955     case 'h': return C_RegisterClass;
10956     case 'x': return C_RegisterClass;
10957     case 't': return C_RegisterClass;
10958     case 'j': return C_Other; // Constant for movw.
10959       // An address with a single base register. Due to the way we
10960       // currently handle addresses it is the same as an 'r' memory constraint.
10961     case 'Q': return C_Memory;
10962     }
10963   } else if (Constraint.size() == 2) {
10964     switch (Constraint[0]) {
10965     default: break;
10966     // All 'U+' constraints are addresses.
10967     case 'U': return C_Memory;
10968     }
10969   }
10970   return TargetLowering::getConstraintType(Constraint);
10971 }
10972
10973 /// Examine constraint type and operand type and determine a weight value.
10974 /// This object must already have been set up with the operand type
10975 /// and the current alternative constraint selected.
10976 TargetLowering::ConstraintWeight
10977 ARMTargetLowering::getSingleConstraintMatchWeight(
10978     AsmOperandInfo &info, const char *constraint) const {
10979   ConstraintWeight weight = CW_Invalid;
10980   Value *CallOperandVal = info.CallOperandVal;
10981     // If we don't have a value, we can't do a match,
10982     // but allow it at the lowest weight.
10983   if (!CallOperandVal)
10984     return CW_Default;
10985   Type *type = CallOperandVal->getType();
10986   // Look at the constraint type.
10987   switch (*constraint) {
10988   default:
10989     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10990     break;
10991   case 'l':
10992     if (type->isIntegerTy()) {
10993       if (Subtarget->isThumb())
10994         weight = CW_SpecificReg;
10995       else
10996         weight = CW_Register;
10997     }
10998     break;
10999   case 'w':
11000     if (type->isFloatingPointTy())
11001       weight = CW_Register;
11002     break;
11003   }
11004   return weight;
11005 }
11006
11007 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11008 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11009     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11010   if (Constraint.size() == 1) {
11011     // GCC ARM Constraint Letters
11012     switch (Constraint[0]) {
11013     case 'l': // Low regs or general regs.
11014       if (Subtarget->isThumb())
11015         return RCPair(0U, &ARM::tGPRRegClass);
11016       return RCPair(0U, &ARM::GPRRegClass);
11017     case 'h': // High regs or no regs.
11018       if (Subtarget->isThumb())
11019         return RCPair(0U, &ARM::hGPRRegClass);
11020       break;
11021     case 'r':
11022       if (Subtarget->isThumb1Only())
11023         return RCPair(0U, &ARM::tGPRRegClass);
11024       return RCPair(0U, &ARM::GPRRegClass);
11025     case 'w':
11026       if (VT == MVT::Other)
11027         break;
11028       if (VT == MVT::f32)
11029         return RCPair(0U, &ARM::SPRRegClass);
11030       if (VT.getSizeInBits() == 64)
11031         return RCPair(0U, &ARM::DPRRegClass);
11032       if (VT.getSizeInBits() == 128)
11033         return RCPair(0U, &ARM::QPRRegClass);
11034       break;
11035     case 'x':
11036       if (VT == MVT::Other)
11037         break;
11038       if (VT == MVT::f32)
11039         return RCPair(0U, &ARM::SPR_8RegClass);
11040       if (VT.getSizeInBits() == 64)
11041         return RCPair(0U, &ARM::DPR_8RegClass);
11042       if (VT.getSizeInBits() == 128)
11043         return RCPair(0U, &ARM::QPR_8RegClass);
11044       break;
11045     case 't':
11046       if (VT == MVT::f32)
11047         return RCPair(0U, &ARM::SPRRegClass);
11048       break;
11049     }
11050   }
11051   if (StringRef("{cc}").equals_lower(Constraint))
11052     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11053
11054   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11055 }
11056
11057 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11058 /// vector.  If it is invalid, don't add anything to Ops.
11059 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11060                                                      std::string &Constraint,
11061                                                      std::vector<SDValue>&Ops,
11062                                                      SelectionDAG &DAG) const {
11063   SDValue Result;
11064
11065   // Currently only support length 1 constraints.
11066   if (Constraint.length() != 1) return;
11067
11068   char ConstraintLetter = Constraint[0];
11069   switch (ConstraintLetter) {
11070   default: break;
11071   case 'j':
11072   case 'I': case 'J': case 'K': case 'L':
11073   case 'M': case 'N': case 'O':
11074     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11075     if (!C)
11076       return;
11077
11078     int64_t CVal64 = C->getSExtValue();
11079     int CVal = (int) CVal64;
11080     // None of these constraints allow values larger than 32 bits.  Check
11081     // that the value fits in an int.
11082     if (CVal != CVal64)
11083       return;
11084
11085     switch (ConstraintLetter) {
11086       case 'j':
11087         // Constant suitable for movw, must be between 0 and
11088         // 65535.
11089         if (Subtarget->hasV6T2Ops())
11090           if (CVal >= 0 && CVal <= 65535)
11091             break;
11092         return;
11093       case 'I':
11094         if (Subtarget->isThumb1Only()) {
11095           // This must be a constant between 0 and 255, for ADD
11096           // immediates.
11097           if (CVal >= 0 && CVal <= 255)
11098             break;
11099         } else if (Subtarget->isThumb2()) {
11100           // A constant that can be used as an immediate value in a
11101           // data-processing instruction.
11102           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11103             break;
11104         } else {
11105           // A constant that can be used as an immediate value in a
11106           // data-processing instruction.
11107           if (ARM_AM::getSOImmVal(CVal) != -1)
11108             break;
11109         }
11110         return;
11111
11112       case 'J':
11113         if (Subtarget->isThumb()) {  // FIXME thumb2
11114           // This must be a constant between -255 and -1, for negated ADD
11115           // immediates. This can be used in GCC with an "n" modifier that
11116           // prints the negated value, for use with SUB instructions. It is
11117           // not useful otherwise but is implemented for compatibility.
11118           if (CVal >= -255 && CVal <= -1)
11119             break;
11120         } else {
11121           // This must be a constant between -4095 and 4095. It is not clear
11122           // what this constraint is intended for. Implemented for
11123           // compatibility with GCC.
11124           if (CVal >= -4095 && CVal <= 4095)
11125             break;
11126         }
11127         return;
11128
11129       case 'K':
11130         if (Subtarget->isThumb1Only()) {
11131           // A 32-bit value where only one byte has a nonzero value. Exclude
11132           // zero to match GCC. This constraint is used by GCC internally for
11133           // constants that can be loaded with a move/shift combination.
11134           // It is not useful otherwise but is implemented for compatibility.
11135           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11136             break;
11137         } else if (Subtarget->isThumb2()) {
11138           // A constant whose bitwise inverse can be used as an immediate
11139           // value in a data-processing instruction. This can be used in GCC
11140           // with a "B" modifier that prints the inverted value, for use with
11141           // BIC and MVN instructions. It is not useful otherwise but is
11142           // implemented for compatibility.
11143           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11144             break;
11145         } else {
11146           // A constant whose bitwise inverse can be used as an immediate
11147           // value in a data-processing instruction. This can be used in GCC
11148           // with a "B" modifier that prints the inverted value, for use with
11149           // BIC and MVN instructions. It is not useful otherwise but is
11150           // implemented for compatibility.
11151           if (ARM_AM::getSOImmVal(~CVal) != -1)
11152             break;
11153         }
11154         return;
11155
11156       case 'L':
11157         if (Subtarget->isThumb1Only()) {
11158           // This must be a constant between -7 and 7,
11159           // for 3-operand ADD/SUB immediate instructions.
11160           if (CVal >= -7 && CVal < 7)
11161             break;
11162         } else if (Subtarget->isThumb2()) {
11163           // A constant whose negation can be used as an immediate value in a
11164           // data-processing instruction. This can be used in GCC with an "n"
11165           // modifier that prints the negated value, for use with SUB
11166           // instructions. It is not useful otherwise but is implemented for
11167           // compatibility.
11168           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11169             break;
11170         } else {
11171           // A constant whose negation can be used as an immediate value in a
11172           // data-processing instruction. This can be used in GCC with an "n"
11173           // modifier that prints the negated value, for use with SUB
11174           // instructions. It is not useful otherwise but is implemented for
11175           // compatibility.
11176           if (ARM_AM::getSOImmVal(-CVal) != -1)
11177             break;
11178         }
11179         return;
11180
11181       case 'M':
11182         if (Subtarget->isThumb()) { // FIXME thumb2
11183           // This must be a multiple of 4 between 0 and 1020, for
11184           // ADD sp + immediate.
11185           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11186             break;
11187         } else {
11188           // A power of two or a constant between 0 and 32.  This is used in
11189           // GCC for the shift amount on shifted register operands, but it is
11190           // useful in general for any shift amounts.
11191           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11192             break;
11193         }
11194         return;
11195
11196       case 'N':
11197         if (Subtarget->isThumb()) {  // FIXME thumb2
11198           // This must be a constant between 0 and 31, for shift amounts.
11199           if (CVal >= 0 && CVal <= 31)
11200             break;
11201         }
11202         return;
11203
11204       case 'O':
11205         if (Subtarget->isThumb()) {  // FIXME thumb2
11206           // This must be a multiple of 4 between -508 and 508, for
11207           // ADD/SUB sp = sp + immediate.
11208           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11209             break;
11210         }
11211         return;
11212     }
11213     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11214     break;
11215   }
11216
11217   if (Result.getNode()) {
11218     Ops.push_back(Result);
11219     return;
11220   }
11221   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11222 }
11223
11224 static RTLIB::Libcall getDivRemLibcall(
11225     const SDNode *N, MVT::SimpleValueType SVT) {
11226   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11227           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11228          "Unhandled Opcode in getDivRemLibcall");
11229   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11230                   N->getOpcode() == ISD::SREM;
11231   RTLIB::Libcall LC;
11232   switch (SVT) {
11233   default: llvm_unreachable("Unexpected request for libcall!");
11234   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11235   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11236   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11237   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11238   }
11239   return LC;
11240 }
11241
11242 static TargetLowering::ArgListTy getDivRemArgList(
11243     const SDNode *N, LLVMContext *Context) {
11244   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11245           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11246          "Unhandled Opcode in getDivRemArgList");
11247   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11248                   N->getOpcode() == ISD::SREM;
11249   TargetLowering::ArgListTy Args;
11250   TargetLowering::ArgListEntry Entry;
11251   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11252     EVT ArgVT = N->getOperand(i).getValueType();
11253     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11254     Entry.Node = N->getOperand(i);
11255     Entry.Ty = ArgTy;
11256     Entry.isSExt = isSigned;
11257     Entry.isZExt = !isSigned;
11258     Args.push_back(Entry);
11259   }
11260   return Args;
11261 }
11262
11263 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11264   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11265          "Register-based DivRem lowering only");
11266   unsigned Opcode = Op->getOpcode();
11267   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11268          "Invalid opcode for Div/Rem lowering");
11269   bool isSigned = (Opcode == ISD::SDIVREM);
11270   EVT VT = Op->getValueType(0);
11271   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11272
11273   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11274                                        VT.getSimpleVT().SimpleTy);
11275   SDValue InChain = DAG.getEntryNode();
11276
11277   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11278                                                     DAG.getContext());
11279
11280   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11281                                          getPointerTy(DAG.getDataLayout()));
11282
11283   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11284
11285   SDLoc dl(Op);
11286   TargetLowering::CallLoweringInfo CLI(DAG);
11287   CLI.setDebugLoc(dl).setChain(InChain)
11288     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11289     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11290
11291   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11292   return CallInfo.first;
11293 }
11294
11295 // Lowers REM using divmod helpers
11296 // see RTABI section 4.2/4.3
11297 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11298   // Build return types (div and rem)
11299   std::vector<Type*> RetTyParams;
11300   Type *RetTyElement;
11301
11302   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11303   default: llvm_unreachable("Unexpected request for libcall!");
11304   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11305   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11306   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11307   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11308   }
11309
11310   RetTyParams.push_back(RetTyElement);
11311   RetTyParams.push_back(RetTyElement);
11312   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11313   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11314
11315   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11316                                                              SimpleTy);
11317   SDValue InChain = DAG.getEntryNode();
11318   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11319   bool isSigned = N->getOpcode() == ISD::SREM;
11320   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11321                                          getPointerTy(DAG.getDataLayout()));
11322
11323   // Lower call
11324   CallLoweringInfo CLI(DAG);
11325   CLI.setChain(InChain)
11326      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11327      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11328   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11329
11330   // Return second (rem) result operand (first contains div)
11331   SDNode *ResNode = CallResult.first.getNode();
11332   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11333   return ResNode->getOperand(1);
11334 }
11335
11336 SDValue
11337 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11338   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11339   SDLoc DL(Op);
11340
11341   // Get the inputs.
11342   SDValue Chain = Op.getOperand(0);
11343   SDValue Size  = Op.getOperand(1);
11344
11345   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11346                               DAG.getConstant(2, DL, MVT::i32));
11347
11348   SDValue Flag;
11349   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11350   Flag = Chain.getValue(1);
11351
11352   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11353   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11354
11355   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11356   Chain = NewSP.getValue(1);
11357
11358   SDValue Ops[2] = { NewSP, Chain };
11359   return DAG.getMergeValues(Ops, DL);
11360 }
11361
11362 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11363   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11364          "Unexpected type for custom-lowering FP_EXTEND");
11365
11366   RTLIB::Libcall LC;
11367   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11368
11369   SDValue SrcVal = Op.getOperand(0);
11370   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11371                      SDLoc(Op)).first;
11372 }
11373
11374 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11375   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11376          Subtarget->isFPOnlySP() &&
11377          "Unexpected type for custom-lowering FP_ROUND");
11378
11379   RTLIB::Libcall LC;
11380   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11381
11382   SDValue SrcVal = Op.getOperand(0);
11383   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11384                      SDLoc(Op)).first;
11385 }
11386
11387 bool
11388 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11389   // The ARM target isn't yet aware of offsets.
11390   return false;
11391 }
11392
11393 bool ARM::isBitFieldInvertedMask(unsigned v) {
11394   if (v == 0xffffffff)
11395     return false;
11396
11397   // there can be 1's on either or both "outsides", all the "inside"
11398   // bits must be 0's
11399   return isShiftedMask_32(~v);
11400 }
11401
11402 /// isFPImmLegal - Returns true if the target can instruction select the
11403 /// specified FP immediate natively. If false, the legalizer will
11404 /// materialize the FP immediate as a load from a constant pool.
11405 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11406   if (!Subtarget->hasVFP3())
11407     return false;
11408   if (VT == MVT::f32)
11409     return ARM_AM::getFP32Imm(Imm) != -1;
11410   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11411     return ARM_AM::getFP64Imm(Imm) != -1;
11412   return false;
11413 }
11414
11415 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11416 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11417 /// specified in the intrinsic calls.
11418 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11419                                            const CallInst &I,
11420                                            unsigned Intrinsic) const {
11421   switch (Intrinsic) {
11422   case Intrinsic::arm_neon_vld1:
11423   case Intrinsic::arm_neon_vld2:
11424   case Intrinsic::arm_neon_vld3:
11425   case Intrinsic::arm_neon_vld4:
11426   case Intrinsic::arm_neon_vld2lane:
11427   case Intrinsic::arm_neon_vld3lane:
11428   case Intrinsic::arm_neon_vld4lane: {
11429     Info.opc = ISD::INTRINSIC_W_CHAIN;
11430     // Conservatively set memVT to the entire set of vectors loaded.
11431     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11432     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11433     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11434     Info.ptrVal = I.getArgOperand(0);
11435     Info.offset = 0;
11436     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11437     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11438     Info.vol = false; // volatile loads with NEON intrinsics not supported
11439     Info.readMem = true;
11440     Info.writeMem = false;
11441     return true;
11442   }
11443   case Intrinsic::arm_neon_vst1:
11444   case Intrinsic::arm_neon_vst2:
11445   case Intrinsic::arm_neon_vst3:
11446   case Intrinsic::arm_neon_vst4:
11447   case Intrinsic::arm_neon_vst2lane:
11448   case Intrinsic::arm_neon_vst3lane:
11449   case Intrinsic::arm_neon_vst4lane: {
11450     Info.opc = ISD::INTRINSIC_VOID;
11451     // Conservatively set memVT to the entire set of vectors stored.
11452     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11453     unsigned NumElts = 0;
11454     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11455       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11456       if (!ArgTy->isVectorTy())
11457         break;
11458       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11459     }
11460     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11461     Info.ptrVal = I.getArgOperand(0);
11462     Info.offset = 0;
11463     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11464     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11465     Info.vol = false; // volatile stores with NEON intrinsics not supported
11466     Info.readMem = false;
11467     Info.writeMem = true;
11468     return true;
11469   }
11470   case Intrinsic::arm_ldaex:
11471   case Intrinsic::arm_ldrex: {
11472     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11473     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11474     Info.opc = ISD::INTRINSIC_W_CHAIN;
11475     Info.memVT = MVT::getVT(PtrTy->getElementType());
11476     Info.ptrVal = I.getArgOperand(0);
11477     Info.offset = 0;
11478     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11479     Info.vol = true;
11480     Info.readMem = true;
11481     Info.writeMem = false;
11482     return true;
11483   }
11484   case Intrinsic::arm_stlex:
11485   case Intrinsic::arm_strex: {
11486     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11487     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11488     Info.opc = ISD::INTRINSIC_W_CHAIN;
11489     Info.memVT = MVT::getVT(PtrTy->getElementType());
11490     Info.ptrVal = I.getArgOperand(1);
11491     Info.offset = 0;
11492     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11493     Info.vol = true;
11494     Info.readMem = false;
11495     Info.writeMem = true;
11496     return true;
11497   }
11498   case Intrinsic::arm_stlexd:
11499   case Intrinsic::arm_strexd: {
11500     Info.opc = ISD::INTRINSIC_W_CHAIN;
11501     Info.memVT = MVT::i64;
11502     Info.ptrVal = I.getArgOperand(2);
11503     Info.offset = 0;
11504     Info.align = 8;
11505     Info.vol = true;
11506     Info.readMem = false;
11507     Info.writeMem = true;
11508     return true;
11509   }
11510   case Intrinsic::arm_ldaexd:
11511   case Intrinsic::arm_ldrexd: {
11512     Info.opc = ISD::INTRINSIC_W_CHAIN;
11513     Info.memVT = MVT::i64;
11514     Info.ptrVal = I.getArgOperand(0);
11515     Info.offset = 0;
11516     Info.align = 8;
11517     Info.vol = true;
11518     Info.readMem = true;
11519     Info.writeMem = false;
11520     return true;
11521   }
11522   default:
11523     break;
11524   }
11525
11526   return false;
11527 }
11528
11529 /// \brief Returns true if it is beneficial to convert a load of a constant
11530 /// to just the constant itself.
11531 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11532                                                           Type *Ty) const {
11533   assert(Ty->isIntegerTy());
11534
11535   unsigned Bits = Ty->getPrimitiveSizeInBits();
11536   if (Bits == 0 || Bits > 32)
11537     return false;
11538   return true;
11539 }
11540
11541 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11542                                         ARM_MB::MemBOpt Domain) const {
11543   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11544
11545   // First, if the target has no DMB, see what fallback we can use.
11546   if (!Subtarget->hasDataBarrier()) {
11547     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11548     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11549     // here.
11550     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11551       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11552       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11553                         Builder.getInt32(0), Builder.getInt32(7),
11554                         Builder.getInt32(10), Builder.getInt32(5)};
11555       return Builder.CreateCall(MCR, args);
11556     } else {
11557       // Instead of using barriers, atomic accesses on these subtargets use
11558       // libcalls.
11559       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11560     }
11561   } else {
11562     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11563     // Only a full system barrier exists in the M-class architectures.
11564     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11565     Constant *CDomain = Builder.getInt32(Domain);
11566     return Builder.CreateCall(DMB, CDomain);
11567   }
11568 }
11569
11570 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11571 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11572                                          AtomicOrdering Ord, bool IsStore,
11573                                          bool IsLoad) const {
11574   if (!getInsertFencesForAtomic())
11575     return nullptr;
11576
11577   switch (Ord) {
11578   case NotAtomic:
11579   case Unordered:
11580     llvm_unreachable("Invalid fence: unordered/non-atomic");
11581   case Monotonic:
11582   case Acquire:
11583     return nullptr; // Nothing to do
11584   case SequentiallyConsistent:
11585     if (!IsStore)
11586       return nullptr; // Nothing to do
11587     /*FALLTHROUGH*/
11588   case Release:
11589   case AcquireRelease:
11590     if (Subtarget->isSwift())
11591       return makeDMB(Builder, ARM_MB::ISHST);
11592     // FIXME: add a comment with a link to documentation justifying this.
11593     else
11594       return makeDMB(Builder, ARM_MB::ISH);
11595   }
11596   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11597 }
11598
11599 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11600                                           AtomicOrdering Ord, bool IsStore,
11601                                           bool IsLoad) const {
11602   if (!getInsertFencesForAtomic())
11603     return nullptr;
11604
11605   switch (Ord) {
11606   case NotAtomic:
11607   case Unordered:
11608     llvm_unreachable("Invalid fence: unordered/not-atomic");
11609   case Monotonic:
11610   case Release:
11611     return nullptr; // Nothing to do
11612   case Acquire:
11613   case AcquireRelease:
11614   case SequentiallyConsistent:
11615     return makeDMB(Builder, ARM_MB::ISH);
11616   }
11617   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11618 }
11619
11620 // Loads and stores less than 64-bits are already atomic; ones above that
11621 // are doomed anyway, so defer to the default libcall and blame the OS when
11622 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11623 // anything for those.
11624 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11625   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11626   return (Size == 64) && !Subtarget->isMClass();
11627 }
11628
11629 // Loads and stores less than 64-bits are already atomic; ones above that
11630 // are doomed anyway, so defer to the default libcall and blame the OS when
11631 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11632 // anything for those.
11633 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11634 // guarantee, see DDI0406C ARM architecture reference manual,
11635 // sections A8.8.72-74 LDRD)
11636 TargetLowering::AtomicExpansionKind
11637 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11638   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11639   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11640                                                   : AtomicExpansionKind::None;
11641 }
11642
11643 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11644 // and up to 64 bits on the non-M profiles
11645 TargetLowering::AtomicExpansionKind
11646 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11647   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11648   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11649              ? AtomicExpansionKind::LLSC
11650              : AtomicExpansionKind::None;
11651 }
11652
11653 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11654     AtomicCmpXchgInst *AI) const {
11655   return true;
11656 }
11657
11658 // This has so far only been implemented for MachO.
11659 bool ARMTargetLowering::useLoadStackGuardNode() const {
11660   return Subtarget->isTargetMachO();
11661 }
11662
11663 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11664                                                   unsigned &Cost) const {
11665   // If we do not have NEON, vector types are not natively supported.
11666   if (!Subtarget->hasNEON())
11667     return false;
11668
11669   // Floating point values and vector values map to the same register file.
11670   // Therefore, although we could do a store extract of a vector type, this is
11671   // better to leave at float as we have more freedom in the addressing mode for
11672   // those.
11673   if (VectorTy->isFPOrFPVectorTy())
11674     return false;
11675
11676   // If the index is unknown at compile time, this is very expensive to lower
11677   // and it is not possible to combine the store with the extract.
11678   if (!isa<ConstantInt>(Idx))
11679     return false;
11680
11681   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11682   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11683   // We can do a store + vector extract on any vector that fits perfectly in a D
11684   // or Q register.
11685   if (BitWidth == 64 || BitWidth == 128) {
11686     Cost = 0;
11687     return true;
11688   }
11689   return false;
11690 }
11691
11692 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11693                                          AtomicOrdering Ord) const {
11694   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11695   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11696   bool IsAcquire = isAtLeastAcquire(Ord);
11697
11698   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11699   // intrinsic must return {i32, i32} and we have to recombine them into a
11700   // single i64 here.
11701   if (ValTy->getPrimitiveSizeInBits() == 64) {
11702     Intrinsic::ID Int =
11703         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11704     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11705
11706     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11707     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11708
11709     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11710     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11711     if (!Subtarget->isLittle())
11712       std::swap (Lo, Hi);
11713     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11714     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11715     return Builder.CreateOr(
11716         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11717   }
11718
11719   Type *Tys[] = { Addr->getType() };
11720   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11721   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11722
11723   return Builder.CreateTruncOrBitCast(
11724       Builder.CreateCall(Ldrex, Addr),
11725       cast<PointerType>(Addr->getType())->getElementType());
11726 }
11727
11728 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11729     IRBuilder<> &Builder) const {
11730   if (!Subtarget->hasV7Ops())
11731     return;
11732   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11733   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11734 }
11735
11736 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11737                                                Value *Addr,
11738                                                AtomicOrdering Ord) const {
11739   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11740   bool IsRelease = isAtLeastRelease(Ord);
11741
11742   // Since the intrinsics must have legal type, the i64 intrinsics take two
11743   // parameters: "i32, i32". We must marshal Val into the appropriate form
11744   // before the call.
11745   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11746     Intrinsic::ID Int =
11747         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11748     Function *Strex = Intrinsic::getDeclaration(M, Int);
11749     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11750
11751     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11752     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11753     if (!Subtarget->isLittle())
11754       std::swap (Lo, Hi);
11755     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11756     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11757   }
11758
11759   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11760   Type *Tys[] = { Addr->getType() };
11761   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11762
11763   return Builder.CreateCall(
11764       Strex, {Builder.CreateZExtOrBitCast(
11765                   Val, Strex->getFunctionType()->getParamType(0)),
11766               Addr});
11767 }
11768
11769 /// \brief Lower an interleaved load into a vldN intrinsic.
11770 ///
11771 /// E.g. Lower an interleaved load (Factor = 2):
11772 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11773 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11774 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11775 ///
11776 ///      Into:
11777 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11778 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11779 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11780 bool ARMTargetLowering::lowerInterleavedLoad(
11781     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11782     ArrayRef<unsigned> Indices, unsigned Factor) const {
11783   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11784          "Invalid interleave factor");
11785   assert(!Shuffles.empty() && "Empty shufflevector input");
11786   assert(Shuffles.size() == Indices.size() &&
11787          "Unmatched number of shufflevectors and indices");
11788
11789   VectorType *VecTy = Shuffles[0]->getType();
11790   Type *EltTy = VecTy->getVectorElementType();
11791
11792   const DataLayout &DL = LI->getModule()->getDataLayout();
11793   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11794   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11795
11796   // Skip if we do not have NEON and skip illegal vector types and vector types
11797   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
11798   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
11799     return false;
11800
11801   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11802   // load integer vectors first and then convert to pointer vectors.
11803   if (EltTy->isPointerTy())
11804     VecTy =
11805         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11806
11807   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11808                                             Intrinsic::arm_neon_vld3,
11809                                             Intrinsic::arm_neon_vld4};
11810
11811   IRBuilder<> Builder(LI);
11812   SmallVector<Value *, 2> Ops;
11813
11814   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11815   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11816   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11817
11818   Type *Tys[] = { VecTy, Int8Ptr };
11819   Function *VldnFunc =
11820       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11821   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11822
11823   // Replace uses of each shufflevector with the corresponding vector loaded
11824   // by ldN.
11825   for (unsigned i = 0; i < Shuffles.size(); i++) {
11826     ShuffleVectorInst *SV = Shuffles[i];
11827     unsigned Index = Indices[i];
11828
11829     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11830
11831     // Convert the integer vector to pointer vector if the element is pointer.
11832     if (EltTy->isPointerTy())
11833       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11834
11835     SV->replaceAllUsesWith(SubVec);
11836   }
11837
11838   return true;
11839 }
11840
11841 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11842 ///
11843 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11844 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11845                                    unsigned NumElts) {
11846   SmallVector<Constant *, 16> Mask;
11847   for (unsigned i = 0; i < NumElts; i++)
11848     Mask.push_back(Builder.getInt32(Start + i));
11849
11850   return ConstantVector::get(Mask);
11851 }
11852
11853 /// \brief Lower an interleaved store into a vstN intrinsic.
11854 ///
11855 /// E.g. Lower an interleaved store (Factor = 3):
11856 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11857 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11858 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11859 ///
11860 ///      Into:
11861 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11862 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11863 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11864 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11865 ///
11866 /// Note that the new shufflevectors will be removed and we'll only generate one
11867 /// vst3 instruction in CodeGen.
11868 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11869                                               ShuffleVectorInst *SVI,
11870                                               unsigned Factor) const {
11871   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11872          "Invalid interleave factor");
11873
11874   VectorType *VecTy = SVI->getType();
11875   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11876          "Invalid interleaved store");
11877
11878   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11879   Type *EltTy = VecTy->getVectorElementType();
11880   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11881
11882   const DataLayout &DL = SI->getModule()->getDataLayout();
11883   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11884   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11885
11886   // Skip if we do not have NEON and skip illegal vector types and vector types
11887   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
11888   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
11889       EltIs64Bits)
11890     return false;
11891
11892   Value *Op0 = SVI->getOperand(0);
11893   Value *Op1 = SVI->getOperand(1);
11894   IRBuilder<> Builder(SI);
11895
11896   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11897   // vectors to integer vectors.
11898   if (EltTy->isPointerTy()) {
11899     Type *IntTy = DL.getIntPtrType(EltTy);
11900
11901     // Convert to the corresponding integer vector.
11902     Type *IntVecTy =
11903         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11904     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11905     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11906
11907     SubVecTy = VectorType::get(IntTy, NumSubElts);
11908   }
11909
11910   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11911                                              Intrinsic::arm_neon_vst3,
11912                                              Intrinsic::arm_neon_vst4};
11913   SmallVector<Value *, 6> Ops;
11914
11915   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11916   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11917
11918   Type *Tys[] = { Int8Ptr, SubVecTy };
11919   Function *VstNFunc = Intrinsic::getDeclaration(
11920       SI->getModule(), StoreInts[Factor - 2], Tys);
11921
11922   // Split the shufflevector operands into sub vectors for the new vstN call.
11923   for (unsigned i = 0; i < Factor; i++)
11924     Ops.push_back(Builder.CreateShuffleVector(
11925         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11926
11927   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11928   Builder.CreateCall(VstNFunc, Ops);
11929   return true;
11930 }
11931
11932 enum HABaseType {
11933   HA_UNKNOWN = 0,
11934   HA_FLOAT,
11935   HA_DOUBLE,
11936   HA_VECT64,
11937   HA_VECT128
11938 };
11939
11940 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11941                                    uint64_t &Members) {
11942   if (auto *ST = dyn_cast<StructType>(Ty)) {
11943     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11944       uint64_t SubMembers = 0;
11945       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11946         return false;
11947       Members += SubMembers;
11948     }
11949   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11950     uint64_t SubMembers = 0;
11951     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11952       return false;
11953     Members += SubMembers * AT->getNumElements();
11954   } else if (Ty->isFloatTy()) {
11955     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11956       return false;
11957     Members = 1;
11958     Base = HA_FLOAT;
11959   } else if (Ty->isDoubleTy()) {
11960     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11961       return false;
11962     Members = 1;
11963     Base = HA_DOUBLE;
11964   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11965     Members = 1;
11966     switch (Base) {
11967     case HA_FLOAT:
11968     case HA_DOUBLE:
11969       return false;
11970     case HA_VECT64:
11971       return VT->getBitWidth() == 64;
11972     case HA_VECT128:
11973       return VT->getBitWidth() == 128;
11974     case HA_UNKNOWN:
11975       switch (VT->getBitWidth()) {
11976       case 64:
11977         Base = HA_VECT64;
11978         return true;
11979       case 128:
11980         Base = HA_VECT128;
11981         return true;
11982       default:
11983         return false;
11984       }
11985     }
11986   }
11987
11988   return (Members > 0 && Members <= 4);
11989 }
11990
11991 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11992 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11993 /// passing according to AAPCS rules.
11994 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11995     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11996   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11997       CallingConv::ARM_AAPCS_VFP)
11998     return false;
11999
12000   HABaseType Base = HA_UNKNOWN;
12001   uint64_t Members = 0;
12002   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12003   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12004
12005   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12006   return IsHA || IsIntArray;
12007 }