[ARM] Do not use vtrn for vectorshuffle if the order is reversed
[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       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   // The half <-> float conversion functions are always soft-float, but are
392   // needed for some targets which use a hard-float calling convention by
393   // default.
394   if (Subtarget->isAAPCS_ABI()) {
395     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
398   } else {
399     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
402   }
403
404   if (Subtarget->isThumb1Only())
405     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
406   else
407     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
409       !Subtarget->isThumb1Only()) {
410     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
412   }
413
414   for (MVT VT : MVT::vector_valuetypes()) {
415     for (MVT InnerVT : MVT::vector_valuetypes()) {
416       setTruncStoreAction(VT, InnerVT, Expand);
417       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
418       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
419       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
420     }
421
422     setOperationAction(ISD::MULHS, VT, Expand);
423     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
424     setOperationAction(ISD::MULHU, VT, Expand);
425     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
426
427     setOperationAction(ISD::BSWAP, VT, Expand);
428   }
429
430   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
431   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
432
433   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
434   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON does not have single instruction CTTZ for vectors.
556     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
560
561     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
562     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
563     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
564     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
570
571     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
572     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
573     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
574     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
575
576     // NEON only has FMA instructions as of VFP4.
577     if (!Subtarget->hasVFP4()) {
578       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
579       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
580     }
581
582     setTargetDAGCombine(ISD::INTRINSIC_VOID);
583     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
584     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
585     setTargetDAGCombine(ISD::SHL);
586     setTargetDAGCombine(ISD::SRL);
587     setTargetDAGCombine(ISD::SRA);
588     setTargetDAGCombine(ISD::SIGN_EXTEND);
589     setTargetDAGCombine(ISD::ZERO_EXTEND);
590     setTargetDAGCombine(ISD::ANY_EXTEND);
591     setTargetDAGCombine(ISD::BUILD_VECTOR);
592     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
593     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
594     setTargetDAGCombine(ISD::STORE);
595     setTargetDAGCombine(ISD::FP_TO_SINT);
596     setTargetDAGCombine(ISD::FP_TO_UINT);
597     setTargetDAGCombine(ISD::FDIV);
598     setTargetDAGCombine(ISD::LOAD);
599
600     // It is legal to extload from v4i8 to v4i16 or v4i32.
601     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
602                    MVT::v2i32}) {
603       for (MVT VT : MVT::integer_vector_valuetypes()) {
604         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
605         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
606         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
607       }
608     }
609   }
610
611   // ARM and Thumb2 support UMLAL/SMLAL.
612   if (!Subtarget->isThumb1Only())
613     setTargetDAGCombine(ISD::ADDC);
614
615   if (Subtarget->isFPOnlySP()) {
616     // When targeting a floating-point unit with only single-precision
617     // operations, f64 is legal for the few double-precision instructions which
618     // are present However, no double-precision operations other than moves,
619     // loads and stores are provided by the hardware.
620     setOperationAction(ISD::FADD,       MVT::f64, Expand);
621     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
622     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
623     setOperationAction(ISD::FMA,        MVT::f64, Expand);
624     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
625     setOperationAction(ISD::FREM,       MVT::f64, Expand);
626     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
627     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
628     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
629     setOperationAction(ISD::FABS,       MVT::f64, Expand);
630     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
631     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
632     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
633     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
634     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
635     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
636     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
637     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
638     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
639     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
640     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
641     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
642     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
643     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
644     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
645     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
646     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
647     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
648     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
649     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
650     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
651     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
652     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
653   }
654
655   computeRegisterProperties(Subtarget->getRegisterInfo());
656
657   // ARM does not have floating-point extending loads.
658   for (MVT VT : MVT::fp_valuetypes()) {
659     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
660     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
661   }
662
663   // ... or truncating stores
664   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
665   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
666   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
667
668   // ARM does not have i1 sign extending load.
669   for (MVT VT : MVT::integer_valuetypes())
670     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
671
672   // ARM supports all 4 flavors of integer indexed load / store.
673   if (!Subtarget->isThumb1Only()) {
674     for (unsigned im = (unsigned)ISD::PRE_INC;
675          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
676       setIndexedLoadAction(im,  MVT::i1,  Legal);
677       setIndexedLoadAction(im,  MVT::i8,  Legal);
678       setIndexedLoadAction(im,  MVT::i16, Legal);
679       setIndexedLoadAction(im,  MVT::i32, Legal);
680       setIndexedStoreAction(im, MVT::i1,  Legal);
681       setIndexedStoreAction(im, MVT::i8,  Legal);
682       setIndexedStoreAction(im, MVT::i16, Legal);
683       setIndexedStoreAction(im, MVT::i32, Legal);
684     }
685   }
686
687   setOperationAction(ISD::SADDO, MVT::i32, Custom);
688   setOperationAction(ISD::UADDO, MVT::i32, Custom);
689   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
690   setOperationAction(ISD::USUBO, MVT::i32, Custom);
691
692   // i64 operation support.
693   setOperationAction(ISD::MUL,     MVT::i64, Expand);
694   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
695   if (Subtarget->isThumb1Only()) {
696     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
697     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
698   }
699   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
700       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
701     setOperationAction(ISD::MULHS, MVT::i32, Expand);
702
703   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
704   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
705   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
706   setOperationAction(ISD::SRL,       MVT::i64, Custom);
707   setOperationAction(ISD::SRA,       MVT::i64, Custom);
708
709   if (!Subtarget->isThumb1Only()) {
710     // FIXME: We should do this for Thumb1 as well.
711     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
712     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
713     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
714     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
715   }
716
717   // ARM does not have ROTL.
718   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
719   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
720   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
721   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
722     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
723
724   // These just redirect to CTTZ and CTLZ on ARM.
725   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
726   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
727
728   // @llvm.readcyclecounter requires the Performance Monitors extension.
729   // Default to the 0 expansion on unsupported platforms.
730   // FIXME: Technically there are older ARM CPUs that have
731   // implementation-specific ways of obtaining this information.
732   if (Subtarget->hasPerfMon())
733     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
734
735   // Only ARMv6 has BSWAP.
736   if (!Subtarget->hasV6Ops())
737     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
738
739   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
740       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
741     // These are expanded into libcalls if the cpu doesn't have HW divider.
742     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
743     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
744   }
745
746   setOperationAction(ISD::SREM,  MVT::i32, Expand);
747   setOperationAction(ISD::UREM,  MVT::i32, Expand);
748   // Register based DivRem for AEABI (RTABI 4.2)
749   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
750     setOperationAction(ISD::SREM, MVT::i64, Custom);
751     setOperationAction(ISD::UREM, MVT::i64, Custom);
752
753     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
754     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
755     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
756     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
757     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
758     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
759     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
760     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
761
762     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
763     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
764     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
765     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
766     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
767     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
768     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
769     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
770
771     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
772     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
773   } else {
774     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
775     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
776   }
777
778   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
779   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
780   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
781   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
782   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
783
784   setOperationAction(ISD::TRAP, MVT::Other, Legal);
785
786   // Use the default implementation.
787   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
788   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
789   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
790   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
791   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
792   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
793
794   if (!Subtarget->isTargetMachO()) {
795     // Non-MachO platforms may return values in these registers via the
796     // personality function.
797     setExceptionPointerRegister(ARM::R0);
798     setExceptionSelectorRegister(ARM::R1);
799   }
800
801   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
802     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
803   else
804     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
805
806   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
807   // the default expansion. If we are targeting a single threaded system,
808   // then set them all for expand so we can lower them later into their
809   // non-atomic form.
810   if (TM.Options.ThreadModel == ThreadModel::Single)
811     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
812   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
813     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
814     // to ldrex/strex loops already.
815     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
816
817     // On v8, we have particularly efficient implementations of atomic fences
818     // if they can be combined with nearby atomic loads and stores.
819     if (!Subtarget->hasV8Ops()) {
820       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
821       setInsertFencesForAtomic(true);
822     }
823   } else {
824     // If there's anything we can use as a barrier, go through custom lowering
825     // for ATOMIC_FENCE.
826     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
827                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
828
829     // Set them all for expansion, which will force libcalls.
830     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
831     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
832     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
833     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
834     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
835     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
836     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
837     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
838     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
839     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
840     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
841     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
842     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
843     // Unordered/Monotonic case.
844     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
845     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
846   }
847
848   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
849
850   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
851   if (!Subtarget->hasV6Ops()) {
852     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
853     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
854   }
855   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
856
857   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
858       !Subtarget->isThumb1Only()) {
859     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
860     // iff target supports vfp2.
861     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
862     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
863   }
864
865   // We want to custom lower some of our intrinsics.
866   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
867   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
868   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
869   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
870   if (Subtarget->isTargetDarwin())
871     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
872
873   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
874   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
875   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
876   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
877   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
878   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
879   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
880   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
881   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
882
883   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
884   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
885   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
886   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
887   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
888
889   // We don't support sin/cos/fmod/copysign/pow
890   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
891   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
892   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
893   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
894   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
895   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
896   setOperationAction(ISD::FREM,      MVT::f64, Expand);
897   setOperationAction(ISD::FREM,      MVT::f32, Expand);
898   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
899       !Subtarget->isThumb1Only()) {
900     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
901     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
902   }
903   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
904   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
905
906   if (!Subtarget->hasVFP4()) {
907     setOperationAction(ISD::FMA, MVT::f64, Expand);
908     setOperationAction(ISD::FMA, MVT::f32, Expand);
909   }
910
911   // Various VFP goodness
912   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
913     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
914     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
915       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
916       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
917     }
918
919     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
920     if (!Subtarget->hasFP16()) {
921       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
922       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
923     }
924   }
925
926   // Combine sin / cos into one node or libcall if possible.
927   if (Subtarget->hasSinCos()) {
928     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
929     setLibcallName(RTLIB::SINCOS_F64, "sincos");
930     if (Subtarget->getTargetTriple().isiOS()) {
931       // For iOS, we don't want to the normal expansion of a libcall to
932       // sincos. We want to issue a libcall to __sincos_stret.
933       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
934       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
935     }
936   }
937
938   // FP-ARMv8 implements a lot of rounding-like FP operations.
939   if (Subtarget->hasFPARMv8()) {
940     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
941     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
942     setOperationAction(ISD::FROUND, MVT::f32, Legal);
943     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
944     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
945     setOperationAction(ISD::FRINT, MVT::f32, Legal);
946     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
947     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
948     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
949     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
950     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
951     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
952
953     if (!Subtarget->isFPOnlySP()) {
954       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
955       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
956       setOperationAction(ISD::FROUND, MVT::f64, Legal);
957       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
958       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
959       setOperationAction(ISD::FRINT, MVT::f64, Legal);
960       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
961       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
962     }
963   }
964
965   if (Subtarget->hasNEON()) {
966     // vmin and vmax aren't available in a scalar form, so we use
967     // a NEON instruction with an undef lane instead.
968     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
969     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
970     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
971     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
972     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
973     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
974   }
975
976   // We have target-specific dag combine patterns for the following nodes:
977   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
978   setTargetDAGCombine(ISD::ADD);
979   setTargetDAGCombine(ISD::SUB);
980   setTargetDAGCombine(ISD::MUL);
981   setTargetDAGCombine(ISD::AND);
982   setTargetDAGCombine(ISD::OR);
983   setTargetDAGCombine(ISD::XOR);
984
985   if (Subtarget->hasV6Ops())
986     setTargetDAGCombine(ISD::SRL);
987
988   setStackPointerRegisterToSaveRestore(ARM::SP);
989
990   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
991       !Subtarget->hasVFP2())
992     setSchedulingPreference(Sched::RegPressure);
993   else
994     setSchedulingPreference(Sched::Hybrid);
995
996   //// temporary - rewrite interface to use type
997   MaxStoresPerMemset = 8;
998   MaxStoresPerMemsetOptSize = 4;
999   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1000   MaxStoresPerMemcpyOptSize = 2;
1001   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1002   MaxStoresPerMemmoveOptSize = 2;
1003
1004   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1005   // are at least 4 bytes aligned.
1006   setMinStackArgumentAlignment(4);
1007
1008   // Prefer likely predicted branches to selects on out-of-order cores.
1009   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1010
1011   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1012 }
1013
1014 bool ARMTargetLowering::useSoftFloat() const {
1015   return Subtarget->useSoftFloat();
1016 }
1017
1018 // FIXME: It might make sense to define the representative register class as the
1019 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1020 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1021 // SPR's representative would be DPR_VFP2. This should work well if register
1022 // pressure tracking were modified such that a register use would increment the
1023 // pressure of the register class's representative and all of it's super
1024 // classes' representatives transitively. We have not implemented this because
1025 // of the difficulty prior to coalescing of modeling operand register classes
1026 // due to the common occurrence of cross class copies and subregister insertions
1027 // and extractions.
1028 std::pair<const TargetRegisterClass *, uint8_t>
1029 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1030                                            MVT VT) const {
1031   const TargetRegisterClass *RRC = nullptr;
1032   uint8_t Cost = 1;
1033   switch (VT.SimpleTy) {
1034   default:
1035     return TargetLowering::findRepresentativeClass(TRI, VT);
1036   // Use DPR as representative register class for all floating point
1037   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1038   // the cost is 1 for both f32 and f64.
1039   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1040   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1041     RRC = &ARM::DPRRegClass;
1042     // When NEON is used for SP, only half of the register file is available
1043     // because operations that define both SP and DP results will be constrained
1044     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1045     // coalescing by double-counting the SP regs. See the FIXME above.
1046     if (Subtarget->useNEONForSinglePrecisionFP())
1047       Cost = 2;
1048     break;
1049   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1050   case MVT::v4f32: case MVT::v2f64:
1051     RRC = &ARM::DPRRegClass;
1052     Cost = 2;
1053     break;
1054   case MVT::v4i64:
1055     RRC = &ARM::DPRRegClass;
1056     Cost = 4;
1057     break;
1058   case MVT::v8i64:
1059     RRC = &ARM::DPRRegClass;
1060     Cost = 8;
1061     break;
1062   }
1063   return std::make_pair(RRC, Cost);
1064 }
1065
1066 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1067   switch ((ARMISD::NodeType)Opcode) {
1068   case ARMISD::FIRST_NUMBER:  break;
1069   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1070   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1071   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1072   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1073   case ARMISD::CALL:          return "ARMISD::CALL";
1074   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1075   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1076   case ARMISD::tCALL:         return "ARMISD::tCALL";
1077   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1078   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1079   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1080   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1081   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1082   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1083   case ARMISD::CMP:           return "ARMISD::CMP";
1084   case ARMISD::CMN:           return "ARMISD::CMN";
1085   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1086   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1087   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1088   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1089   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1090
1091   case ARMISD::CMOV:          return "ARMISD::CMOV";
1092
1093   case ARMISD::RBIT:          return "ARMISD::RBIT";
1094
1095   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1096   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1097   case ARMISD::RRX:           return "ARMISD::RRX";
1098
1099   case ARMISD::ADDC:          return "ARMISD::ADDC";
1100   case ARMISD::ADDE:          return "ARMISD::ADDE";
1101   case ARMISD::SUBC:          return "ARMISD::SUBC";
1102   case ARMISD::SUBE:          return "ARMISD::SUBE";
1103
1104   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1105   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1106
1107   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1108   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1109   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1110
1111   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1112
1113   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1114
1115   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1116
1117   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1118
1119   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1120
1121   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1122
1123   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1124   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1125   case ARMISD::VCGE:          return "ARMISD::VCGE";
1126   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1127   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1128   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1129   case ARMISD::VCGT:          return "ARMISD::VCGT";
1130   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1131   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1132   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1133   case ARMISD::VTST:          return "ARMISD::VTST";
1134
1135   case ARMISD::VSHL:          return "ARMISD::VSHL";
1136   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1137   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1138   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1139   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1140   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1141   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1142   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1143   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1144   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1145   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1146   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1147   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1148   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1149   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1150   case ARMISD::VSLI:          return "ARMISD::VSLI";
1151   case ARMISD::VSRI:          return "ARMISD::VSRI";
1152   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1153   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1154   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1155   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1156   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1157   case ARMISD::VDUP:          return "ARMISD::VDUP";
1158   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1159   case ARMISD::VEXT:          return "ARMISD::VEXT";
1160   case ARMISD::VREV64:        return "ARMISD::VREV64";
1161   case ARMISD::VREV32:        return "ARMISD::VREV32";
1162   case ARMISD::VREV16:        return "ARMISD::VREV16";
1163   case ARMISD::VZIP:          return "ARMISD::VZIP";
1164   case ARMISD::VUZP:          return "ARMISD::VUZP";
1165   case ARMISD::VTRN:          return "ARMISD::VTRN";
1166   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1167   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1168   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1169   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1170   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1171   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1172   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1173   case ARMISD::BFI:           return "ARMISD::BFI";
1174   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1175   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1176   case ARMISD::VBSL:          return "ARMISD::VBSL";
1177   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1178   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1179   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1180   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1181   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1182   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1183   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1184   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1185   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1186   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1187   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1188   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1189   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1190   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1191   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1192   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1193   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1194   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1195   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1196   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1197   }
1198   return nullptr;
1199 }
1200
1201 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1202                                           EVT VT) const {
1203   if (!VT.isVector())
1204     return getPointerTy(DL);
1205   return VT.changeVectorElementTypeToInteger();
1206 }
1207
1208 /// getRegClassFor - Return the register class that should be used for the
1209 /// specified value type.
1210 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1211   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1212   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1213   // load / store 4 to 8 consecutive D registers.
1214   if (Subtarget->hasNEON()) {
1215     if (VT == MVT::v4i64)
1216       return &ARM::QQPRRegClass;
1217     if (VT == MVT::v8i64)
1218       return &ARM::QQQQPRRegClass;
1219   }
1220   return TargetLowering::getRegClassFor(VT);
1221 }
1222
1223 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1224 // source/dest is aligned and the copy size is large enough. We therefore want
1225 // to align such objects passed to memory intrinsics.
1226 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1227                                                unsigned &PrefAlign) const {
1228   if (!isa<MemIntrinsic>(CI))
1229     return false;
1230   MinSize = 8;
1231   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1232   // cycle faster than 4-byte aligned LDM.
1233   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1234   return true;
1235 }
1236
1237 // Create a fast isel object.
1238 FastISel *
1239 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1240                                   const TargetLibraryInfo *libInfo) const {
1241   return ARM::createFastISel(funcInfo, libInfo);
1242 }
1243
1244 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1245   unsigned NumVals = N->getNumValues();
1246   if (!NumVals)
1247     return Sched::RegPressure;
1248
1249   for (unsigned i = 0; i != NumVals; ++i) {
1250     EVT VT = N->getValueType(i);
1251     if (VT == MVT::Glue || VT == MVT::Other)
1252       continue;
1253     if (VT.isFloatingPoint() || VT.isVector())
1254       return Sched::ILP;
1255   }
1256
1257   if (!N->isMachineOpcode())
1258     return Sched::RegPressure;
1259
1260   // Load are scheduled for latency even if there instruction itinerary
1261   // is not available.
1262   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1263   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1264
1265   if (MCID.getNumDefs() == 0)
1266     return Sched::RegPressure;
1267   if (!Itins->isEmpty() &&
1268       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1269     return Sched::ILP;
1270
1271   return Sched::RegPressure;
1272 }
1273
1274 //===----------------------------------------------------------------------===//
1275 // Lowering Code
1276 //===----------------------------------------------------------------------===//
1277
1278 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1279 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1280   switch (CC) {
1281   default: llvm_unreachable("Unknown condition code!");
1282   case ISD::SETNE:  return ARMCC::NE;
1283   case ISD::SETEQ:  return ARMCC::EQ;
1284   case ISD::SETGT:  return ARMCC::GT;
1285   case ISD::SETGE:  return ARMCC::GE;
1286   case ISD::SETLT:  return ARMCC::LT;
1287   case ISD::SETLE:  return ARMCC::LE;
1288   case ISD::SETUGT: return ARMCC::HI;
1289   case ISD::SETUGE: return ARMCC::HS;
1290   case ISD::SETULT: return ARMCC::LO;
1291   case ISD::SETULE: return ARMCC::LS;
1292   }
1293 }
1294
1295 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1296 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1297                         ARMCC::CondCodes &CondCode2) {
1298   CondCode2 = ARMCC::AL;
1299   switch (CC) {
1300   default: llvm_unreachable("Unknown FP condition!");
1301   case ISD::SETEQ:
1302   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1303   case ISD::SETGT:
1304   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1305   case ISD::SETGE:
1306   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1307   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1308   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1309   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1310   case ISD::SETO:   CondCode = ARMCC::VC; break;
1311   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1312   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1313   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1314   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1315   case ISD::SETLT:
1316   case ISD::SETULT: CondCode = ARMCC::LT; break;
1317   case ISD::SETLE:
1318   case ISD::SETULE: CondCode = ARMCC::LE; break;
1319   case ISD::SETNE:
1320   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1321   }
1322 }
1323
1324 //===----------------------------------------------------------------------===//
1325 //                      Calling Convention Implementation
1326 //===----------------------------------------------------------------------===//
1327
1328 #include "ARMGenCallingConv.inc"
1329
1330 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1331 /// account presence of floating point hardware and calling convention
1332 /// limitations, such as support for variadic functions.
1333 CallingConv::ID
1334 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1335                                            bool isVarArg) const {
1336   switch (CC) {
1337   default:
1338     llvm_unreachable("Unsupported calling convention");
1339   case CallingConv::ARM_AAPCS:
1340   case CallingConv::ARM_APCS:
1341   case CallingConv::GHC:
1342     return CC;
1343   case CallingConv::ARM_AAPCS_VFP:
1344     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1345   case CallingConv::C:
1346     if (!Subtarget->isAAPCS_ABI())
1347       return CallingConv::ARM_APCS;
1348     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1349              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1350              !isVarArg)
1351       return CallingConv::ARM_AAPCS_VFP;
1352     else
1353       return CallingConv::ARM_AAPCS;
1354   case CallingConv::Fast:
1355     if (!Subtarget->isAAPCS_ABI()) {
1356       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1357         return CallingConv::Fast;
1358       return CallingConv::ARM_APCS;
1359     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1360       return CallingConv::ARM_AAPCS_VFP;
1361     else
1362       return CallingConv::ARM_AAPCS;
1363   }
1364 }
1365
1366 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1367 /// CallingConvention.
1368 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1369                                                  bool Return,
1370                                                  bool isVarArg) const {
1371   switch (getEffectiveCallingConv(CC, isVarArg)) {
1372   default:
1373     llvm_unreachable("Unsupported calling convention");
1374   case CallingConv::ARM_APCS:
1375     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1376   case CallingConv::ARM_AAPCS:
1377     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1378   case CallingConv::ARM_AAPCS_VFP:
1379     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1380   case CallingConv::Fast:
1381     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1382   case CallingConv::GHC:
1383     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1384   }
1385 }
1386
1387 /// LowerCallResult - Lower the result values of a call into the
1388 /// appropriate copies out of appropriate physical registers.
1389 SDValue
1390 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1391                                    CallingConv::ID CallConv, bool isVarArg,
1392                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1393                                    SDLoc dl, SelectionDAG &DAG,
1394                                    SmallVectorImpl<SDValue> &InVals,
1395                                    bool isThisReturn, SDValue ThisVal) const {
1396
1397   // Assign locations to each value returned by this call.
1398   SmallVector<CCValAssign, 16> RVLocs;
1399   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1400                     *DAG.getContext(), Call);
1401   CCInfo.AnalyzeCallResult(Ins,
1402                            CCAssignFnForNode(CallConv, /* Return*/ true,
1403                                              isVarArg));
1404
1405   // Copy all of the result registers out of their specified physreg.
1406   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1407     CCValAssign VA = RVLocs[i];
1408
1409     // Pass 'this' value directly from the argument to return value, to avoid
1410     // reg unit interference
1411     if (i == 0 && isThisReturn) {
1412       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1413              "unexpected return calling convention register assignment");
1414       InVals.push_back(ThisVal);
1415       continue;
1416     }
1417
1418     SDValue Val;
1419     if (VA.needsCustom()) {
1420       // Handle f64 or half of a v2f64.
1421       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1422                                       InFlag);
1423       Chain = Lo.getValue(1);
1424       InFlag = Lo.getValue(2);
1425       VA = RVLocs[++i]; // skip ahead to next loc
1426       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1427                                       InFlag);
1428       Chain = Hi.getValue(1);
1429       InFlag = Hi.getValue(2);
1430       if (!Subtarget->isLittle())
1431         std::swap (Lo, Hi);
1432       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1433
1434       if (VA.getLocVT() == MVT::v2f64) {
1435         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1436         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1437                           DAG.getConstant(0, dl, MVT::i32));
1438
1439         VA = RVLocs[++i]; // skip ahead to next loc
1440         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1441         Chain = Lo.getValue(1);
1442         InFlag = Lo.getValue(2);
1443         VA = RVLocs[++i]; // skip ahead to next loc
1444         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1445         Chain = Hi.getValue(1);
1446         InFlag = Hi.getValue(2);
1447         if (!Subtarget->isLittle())
1448           std::swap (Lo, Hi);
1449         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1450         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1451                           DAG.getConstant(1, dl, MVT::i32));
1452       }
1453     } else {
1454       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1455                                InFlag);
1456       Chain = Val.getValue(1);
1457       InFlag = Val.getValue(2);
1458     }
1459
1460     switch (VA.getLocInfo()) {
1461     default: llvm_unreachable("Unknown loc info!");
1462     case CCValAssign::Full: break;
1463     case CCValAssign::BCvt:
1464       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1465       break;
1466     }
1467
1468     InVals.push_back(Val);
1469   }
1470
1471   return Chain;
1472 }
1473
1474 /// LowerMemOpCallTo - Store the argument to the stack.
1475 SDValue
1476 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1477                                     SDValue StackPtr, SDValue Arg,
1478                                     SDLoc dl, SelectionDAG &DAG,
1479                                     const CCValAssign &VA,
1480                                     ISD::ArgFlagsTy Flags) const {
1481   unsigned LocMemOffset = VA.getLocMemOffset();
1482   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1483   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1484                        StackPtr, PtrOff);
1485   return DAG.getStore(
1486       Chain, dl, Arg, PtrOff,
1487       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1488       false, false, 0);
1489 }
1490
1491 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1492                                          SDValue Chain, SDValue &Arg,
1493                                          RegsToPassVector &RegsToPass,
1494                                          CCValAssign &VA, CCValAssign &NextVA,
1495                                          SDValue &StackPtr,
1496                                          SmallVectorImpl<SDValue> &MemOpChains,
1497                                          ISD::ArgFlagsTy Flags) const {
1498
1499   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1500                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1501   unsigned id = Subtarget->isLittle() ? 0 : 1;
1502   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1503
1504   if (NextVA.isRegLoc())
1505     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1506   else {
1507     assert(NextVA.isMemLoc());
1508     if (!StackPtr.getNode())
1509       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1510                                     getPointerTy(DAG.getDataLayout()));
1511
1512     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1513                                            dl, DAG, NextVA,
1514                                            Flags));
1515   }
1516 }
1517
1518 /// LowerCall - Lowering a call into a callseq_start <-
1519 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1520 /// nodes.
1521 SDValue
1522 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1523                              SmallVectorImpl<SDValue> &InVals) const {
1524   SelectionDAG &DAG                     = CLI.DAG;
1525   SDLoc &dl                             = CLI.DL;
1526   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1527   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1528   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1529   SDValue Chain                         = CLI.Chain;
1530   SDValue Callee                        = CLI.Callee;
1531   bool &isTailCall                      = CLI.IsTailCall;
1532   CallingConv::ID CallConv              = CLI.CallConv;
1533   bool doesNotRet                       = CLI.DoesNotReturn;
1534   bool isVarArg                         = CLI.IsVarArg;
1535
1536   MachineFunction &MF = DAG.getMachineFunction();
1537   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1538   bool isThisReturn   = false;
1539   bool isSibCall      = false;
1540   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1541
1542   // Disable tail calls if they're not supported.
1543   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1544     isTailCall = false;
1545
1546   if (isTailCall) {
1547     // Check if it's really possible to do a tail call.
1548     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1549                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1550                                                    Outs, OutVals, Ins, DAG);
1551     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1552       report_fatal_error("failed to perform tail call elimination on a call "
1553                          "site marked musttail");
1554     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1555     // detected sibcalls.
1556     if (isTailCall) {
1557       ++NumTailCalls;
1558       isSibCall = true;
1559     }
1560   }
1561
1562   // Analyze operands of the call, assigning locations to each operand.
1563   SmallVector<CCValAssign, 16> ArgLocs;
1564   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1565                     *DAG.getContext(), Call);
1566   CCInfo.AnalyzeCallOperands(Outs,
1567                              CCAssignFnForNode(CallConv, /* Return*/ false,
1568                                                isVarArg));
1569
1570   // Get a count of how many bytes are to be pushed on the stack.
1571   unsigned NumBytes = CCInfo.getNextStackOffset();
1572
1573   // For tail calls, memory operands are available in our caller's stack.
1574   if (isSibCall)
1575     NumBytes = 0;
1576
1577   // Adjust the stack pointer for the new arguments...
1578   // These operations are automatically eliminated by the prolog/epilog pass
1579   if (!isSibCall)
1580     Chain = DAG.getCALLSEQ_START(Chain,
1581                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1582
1583   SDValue StackPtr =
1584       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1585
1586   RegsToPassVector RegsToPass;
1587   SmallVector<SDValue, 8> MemOpChains;
1588
1589   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1590   // of tail call optimization, arguments are handled later.
1591   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1592        i != e;
1593        ++i, ++realArgIdx) {
1594     CCValAssign &VA = ArgLocs[i];
1595     SDValue Arg = OutVals[realArgIdx];
1596     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1597     bool isByVal = Flags.isByVal();
1598
1599     // Promote the value if needed.
1600     switch (VA.getLocInfo()) {
1601     default: llvm_unreachable("Unknown loc info!");
1602     case CCValAssign::Full: break;
1603     case CCValAssign::SExt:
1604       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1605       break;
1606     case CCValAssign::ZExt:
1607       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1608       break;
1609     case CCValAssign::AExt:
1610       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1611       break;
1612     case CCValAssign::BCvt:
1613       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1614       break;
1615     }
1616
1617     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1618     if (VA.needsCustom()) {
1619       if (VA.getLocVT() == MVT::v2f64) {
1620         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1621                                   DAG.getConstant(0, dl, MVT::i32));
1622         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1623                                   DAG.getConstant(1, dl, MVT::i32));
1624
1625         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1626                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1627
1628         VA = ArgLocs[++i]; // skip ahead to next loc
1629         if (VA.isRegLoc()) {
1630           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1631                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1632         } else {
1633           assert(VA.isMemLoc());
1634
1635           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1636                                                  dl, DAG, VA, Flags));
1637         }
1638       } else {
1639         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1640                          StackPtr, MemOpChains, Flags);
1641       }
1642     } else if (VA.isRegLoc()) {
1643       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1644         assert(VA.getLocVT() == MVT::i32 &&
1645                "unexpected calling convention register assignment");
1646         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1647                "unexpected use of 'returned'");
1648         isThisReturn = true;
1649       }
1650       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1651     } else if (isByVal) {
1652       assert(VA.isMemLoc());
1653       unsigned offset = 0;
1654
1655       // True if this byval aggregate will be split between registers
1656       // and memory.
1657       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1658       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1659
1660       if (CurByValIdx < ByValArgsCount) {
1661
1662         unsigned RegBegin, RegEnd;
1663         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1664
1665         EVT PtrVT =
1666             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1667         unsigned int i, j;
1668         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1669           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1670           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1671           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1672                                      MachinePointerInfo(),
1673                                      false, false, false,
1674                                      DAG.InferPtrAlignment(AddArg));
1675           MemOpChains.push_back(Load.getValue(1));
1676           RegsToPass.push_back(std::make_pair(j, Load));
1677         }
1678
1679         // If parameter size outsides register area, "offset" value
1680         // helps us to calculate stack slot for remained part properly.
1681         offset = RegEnd - RegBegin;
1682
1683         CCInfo.nextInRegsParam();
1684       }
1685
1686       if (Flags.getByValSize() > 4*offset) {
1687         auto PtrVT = getPointerTy(DAG.getDataLayout());
1688         unsigned LocMemOffset = VA.getLocMemOffset();
1689         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1690         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1691         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1692         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1693         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1694                                            MVT::i32);
1695         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1696                                             MVT::i32);
1697
1698         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1699         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1700         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1701                                           Ops));
1702       }
1703     } else if (!isSibCall) {
1704       assert(VA.isMemLoc());
1705
1706       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1707                                              dl, DAG, VA, Flags));
1708     }
1709   }
1710
1711   if (!MemOpChains.empty())
1712     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1713
1714   // Build a sequence of copy-to-reg nodes chained together with token chain
1715   // and flag operands which copy the outgoing args into the appropriate regs.
1716   SDValue InFlag;
1717   // Tail call byval lowering might overwrite argument registers so in case of
1718   // tail call optimization the copies to registers are lowered later.
1719   if (!isTailCall)
1720     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1721       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1722                                RegsToPass[i].second, InFlag);
1723       InFlag = Chain.getValue(1);
1724     }
1725
1726   // For tail calls lower the arguments to the 'real' stack slot.
1727   if (isTailCall) {
1728     // Force all the incoming stack arguments to be loaded from the stack
1729     // before any new outgoing arguments are stored to the stack, because the
1730     // outgoing stack slots may alias the incoming argument stack slots, and
1731     // the alias isn't otherwise explicit. This is slightly more conservative
1732     // than necessary, because it means that each store effectively depends
1733     // on every argument instead of just those arguments it would clobber.
1734
1735     // Do not flag preceding copytoreg stuff together with the following stuff.
1736     InFlag = SDValue();
1737     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1738       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1739                                RegsToPass[i].second, InFlag);
1740       InFlag = Chain.getValue(1);
1741     }
1742     InFlag = SDValue();
1743   }
1744
1745   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1746   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1747   // node so that legalize doesn't hack it.
1748   bool isDirect = false;
1749   bool isARMFunc = false;
1750   bool isLocalARMFunc = false;
1751   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1752   auto PtrVt = getPointerTy(DAG.getDataLayout());
1753
1754   if (Subtarget->genLongCalls()) {
1755     assert((Subtarget->isTargetWindows() ||
1756             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1757            "long-calls with non-static relocation model!");
1758     // Handle a global address or an external symbol. If it's not one of
1759     // those, the target's already in a register, so we don't need to do
1760     // anything extra.
1761     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1762       const GlobalValue *GV = G->getGlobal();
1763       // Create a constant pool entry for the callee address
1764       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765       ARMConstantPoolValue *CPV =
1766         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1767
1768       // Get the address of the callee into a register
1769       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1770       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1771       Callee = DAG.getLoad(
1772           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1773           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1774           false, false, 0);
1775     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1776       const char *Sym = S->getSymbol();
1777
1778       // Create a constant pool entry for the callee address
1779       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1780       ARMConstantPoolValue *CPV =
1781         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1782                                       ARMPCLabelIndex, 0);
1783       // Get the address of the callee into a register
1784       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1785       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1786       Callee = DAG.getLoad(
1787           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1788           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1789           false, false, 0);
1790     }
1791   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1792     const GlobalValue *GV = G->getGlobal();
1793     isDirect = true;
1794     bool isDef = GV->isStrongDefinitionForLinker();
1795     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1796                    getTargetMachine().getRelocationModel() != Reloc::Static;
1797     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1798     // ARM call to a local ARM function is predicable.
1799     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1800     // tBX takes a register source operand.
1801     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1802       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1803       Callee = DAG.getNode(
1804           ARMISD::WrapperPIC, dl, PtrVt,
1805           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1806       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1807                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1808                            false, false, true, 0);
1809     } else if (Subtarget->isTargetCOFF()) {
1810       assert(Subtarget->isTargetWindows() &&
1811              "Windows is the only supported COFF target");
1812       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1813                                  ? ARMII::MO_DLLIMPORT
1814                                  : ARMII::MO_NO_FLAG;
1815       Callee =
1816           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1817       if (GV->hasDLLImportStorageClass())
1818         Callee =
1819             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1820                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1821                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1822                         false, false, false, 0);
1823     } else {
1824       // On ELF targets for PIC code, direct calls should go through the PLT
1825       unsigned OpFlags = 0;
1826       if (Subtarget->isTargetELF() &&
1827           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1828         OpFlags = ARMII::MO_PLT;
1829       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1830     }
1831   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1832     isDirect = true;
1833     bool isStub = Subtarget->isTargetMachO() &&
1834                   getTargetMachine().getRelocationModel() != Reloc::Static;
1835     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1836     // tBX takes a register source operand.
1837     const char *Sym = S->getSymbol();
1838     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1839       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1840       ARMConstantPoolValue *CPV =
1841         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1842                                       ARMPCLabelIndex, 4);
1843       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1844       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1845       Callee = DAG.getLoad(
1846           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1847           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1848           false, false, 0);
1849       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1850       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1851     } else {
1852       unsigned OpFlags = 0;
1853       // On ELF targets for PIC code, direct calls should go through the PLT
1854       if (Subtarget->isTargetELF() &&
1855                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1856         OpFlags = ARMII::MO_PLT;
1857       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1858     }
1859   }
1860
1861   // FIXME: handle tail calls differently.
1862   unsigned CallOpc;
1863   if (Subtarget->isThumb()) {
1864     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1865       CallOpc = ARMISD::CALL_NOLINK;
1866     else
1867       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1868   } else {
1869     if (!isDirect && !Subtarget->hasV5TOps())
1870       CallOpc = ARMISD::CALL_NOLINK;
1871     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1872              // Emit regular call when code size is the priority
1873              !MF.getFunction()->optForMinSize())
1874       // "mov lr, pc; b _foo" to avoid confusing the RSP
1875       CallOpc = ARMISD::CALL_NOLINK;
1876     else
1877       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1878   }
1879
1880   std::vector<SDValue> Ops;
1881   Ops.push_back(Chain);
1882   Ops.push_back(Callee);
1883
1884   // Add argument registers to the end of the list so that they are known live
1885   // into the call.
1886   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1887     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1888                                   RegsToPass[i].second.getValueType()));
1889
1890   // Add a register mask operand representing the call-preserved registers.
1891   if (!isTailCall) {
1892     const uint32_t *Mask;
1893     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1894     if (isThisReturn) {
1895       // For 'this' returns, use the R0-preserving mask if applicable
1896       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1897       if (!Mask) {
1898         // Set isThisReturn to false if the calling convention is not one that
1899         // allows 'returned' to be modeled in this way, so LowerCallResult does
1900         // not try to pass 'this' straight through
1901         isThisReturn = false;
1902         Mask = ARI->getCallPreservedMask(MF, CallConv);
1903       }
1904     } else
1905       Mask = ARI->getCallPreservedMask(MF, CallConv);
1906
1907     assert(Mask && "Missing call preserved mask for calling convention");
1908     Ops.push_back(DAG.getRegisterMask(Mask));
1909   }
1910
1911   if (InFlag.getNode())
1912     Ops.push_back(InFlag);
1913
1914   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1915   if (isTailCall) {
1916     MF.getFrameInfo()->setHasTailCall();
1917     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1918   }
1919
1920   // Returns a chain and a flag for retval copy to use.
1921   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1922   InFlag = Chain.getValue(1);
1923
1924   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1925                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1926   if (!Ins.empty())
1927     InFlag = Chain.getValue(1);
1928
1929   // Handle result values, copying them out of physregs into vregs that we
1930   // return.
1931   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1932                          InVals, isThisReturn,
1933                          isThisReturn ? OutVals[0] : SDValue());
1934 }
1935
1936 /// HandleByVal - Every parameter *after* a byval parameter is passed
1937 /// on the stack.  Remember the next parameter register to allocate,
1938 /// and then confiscate the rest of the parameter registers to insure
1939 /// this.
1940 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1941                                     unsigned Align) const {
1942   assert((State->getCallOrPrologue() == Prologue ||
1943           State->getCallOrPrologue() == Call) &&
1944          "unhandled ParmContext");
1945
1946   // Byval (as with any stack) slots are always at least 4 byte aligned.
1947   Align = std::max(Align, 4U);
1948
1949   unsigned Reg = State->AllocateReg(GPRArgRegs);
1950   if (!Reg)
1951     return;
1952
1953   unsigned AlignInRegs = Align / 4;
1954   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1955   for (unsigned i = 0; i < Waste; ++i)
1956     Reg = State->AllocateReg(GPRArgRegs);
1957
1958   if (!Reg)
1959     return;
1960
1961   unsigned Excess = 4 * (ARM::R4 - Reg);
1962
1963   // Special case when NSAA != SP and parameter size greater than size of
1964   // all remained GPR regs. In that case we can't split parameter, we must
1965   // send it to stack. We also must set NCRN to R4, so waste all
1966   // remained registers.
1967   const unsigned NSAAOffset = State->getNextStackOffset();
1968   if (NSAAOffset != 0 && Size > Excess) {
1969     while (State->AllocateReg(GPRArgRegs))
1970       ;
1971     return;
1972   }
1973
1974   // First register for byval parameter is the first register that wasn't
1975   // allocated before this method call, so it would be "reg".
1976   // If parameter is small enough to be saved in range [reg, r4), then
1977   // the end (first after last) register would be reg + param-size-in-regs,
1978   // else parameter would be splitted between registers and stack,
1979   // end register would be r4 in this case.
1980   unsigned ByValRegBegin = Reg;
1981   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1982   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1983   // Note, first register is allocated in the beginning of function already,
1984   // allocate remained amount of registers we need.
1985   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1986     State->AllocateReg(GPRArgRegs);
1987   // A byval parameter that is split between registers and memory needs its
1988   // size truncated here.
1989   // In the case where the entire structure fits in registers, we set the
1990   // size in memory to zero.
1991   Size = std::max<int>(Size - Excess, 0);
1992 }
1993
1994 /// MatchingStackOffset - Return true if the given stack call argument is
1995 /// already available in the same position (relatively) of the caller's
1996 /// incoming argument stack.
1997 static
1998 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1999                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2000                          const TargetInstrInfo *TII) {
2001   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2002   int FI = INT_MAX;
2003   if (Arg.getOpcode() == ISD::CopyFromReg) {
2004     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2005     if (!TargetRegisterInfo::isVirtualRegister(VR))
2006       return false;
2007     MachineInstr *Def = MRI->getVRegDef(VR);
2008     if (!Def)
2009       return false;
2010     if (!Flags.isByVal()) {
2011       if (!TII->isLoadFromStackSlot(Def, FI))
2012         return false;
2013     } else {
2014       return false;
2015     }
2016   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2017     if (Flags.isByVal())
2018       // ByVal argument is passed in as a pointer but it's now being
2019       // dereferenced. e.g.
2020       // define @foo(%struct.X* %A) {
2021       //   tail call @bar(%struct.X* byval %A)
2022       // }
2023       return false;
2024     SDValue Ptr = Ld->getBasePtr();
2025     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2026     if (!FINode)
2027       return false;
2028     FI = FINode->getIndex();
2029   } else
2030     return false;
2031
2032   assert(FI != INT_MAX);
2033   if (!MFI->isFixedObjectIndex(FI))
2034     return false;
2035   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2036 }
2037
2038 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2039 /// for tail call optimization. Targets which want to do tail call
2040 /// optimization should implement this function.
2041 bool
2042 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2043                                                      CallingConv::ID CalleeCC,
2044                                                      bool isVarArg,
2045                                                      bool isCalleeStructRet,
2046                                                      bool isCallerStructRet,
2047                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2048                                     const SmallVectorImpl<SDValue> &OutVals,
2049                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2050                                                      SelectionDAG& DAG) const {
2051   const Function *CallerF = DAG.getMachineFunction().getFunction();
2052   CallingConv::ID CallerCC = CallerF->getCallingConv();
2053   bool CCMatch = CallerCC == CalleeCC;
2054
2055   // Look for obvious safe cases to perform tail call optimization that do not
2056   // require ABI changes. This is what gcc calls sibcall.
2057
2058   // Do not sibcall optimize vararg calls unless the call site is not passing
2059   // any arguments.
2060   if (isVarArg && !Outs.empty())
2061     return false;
2062
2063   // Exception-handling functions need a special set of instructions to indicate
2064   // a return to the hardware. Tail-calling another function would probably
2065   // break this.
2066   if (CallerF->hasFnAttribute("interrupt"))
2067     return false;
2068
2069   // Also avoid sibcall optimization if either caller or callee uses struct
2070   // return semantics.
2071   if (isCalleeStructRet || isCallerStructRet)
2072     return false;
2073
2074   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2075   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2076   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2077   // support in the assembler and linker to be used. This would need to be
2078   // fixed to fully support tail calls in Thumb1.
2079   //
2080   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2081   // LR.  This means if we need to reload LR, it takes an extra instructions,
2082   // which outweighs the value of the tail call; but here we don't know yet
2083   // whether LR is going to be used.  Probably the right approach is to
2084   // generate the tail call here and turn it back into CALL/RET in
2085   // emitEpilogue if LR is used.
2086
2087   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2088   // but we need to make sure there are enough registers; the only valid
2089   // registers are the 4 used for parameters.  We don't currently do this
2090   // case.
2091   if (Subtarget->isThumb1Only())
2092     return false;
2093
2094   // Externally-defined functions with weak linkage should not be
2095   // tail-called on ARM when the OS does not support dynamic
2096   // pre-emption of symbols, as the AAELF spec requires normal calls
2097   // to undefined weak functions to be replaced with a NOP or jump to the
2098   // next instruction. The behaviour of branch instructions in this
2099   // situation (as used for tail calls) is implementation-defined, so we
2100   // cannot rely on the linker replacing the tail call with a return.
2101   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2102     const GlobalValue *GV = G->getGlobal();
2103     const Triple &TT = getTargetMachine().getTargetTriple();
2104     if (GV->hasExternalWeakLinkage() &&
2105         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2106       return false;
2107   }
2108
2109   // If the calling conventions do not match, then we'd better make sure the
2110   // results are returned in the same way as what the caller expects.
2111   if (!CCMatch) {
2112     SmallVector<CCValAssign, 16> RVLocs1;
2113     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2114                        *DAG.getContext(), Call);
2115     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2116
2117     SmallVector<CCValAssign, 16> RVLocs2;
2118     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2119                        *DAG.getContext(), Call);
2120     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2121
2122     if (RVLocs1.size() != RVLocs2.size())
2123       return false;
2124     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2125       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2126         return false;
2127       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2128         return false;
2129       if (RVLocs1[i].isRegLoc()) {
2130         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2131           return false;
2132       } else {
2133         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2134           return false;
2135       }
2136     }
2137   }
2138
2139   // If Caller's vararg or byval argument has been split between registers and
2140   // stack, do not perform tail call, since part of the argument is in caller's
2141   // local frame.
2142   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2143                                       getInfo<ARMFunctionInfo>();
2144   if (AFI_Caller->getArgRegsSaveSize())
2145     return false;
2146
2147   // If the callee takes no arguments then go on to check the results of the
2148   // call.
2149   if (!Outs.empty()) {
2150     // Check if stack adjustment is needed. For now, do not do this if any
2151     // argument is passed on the stack.
2152     SmallVector<CCValAssign, 16> ArgLocs;
2153     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2154                       *DAG.getContext(), Call);
2155     CCInfo.AnalyzeCallOperands(Outs,
2156                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2157     if (CCInfo.getNextStackOffset()) {
2158       MachineFunction &MF = DAG.getMachineFunction();
2159
2160       // Check if the arguments are already laid out in the right way as
2161       // the caller's fixed stack objects.
2162       MachineFrameInfo *MFI = MF.getFrameInfo();
2163       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2164       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2165       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2166            i != e;
2167            ++i, ++realArgIdx) {
2168         CCValAssign &VA = ArgLocs[i];
2169         EVT RegVT = VA.getLocVT();
2170         SDValue Arg = OutVals[realArgIdx];
2171         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2172         if (VA.getLocInfo() == CCValAssign::Indirect)
2173           return false;
2174         if (VA.needsCustom()) {
2175           // f64 and vector types are split into multiple registers or
2176           // register/stack-slot combinations.  The types will not match
2177           // the registers; give up on memory f64 refs until we figure
2178           // out what to do about this.
2179           if (!VA.isRegLoc())
2180             return false;
2181           if (!ArgLocs[++i].isRegLoc())
2182             return false;
2183           if (RegVT == MVT::v2f64) {
2184             if (!ArgLocs[++i].isRegLoc())
2185               return false;
2186             if (!ArgLocs[++i].isRegLoc())
2187               return false;
2188           }
2189         } else if (!VA.isRegLoc()) {
2190           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2191                                    MFI, MRI, TII))
2192             return false;
2193         }
2194       }
2195     }
2196   }
2197
2198   return true;
2199 }
2200
2201 bool
2202 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2203                                   MachineFunction &MF, bool isVarArg,
2204                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2205                                   LLVMContext &Context) const {
2206   SmallVector<CCValAssign, 16> RVLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2208   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2209                                                     isVarArg));
2210 }
2211
2212 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2213                                     SDLoc DL, SelectionDAG &DAG) {
2214   const MachineFunction &MF = DAG.getMachineFunction();
2215   const Function *F = MF.getFunction();
2216
2217   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2218
2219   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2220   // version of the "preferred return address". These offsets affect the return
2221   // instruction if this is a return from PL1 without hypervisor extensions.
2222   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2223   //    SWI:     0      "subs pc, lr, #0"
2224   //    ABORT:   +4     "subs pc, lr, #4"
2225   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2226   // UNDEF varies depending on where the exception came from ARM or Thumb
2227   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2228
2229   int64_t LROffset;
2230   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2231       IntKind == "ABORT")
2232     LROffset = 4;
2233   else if (IntKind == "SWI" || IntKind == "UNDEF")
2234     LROffset = 0;
2235   else
2236     report_fatal_error("Unsupported interrupt attribute. If present, value "
2237                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2238
2239   RetOps.insert(RetOps.begin() + 1,
2240                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2241
2242   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2243 }
2244
2245 SDValue
2246 ARMTargetLowering::LowerReturn(SDValue Chain,
2247                                CallingConv::ID CallConv, bool isVarArg,
2248                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2249                                const SmallVectorImpl<SDValue> &OutVals,
2250                                SDLoc dl, SelectionDAG &DAG) const {
2251
2252   // CCValAssign - represent the assignment of the return value to a location.
2253   SmallVector<CCValAssign, 16> RVLocs;
2254
2255   // CCState - Info about the registers and stack slots.
2256   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2257                     *DAG.getContext(), Call);
2258
2259   // Analyze outgoing return values.
2260   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2261                                                isVarArg));
2262
2263   SDValue Flag;
2264   SmallVector<SDValue, 4> RetOps;
2265   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2266   bool isLittleEndian = Subtarget->isLittle();
2267
2268   MachineFunction &MF = DAG.getMachineFunction();
2269   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2270   AFI->setReturnRegsCount(RVLocs.size());
2271
2272   // Copy the result values into the output registers.
2273   for (unsigned i = 0, realRVLocIdx = 0;
2274        i != RVLocs.size();
2275        ++i, ++realRVLocIdx) {
2276     CCValAssign &VA = RVLocs[i];
2277     assert(VA.isRegLoc() && "Can only return in registers!");
2278
2279     SDValue Arg = OutVals[realRVLocIdx];
2280
2281     switch (VA.getLocInfo()) {
2282     default: llvm_unreachable("Unknown loc info!");
2283     case CCValAssign::Full: break;
2284     case CCValAssign::BCvt:
2285       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2286       break;
2287     }
2288
2289     if (VA.needsCustom()) {
2290       if (VA.getLocVT() == MVT::v2f64) {
2291         // Extract the first half and return it in two registers.
2292         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2293                                    DAG.getConstant(0, dl, MVT::i32));
2294         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2295                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2296
2297         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2298                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
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         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2304                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2305                                  Flag);
2306         Flag = Chain.getValue(1);
2307         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2308         VA = RVLocs[++i]; // skip ahead to next loc
2309
2310         // Extract the 2nd half and fall through to handle it as an f64 value.
2311         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2312                           DAG.getConstant(1, dl, MVT::i32));
2313       }
2314       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2315       // available.
2316       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2317                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2318       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2319                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2320                                Flag);
2321       Flag = Chain.getValue(1);
2322       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2323       VA = RVLocs[++i]; // skip ahead to next loc
2324       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2325                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2326                                Flag);
2327     } else
2328       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2329
2330     // Guarantee that all emitted copies are
2331     // stuck together, avoiding something bad.
2332     Flag = Chain.getValue(1);
2333     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2334   }
2335
2336   // Update chain and glue.
2337   RetOps[0] = Chain;
2338   if (Flag.getNode())
2339     RetOps.push_back(Flag);
2340
2341   // CPUs which aren't M-class use a special sequence to return from
2342   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2343   // though we use "subs pc, lr, #N").
2344   //
2345   // M-class CPUs actually use a normal return sequence with a special
2346   // (hardware-provided) value in LR, so the normal code path works.
2347   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2348       !Subtarget->isMClass()) {
2349     if (Subtarget->isThumb1Only())
2350       report_fatal_error("interrupt attribute is not supported in Thumb1");
2351     return LowerInterruptReturn(RetOps, dl, DAG);
2352   }
2353
2354   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2355 }
2356
2357 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2358   if (N->getNumValues() != 1)
2359     return false;
2360   if (!N->hasNUsesOfValue(1, 0))
2361     return false;
2362
2363   SDValue TCChain = Chain;
2364   SDNode *Copy = *N->use_begin();
2365   if (Copy->getOpcode() == ISD::CopyToReg) {
2366     // If the copy has a glue operand, we conservatively assume it isn't safe to
2367     // perform a tail call.
2368     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2369       return false;
2370     TCChain = Copy->getOperand(0);
2371   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2372     SDNode *VMov = Copy;
2373     // f64 returned in a pair of GPRs.
2374     SmallPtrSet<SDNode*, 2> Copies;
2375     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2376          UI != UE; ++UI) {
2377       if (UI->getOpcode() != ISD::CopyToReg)
2378         return false;
2379       Copies.insert(*UI);
2380     }
2381     if (Copies.size() > 2)
2382       return false;
2383
2384     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2385          UI != UE; ++UI) {
2386       SDValue UseChain = UI->getOperand(0);
2387       if (Copies.count(UseChain.getNode()))
2388         // Second CopyToReg
2389         Copy = *UI;
2390       else {
2391         // We are at the top of this chain.
2392         // If the copy has a glue operand, we conservatively assume it
2393         // isn't safe to perform a tail call.
2394         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2395           return false;
2396         // First CopyToReg
2397         TCChain = UseChain;
2398       }
2399     }
2400   } else if (Copy->getOpcode() == ISD::BITCAST) {
2401     // f32 returned in a single GPR.
2402     if (!Copy->hasOneUse())
2403       return false;
2404     Copy = *Copy->use_begin();
2405     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2406       return false;
2407     // If the copy has a glue operand, we conservatively assume it isn't safe to
2408     // perform a tail call.
2409     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2410       return false;
2411     TCChain = Copy->getOperand(0);
2412   } else {
2413     return false;
2414   }
2415
2416   bool HasRet = false;
2417   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2418        UI != UE; ++UI) {
2419     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2420         UI->getOpcode() != ARMISD::INTRET_FLAG)
2421       return false;
2422     HasRet = true;
2423   }
2424
2425   if (!HasRet)
2426     return false;
2427
2428   Chain = TCChain;
2429   return true;
2430 }
2431
2432 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2433   if (!Subtarget->supportsTailCall())
2434     return false;
2435
2436   auto Attr =
2437       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2438   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2439     return false;
2440
2441   return !Subtarget->isThumb1Only();
2442 }
2443
2444 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2445 // and pass the lower and high parts through.
2446 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2447   SDLoc DL(Op);
2448   SDValue WriteValue = Op->getOperand(2);
2449
2450   // This function is only supposed to be called for i64 type argument.
2451   assert(WriteValue.getValueType() == MVT::i64
2452           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2453
2454   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2455                            DAG.getConstant(0, DL, MVT::i32));
2456   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2457                            DAG.getConstant(1, DL, MVT::i32));
2458   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2459   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2460 }
2461
2462 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2463 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2464 // one of the above mentioned nodes. It has to be wrapped because otherwise
2465 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2466 // be used to form addressing mode. These wrapped nodes will be selected
2467 // into MOVi.
2468 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2469   EVT PtrVT = Op.getValueType();
2470   // FIXME there is no actual debug info here
2471   SDLoc dl(Op);
2472   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2473   SDValue Res;
2474   if (CP->isMachineConstantPoolEntry())
2475     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2476                                     CP->getAlignment());
2477   else
2478     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2479                                     CP->getAlignment());
2480   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2481 }
2482
2483 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2484   return MachineJumpTableInfo::EK_Inline;
2485 }
2486
2487 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2488                                              SelectionDAG &DAG) const {
2489   MachineFunction &MF = DAG.getMachineFunction();
2490   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2491   unsigned ARMPCLabelIndex = 0;
2492   SDLoc DL(Op);
2493   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2494   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2495   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2496   SDValue CPAddr;
2497   if (RelocM == Reloc::Static) {
2498     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2499   } else {
2500     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2501     ARMPCLabelIndex = AFI->createPICLabelUId();
2502     ARMConstantPoolValue *CPV =
2503       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2504                                       ARMCP::CPBlockAddress, PCAdj);
2505     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2506   }
2507   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2508   SDValue Result =
2509       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2510                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2511                   false, false, false, 0);
2512   if (RelocM == Reloc::Static)
2513     return Result;
2514   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2515   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2516 }
2517
2518 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2519 SDValue
2520 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2521                                                  SelectionDAG &DAG) const {
2522   SDLoc dl(GA);
2523   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2524   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2525   MachineFunction &MF = DAG.getMachineFunction();
2526   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2527   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2528   ARMConstantPoolValue *CPV =
2529     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2530                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2531   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2532   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2533   Argument =
2534       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2535                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2536                   false, false, false, 0);
2537   SDValue Chain = Argument.getValue(1);
2538
2539   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2540   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2541
2542   // call __tls_get_addr.
2543   ArgListTy Args;
2544   ArgListEntry Entry;
2545   Entry.Node = Argument;
2546   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2547   Args.push_back(Entry);
2548
2549   // FIXME: is there useful debug info available here?
2550   TargetLowering::CallLoweringInfo CLI(DAG);
2551   CLI.setDebugLoc(dl).setChain(Chain)
2552     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2553                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2554                0);
2555
2556   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2557   return CallResult.first;
2558 }
2559
2560 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2561 // "local exec" model.
2562 SDValue
2563 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2564                                         SelectionDAG &DAG,
2565                                         TLSModel::Model model) const {
2566   const GlobalValue *GV = GA->getGlobal();
2567   SDLoc dl(GA);
2568   SDValue Offset;
2569   SDValue Chain = DAG.getEntryNode();
2570   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2571   // Get the Thread Pointer
2572   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2573
2574   if (model == TLSModel::InitialExec) {
2575     MachineFunction &MF = DAG.getMachineFunction();
2576     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2577     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2578     // Initial exec model.
2579     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2580     ARMConstantPoolValue *CPV =
2581       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2582                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2583                                       true);
2584     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2585     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2586     Offset = DAG.getLoad(
2587         PtrVT, dl, Chain, Offset,
2588         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2589         false, false, 0);
2590     Chain = Offset.getValue(1);
2591
2592     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2593     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2594
2595     Offset = DAG.getLoad(
2596         PtrVT, dl, Chain, Offset,
2597         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2598         false, false, 0);
2599   } else {
2600     // local exec model
2601     assert(model == TLSModel::LocalExec);
2602     ARMConstantPoolValue *CPV =
2603       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2604     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2605     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2606     Offset = DAG.getLoad(
2607         PtrVT, dl, Chain, Offset,
2608         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2609         false, false, 0);
2610   }
2611
2612   // The address of the thread local variable is the add of the thread
2613   // pointer with the offset of the variable.
2614   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2615 }
2616
2617 SDValue
2618 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2619   // TODO: implement the "local dynamic" model
2620   assert(Subtarget->isTargetELF() &&
2621          "TLS not implemented for non-ELF targets");
2622   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2623   if (DAG.getTarget().Options.EmulatedTLS)
2624     return LowerToTLSEmulatedModel(GA, DAG);
2625
2626   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2627
2628   switch (model) {
2629     case TLSModel::GeneralDynamic:
2630     case TLSModel::LocalDynamic:
2631       return LowerToTLSGeneralDynamicModel(GA, DAG);
2632     case TLSModel::InitialExec:
2633     case TLSModel::LocalExec:
2634       return LowerToTLSExecModels(GA, DAG, model);
2635   }
2636   llvm_unreachable("bogus TLS model");
2637 }
2638
2639 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2640                                                  SelectionDAG &DAG) const {
2641   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2642   SDLoc dl(Op);
2643   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2644   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2645     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2646     ARMConstantPoolValue *CPV =
2647       ARMConstantPoolConstant::Create(GV,
2648                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2649     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2650     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2651     SDValue Result = DAG.getLoad(
2652         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2653         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2654         false, false, 0);
2655     SDValue Chain = Result.getValue(1);
2656     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2657     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2658     if (!UseGOTOFF)
2659       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2660                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2661                            false, false, false, 0);
2662     return Result;
2663   }
2664
2665   // If we have T2 ops, we can materialize the address directly via movt/movw
2666   // pair. This is always cheaper.
2667   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2668     ++NumMovwMovt;
2669     // FIXME: Once remat is capable of dealing with instructions with register
2670     // operands, expand this into two nodes.
2671     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2672                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2673   } else {
2674     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2675     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2676     return DAG.getLoad(
2677         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2678         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2679         false, false, 0);
2680   }
2681 }
2682
2683 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2684                                                     SelectionDAG &DAG) const {
2685   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2686   SDLoc dl(Op);
2687   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2688   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2689
2690   if (Subtarget->useMovt(DAG.getMachineFunction()))
2691     ++NumMovwMovt;
2692
2693   // FIXME: Once remat is capable of dealing with instructions with register
2694   // operands, expand this into multiple nodes
2695   unsigned Wrapper =
2696       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2697
2698   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2699   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2700
2701   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2702     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2703                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2704                          false, false, false, 0);
2705   return Result;
2706 }
2707
2708 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2709                                                      SelectionDAG &DAG) const {
2710   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2711   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2712          "Windows on ARM expects to use movw/movt");
2713
2714   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2715   const ARMII::TOF TargetFlags =
2716     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2717   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2718   SDValue Result;
2719   SDLoc DL(Op);
2720
2721   ++NumMovwMovt;
2722
2723   // FIXME: Once remat is capable of dealing with instructions with register
2724   // operands, expand this into two nodes.
2725   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2726                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2727                                                   TargetFlags));
2728   if (GV->hasDLLImportStorageClass())
2729     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2730                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2731                          false, false, false, 0);
2732   return Result;
2733 }
2734
2735 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2736                                                     SelectionDAG &DAG) const {
2737   assert(Subtarget->isTargetELF() &&
2738          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2739   MachineFunction &MF = DAG.getMachineFunction();
2740   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2741   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2742   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2743   SDLoc dl(Op);
2744   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2745   ARMConstantPoolValue *CPV =
2746     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2747                                   ARMPCLabelIndex, PCAdj);
2748   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2749   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2750   SDValue Result =
2751       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2752                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2753                   false, false, false, 0);
2754   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2755   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2756 }
2757
2758 SDValue
2759 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2760   SDLoc dl(Op);
2761   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2762   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2763                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2764                      Op.getOperand(1), Val);
2765 }
2766
2767 SDValue
2768 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2769   SDLoc dl(Op);
2770   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2771                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2772 }
2773
2774 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2775                                                       SelectionDAG &DAG) const {
2776   SDLoc dl(Op);
2777   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2778                      Op.getOperand(0));
2779 }
2780
2781 SDValue
2782 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2783                                           const ARMSubtarget *Subtarget) const {
2784   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2785   SDLoc dl(Op);
2786   switch (IntNo) {
2787   default: return SDValue();    // Don't custom lower most intrinsics.
2788   case Intrinsic::arm_rbit: {
2789     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2790            "RBIT intrinsic must have i32 type!");
2791     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2792   }
2793   case Intrinsic::arm_thread_pointer: {
2794     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2795     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2796   }
2797   case Intrinsic::eh_sjlj_lsda: {
2798     MachineFunction &MF = DAG.getMachineFunction();
2799     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2800     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2801     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2802     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2803     SDValue CPAddr;
2804     unsigned PCAdj = (RelocM != Reloc::PIC_)
2805       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2806     ARMConstantPoolValue *CPV =
2807       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2808                                       ARMCP::CPLSDA, PCAdj);
2809     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2810     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2811     SDValue Result = DAG.getLoad(
2812         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2813         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2814         false, false, 0);
2815
2816     if (RelocM == Reloc::PIC_) {
2817       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2818       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2819     }
2820     return Result;
2821   }
2822   case Intrinsic::arm_neon_vmulls:
2823   case Intrinsic::arm_neon_vmullu: {
2824     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2825       ? ARMISD::VMULLs : ARMISD::VMULLu;
2826     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2827                        Op.getOperand(1), Op.getOperand(2));
2828   }
2829   case Intrinsic::arm_neon_vminnm:
2830   case Intrinsic::arm_neon_vmaxnm: {
2831     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2832       ? ISD::FMINNUM : ISD::FMAXNUM;
2833     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2834                        Op.getOperand(1), Op.getOperand(2));
2835   }
2836   case Intrinsic::arm_neon_vminu:
2837   case Intrinsic::arm_neon_vmaxu: {
2838     if (Op.getValueType().isFloatingPoint())
2839       return SDValue();
2840     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2841       ? ISD::UMIN : ISD::UMAX;
2842     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2843                          Op.getOperand(1), Op.getOperand(2));
2844   }
2845   case Intrinsic::arm_neon_vmins:
2846   case Intrinsic::arm_neon_vmaxs: {
2847     // v{min,max}s is overloaded between signed integers and floats.
2848     if (!Op.getValueType().isFloatingPoint()) {
2849       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2850         ? ISD::SMIN : ISD::SMAX;
2851       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2852                          Op.getOperand(1), Op.getOperand(2));
2853     }
2854     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2855       ? ISD::FMINNAN : ISD::FMAXNAN;
2856     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2857                        Op.getOperand(1), Op.getOperand(2));
2858   }
2859   }
2860 }
2861
2862 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2863                                  const ARMSubtarget *Subtarget) {
2864   // FIXME: handle "fence singlethread" more efficiently.
2865   SDLoc dl(Op);
2866   if (!Subtarget->hasDataBarrier()) {
2867     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2868     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2869     // here.
2870     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2871            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2872     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2873                        DAG.getConstant(0, dl, MVT::i32));
2874   }
2875
2876   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2877   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2878   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2879   if (Subtarget->isMClass()) {
2880     // Only a full system barrier exists in the M-class architectures.
2881     Domain = ARM_MB::SY;
2882   } else if (Subtarget->isSwift() && Ord == Release) {
2883     // Swift happens to implement ISHST barriers in a way that's compatible with
2884     // Release semantics but weaker than ISH so we'd be fools not to use
2885     // it. Beware: other processors probably don't!
2886     Domain = ARM_MB::ISHST;
2887   }
2888
2889   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2890                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2891                      DAG.getConstant(Domain, dl, MVT::i32));
2892 }
2893
2894 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2895                              const ARMSubtarget *Subtarget) {
2896   // ARM pre v5TE and Thumb1 does not have preload instructions.
2897   if (!(Subtarget->isThumb2() ||
2898         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2899     // Just preserve the chain.
2900     return Op.getOperand(0);
2901
2902   SDLoc dl(Op);
2903   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2904   if (!isRead &&
2905       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2906     // ARMv7 with MP extension has PLDW.
2907     return Op.getOperand(0);
2908
2909   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2910   if (Subtarget->isThumb()) {
2911     // Invert the bits.
2912     isRead = ~isRead & 1;
2913     isData = ~isData & 1;
2914   }
2915
2916   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2917                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2918                      DAG.getConstant(isData, dl, MVT::i32));
2919 }
2920
2921 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2922   MachineFunction &MF = DAG.getMachineFunction();
2923   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2924
2925   // vastart just stores the address of the VarArgsFrameIndex slot into the
2926   // memory location argument.
2927   SDLoc dl(Op);
2928   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2929   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2930   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2931   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2932                       MachinePointerInfo(SV), false, false, 0);
2933 }
2934
2935 SDValue
2936 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2937                                         SDValue &Root, SelectionDAG &DAG,
2938                                         SDLoc dl) const {
2939   MachineFunction &MF = DAG.getMachineFunction();
2940   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2941
2942   const TargetRegisterClass *RC;
2943   if (AFI->isThumb1OnlyFunction())
2944     RC = &ARM::tGPRRegClass;
2945   else
2946     RC = &ARM::GPRRegClass;
2947
2948   // Transform the arguments stored in physical registers into virtual ones.
2949   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2950   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2951
2952   SDValue ArgValue2;
2953   if (NextVA.isMemLoc()) {
2954     MachineFrameInfo *MFI = MF.getFrameInfo();
2955     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2956
2957     // Create load node to retrieve arguments from the stack.
2958     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2959     ArgValue2 = DAG.getLoad(
2960         MVT::i32, dl, Root, FIN,
2961         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2962         false, false, 0);
2963   } else {
2964     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2965     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2966   }
2967   if (!Subtarget->isLittle())
2968     std::swap (ArgValue, ArgValue2);
2969   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2970 }
2971
2972 // The remaining GPRs hold either the beginning of variable-argument
2973 // data, or the beginning of an aggregate passed by value (usually
2974 // byval).  Either way, we allocate stack slots adjacent to the data
2975 // provided by our caller, and store the unallocated registers there.
2976 // If this is a variadic function, the va_list pointer will begin with
2977 // these values; otherwise, this reassembles a (byval) structure that
2978 // was split between registers and memory.
2979 // Return: The frame index registers were stored into.
2980 int
2981 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2982                                   SDLoc dl, SDValue &Chain,
2983                                   const Value *OrigArg,
2984                                   unsigned InRegsParamRecordIdx,
2985                                   int ArgOffset,
2986                                   unsigned ArgSize) const {
2987   // Currently, two use-cases possible:
2988   // Case #1. Non-var-args function, and we meet first byval parameter.
2989   //          Setup first unallocated register as first byval register;
2990   //          eat all remained registers
2991   //          (these two actions are performed by HandleByVal method).
2992   //          Then, here, we initialize stack frame with
2993   //          "store-reg" instructions.
2994   // Case #2. Var-args function, that doesn't contain byval parameters.
2995   //          The same: eat all remained unallocated registers,
2996   //          initialize stack frame.
2997
2998   MachineFunction &MF = DAG.getMachineFunction();
2999   MachineFrameInfo *MFI = MF.getFrameInfo();
3000   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3001   unsigned RBegin, REnd;
3002   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3003     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3004   } else {
3005     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3006     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3007     REnd = ARM::R4;
3008   }
3009
3010   if (REnd != RBegin)
3011     ArgOffset = -4 * (ARM::R4 - RBegin);
3012
3013   auto PtrVT = getPointerTy(DAG.getDataLayout());
3014   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3015   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3016
3017   SmallVector<SDValue, 4> MemOps;
3018   const TargetRegisterClass *RC =
3019       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3020
3021   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3022     unsigned VReg = MF.addLiveIn(Reg, RC);
3023     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3024     SDValue Store =
3025         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3026                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3027     MemOps.push_back(Store);
3028     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3029   }
3030
3031   if (!MemOps.empty())
3032     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3033   return FrameIndex;
3034 }
3035
3036 // Setup stack frame, the va_list pointer will start from.
3037 void
3038 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3039                                         SDLoc dl, SDValue &Chain,
3040                                         unsigned ArgOffset,
3041                                         unsigned TotalArgRegsSaveSize,
3042                                         bool ForceMutable) const {
3043   MachineFunction &MF = DAG.getMachineFunction();
3044   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3045
3046   // Try to store any remaining integer argument regs
3047   // to their spots on the stack so that they may be loaded by deferencing
3048   // the result of va_next.
3049   // If there is no regs to be stored, just point address after last
3050   // argument passed via stack.
3051   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3052                                   CCInfo.getInRegsParamsCount(),
3053                                   CCInfo.getNextStackOffset(), 4);
3054   AFI->setVarArgsFrameIndex(FrameIndex);
3055 }
3056
3057 SDValue
3058 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3059                                         CallingConv::ID CallConv, bool isVarArg,
3060                                         const SmallVectorImpl<ISD::InputArg>
3061                                           &Ins,
3062                                         SDLoc dl, SelectionDAG &DAG,
3063                                         SmallVectorImpl<SDValue> &InVals)
3064                                           const {
3065   MachineFunction &MF = DAG.getMachineFunction();
3066   MachineFrameInfo *MFI = MF.getFrameInfo();
3067
3068   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3069
3070   // Assign locations to all of the incoming arguments.
3071   SmallVector<CCValAssign, 16> ArgLocs;
3072   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3073                     *DAG.getContext(), Prologue);
3074   CCInfo.AnalyzeFormalArguments(Ins,
3075                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3076                                                   isVarArg));
3077
3078   SmallVector<SDValue, 16> ArgValues;
3079   SDValue ArgValue;
3080   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3081   unsigned CurArgIdx = 0;
3082
3083   // Initially ArgRegsSaveSize is zero.
3084   // Then we increase this value each time we meet byval parameter.
3085   // We also increase this value in case of varargs function.
3086   AFI->setArgRegsSaveSize(0);
3087
3088   // Calculate the amount of stack space that we need to allocate to store
3089   // byval and variadic arguments that are passed in registers.
3090   // We need to know this before we allocate the first byval or variadic
3091   // argument, as they will be allocated a stack slot below the CFA (Canonical
3092   // Frame Address, the stack pointer at entry to the function).
3093   unsigned ArgRegBegin = ARM::R4;
3094   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3095     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3096       break;
3097
3098     CCValAssign &VA = ArgLocs[i];
3099     unsigned Index = VA.getValNo();
3100     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3101     if (!Flags.isByVal())
3102       continue;
3103
3104     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3105     unsigned RBegin, REnd;
3106     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3107     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3108
3109     CCInfo.nextInRegsParam();
3110   }
3111   CCInfo.rewindByValRegsInfo();
3112
3113   int lastInsIndex = -1;
3114   if (isVarArg && MFI->hasVAStart()) {
3115     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3116     if (RegIdx != array_lengthof(GPRArgRegs))
3117       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3118   }
3119
3120   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3121   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3122   auto PtrVT = getPointerTy(DAG.getDataLayout());
3123
3124   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3125     CCValAssign &VA = ArgLocs[i];
3126     if (Ins[VA.getValNo()].isOrigArg()) {
3127       std::advance(CurOrigArg,
3128                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3129       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3130     }
3131     // Arguments stored in registers.
3132     if (VA.isRegLoc()) {
3133       EVT RegVT = VA.getLocVT();
3134
3135       if (VA.needsCustom()) {
3136         // f64 and vector types are split up into multiple registers or
3137         // combinations of registers and stack slots.
3138         if (VA.getLocVT() == MVT::v2f64) {
3139           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3140                                                    Chain, DAG, dl);
3141           VA = ArgLocs[++i]; // skip ahead to next loc
3142           SDValue ArgValue2;
3143           if (VA.isMemLoc()) {
3144             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3145             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3146             ArgValue2 = DAG.getLoad(
3147                 MVT::f64, dl, Chain, FIN,
3148                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3149                 false, false, false, 0);
3150           } else {
3151             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3152                                              Chain, DAG, dl);
3153           }
3154           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3155           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3156                                  ArgValue, ArgValue1,
3157                                  DAG.getIntPtrConstant(0, dl));
3158           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3159                                  ArgValue, ArgValue2,
3160                                  DAG.getIntPtrConstant(1, dl));
3161         } else
3162           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3163
3164       } else {
3165         const TargetRegisterClass *RC;
3166
3167         if (RegVT == MVT::f32)
3168           RC = &ARM::SPRRegClass;
3169         else if (RegVT == MVT::f64)
3170           RC = &ARM::DPRRegClass;
3171         else if (RegVT == MVT::v2f64)
3172           RC = &ARM::QPRRegClass;
3173         else if (RegVT == MVT::i32)
3174           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3175                                            : &ARM::GPRRegClass;
3176         else
3177           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3178
3179         // Transform the arguments in physical registers into virtual ones.
3180         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3181         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3182       }
3183
3184       // If this is an 8 or 16-bit value, it is really passed promoted
3185       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3186       // truncate to the right size.
3187       switch (VA.getLocInfo()) {
3188       default: llvm_unreachable("Unknown loc info!");
3189       case CCValAssign::Full: break;
3190       case CCValAssign::BCvt:
3191         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3192         break;
3193       case CCValAssign::SExt:
3194         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3195                                DAG.getValueType(VA.getValVT()));
3196         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3197         break;
3198       case CCValAssign::ZExt:
3199         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3200                                DAG.getValueType(VA.getValVT()));
3201         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3202         break;
3203       }
3204
3205       InVals.push_back(ArgValue);
3206
3207     } else { // VA.isRegLoc()
3208
3209       // sanity check
3210       assert(VA.isMemLoc());
3211       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3212
3213       int index = VA.getValNo();
3214
3215       // Some Ins[] entries become multiple ArgLoc[] entries.
3216       // Process them only once.
3217       if (index != lastInsIndex)
3218         {
3219           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3220           // FIXME: For now, all byval parameter objects are marked mutable.
3221           // This can be changed with more analysis.
3222           // In case of tail call optimization mark all arguments mutable.
3223           // Since they could be overwritten by lowering of arguments in case of
3224           // a tail call.
3225           if (Flags.isByVal()) {
3226             assert(Ins[index].isOrigArg() &&
3227                    "Byval arguments cannot be implicit");
3228             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3229
3230             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3231                                             CurByValIndex, VA.getLocMemOffset(),
3232                                             Flags.getByValSize());
3233             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3234             CCInfo.nextInRegsParam();
3235           } else {
3236             unsigned FIOffset = VA.getLocMemOffset();
3237             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3238                                             FIOffset, true);
3239
3240             // Create load nodes to retrieve arguments from the stack.
3241             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3242             InVals.push_back(DAG.getLoad(
3243                 VA.getValVT(), dl, Chain, FIN,
3244                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3245                 false, false, false, 0));
3246           }
3247           lastInsIndex = index;
3248         }
3249     }
3250   }
3251
3252   // varargs
3253   if (isVarArg && MFI->hasVAStart())
3254     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3255                          CCInfo.getNextStackOffset(),
3256                          TotalArgRegsSaveSize);
3257
3258   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3259
3260   return Chain;
3261 }
3262
3263 /// isFloatingPointZero - Return true if this is +0.0.
3264 static bool isFloatingPointZero(SDValue Op) {
3265   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3266     return CFP->getValueAPF().isPosZero();
3267   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3268     // Maybe this has already been legalized into the constant pool?
3269     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3270       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3271       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3272         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3273           return CFP->getValueAPF().isPosZero();
3274     }
3275   } else if (Op->getOpcode() == ISD::BITCAST &&
3276              Op->getValueType(0) == MVT::f64) {
3277     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3278     // created by LowerConstantFP().
3279     SDValue BitcastOp = Op->getOperand(0);
3280     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3281       SDValue MoveOp = BitcastOp->getOperand(0);
3282       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3283           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3284         return true;
3285       }
3286     }
3287   }
3288   return false;
3289 }
3290
3291 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3292 /// the given operands.
3293 SDValue
3294 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3295                              SDValue &ARMcc, SelectionDAG &DAG,
3296                              SDLoc dl) const {
3297   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3298     unsigned C = RHSC->getZExtValue();
3299     if (!isLegalICmpImmediate(C)) {
3300       // Constant does not fit, try adjusting it by one?
3301       switch (CC) {
3302       default: break;
3303       case ISD::SETLT:
3304       case ISD::SETGE:
3305         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3306           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3307           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3308         }
3309         break;
3310       case ISD::SETULT:
3311       case ISD::SETUGE:
3312         if (C != 0 && isLegalICmpImmediate(C-1)) {
3313           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3314           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3315         }
3316         break;
3317       case ISD::SETLE:
3318       case ISD::SETGT:
3319         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3320           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3321           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3322         }
3323         break;
3324       case ISD::SETULE:
3325       case ISD::SETUGT:
3326         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3327           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3328           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3329         }
3330         break;
3331       }
3332     }
3333   }
3334
3335   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3336   ARMISD::NodeType CompareType;
3337   switch (CondCode) {
3338   default:
3339     CompareType = ARMISD::CMP;
3340     break;
3341   case ARMCC::EQ:
3342   case ARMCC::NE:
3343     // Uses only Z Flag
3344     CompareType = ARMISD::CMPZ;
3345     break;
3346   }
3347   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3348   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3349 }
3350
3351 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3352 SDValue
3353 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3354                              SDLoc dl) const {
3355   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3356   SDValue Cmp;
3357   if (!isFloatingPointZero(RHS))
3358     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3359   else
3360     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3361   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3362 }
3363
3364 /// duplicateCmp - Glue values can have only one use, so this function
3365 /// duplicates a comparison node.
3366 SDValue
3367 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3368   unsigned Opc = Cmp.getOpcode();
3369   SDLoc DL(Cmp);
3370   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3371     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3372
3373   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3374   Cmp = Cmp.getOperand(0);
3375   Opc = Cmp.getOpcode();
3376   if (Opc == ARMISD::CMPFP)
3377     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3378   else {
3379     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3380     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3381   }
3382   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3383 }
3384
3385 std::pair<SDValue, SDValue>
3386 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3387                                  SDValue &ARMcc) const {
3388   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3389
3390   SDValue Value, OverflowCmp;
3391   SDValue LHS = Op.getOperand(0);
3392   SDValue RHS = Op.getOperand(1);
3393   SDLoc dl(Op);
3394
3395   // FIXME: We are currently always generating CMPs because we don't support
3396   // generating CMN through the backend. This is not as good as the natural
3397   // CMP case because it causes a register dependency and cannot be folded
3398   // later.
3399
3400   switch (Op.getOpcode()) {
3401   default:
3402     llvm_unreachable("Unknown overflow instruction!");
3403   case ISD::SADDO:
3404     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3405     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3406     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3407     break;
3408   case ISD::UADDO:
3409     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3410     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3411     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3412     break;
3413   case ISD::SSUBO:
3414     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3415     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3416     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3417     break;
3418   case ISD::USUBO:
3419     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3420     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3421     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3422     break;
3423   } // switch (...)
3424
3425   return std::make_pair(Value, OverflowCmp);
3426 }
3427
3428
3429 SDValue
3430 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3431   // Let legalize expand this if it isn't a legal type yet.
3432   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3433     return SDValue();
3434
3435   SDValue Value, OverflowCmp;
3436   SDValue ARMcc;
3437   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3438   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3439   SDLoc dl(Op);
3440   // We use 0 and 1 as false and true values.
3441   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3442   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3443   EVT VT = Op.getValueType();
3444
3445   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3446                                  ARMcc, CCR, OverflowCmp);
3447
3448   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3449   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3450 }
3451
3452
3453 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3454   SDValue Cond = Op.getOperand(0);
3455   SDValue SelectTrue = Op.getOperand(1);
3456   SDValue SelectFalse = Op.getOperand(2);
3457   SDLoc dl(Op);
3458   unsigned Opc = Cond.getOpcode();
3459
3460   if (Cond.getResNo() == 1 &&
3461       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3462        Opc == ISD::USUBO)) {
3463     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3464       return SDValue();
3465
3466     SDValue Value, OverflowCmp;
3467     SDValue ARMcc;
3468     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3469     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3470     EVT VT = Op.getValueType();
3471
3472     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3473                    OverflowCmp, DAG);
3474   }
3475
3476   // Convert:
3477   //
3478   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3479   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3480   //
3481   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3482     const ConstantSDNode *CMOVTrue =
3483       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3484     const ConstantSDNode *CMOVFalse =
3485       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3486
3487     if (CMOVTrue && CMOVFalse) {
3488       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3489       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3490
3491       SDValue True;
3492       SDValue False;
3493       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3494         True = SelectTrue;
3495         False = SelectFalse;
3496       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3497         True = SelectFalse;
3498         False = SelectTrue;
3499       }
3500
3501       if (True.getNode() && False.getNode()) {
3502         EVT VT = Op.getValueType();
3503         SDValue ARMcc = Cond.getOperand(2);
3504         SDValue CCR = Cond.getOperand(3);
3505         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3506         assert(True.getValueType() == VT);
3507         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3508       }
3509     }
3510   }
3511
3512   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3513   // undefined bits before doing a full-word comparison with zero.
3514   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3515                      DAG.getConstant(1, dl, Cond.getValueType()));
3516
3517   return DAG.getSelectCC(dl, Cond,
3518                          DAG.getConstant(0, dl, Cond.getValueType()),
3519                          SelectTrue, SelectFalse, ISD::SETNE);
3520 }
3521
3522 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3523                                  bool &swpCmpOps, bool &swpVselOps) {
3524   // Start by selecting the GE condition code for opcodes that return true for
3525   // 'equality'
3526   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3527       CC == ISD::SETULE)
3528     CondCode = ARMCC::GE;
3529
3530   // and GT for opcodes that return false for 'equality'.
3531   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3532            CC == ISD::SETULT)
3533     CondCode = ARMCC::GT;
3534
3535   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3536   // to swap the compare operands.
3537   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3538       CC == ISD::SETULT)
3539     swpCmpOps = true;
3540
3541   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3542   // If we have an unordered opcode, we need to swap the operands to the VSEL
3543   // instruction (effectively negating the condition).
3544   //
3545   // This also has the effect of swapping which one of 'less' or 'greater'
3546   // returns true, so we also swap the compare operands. It also switches
3547   // whether we return true for 'equality', so we compensate by picking the
3548   // opposite condition code to our original choice.
3549   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3550       CC == ISD::SETUGT) {
3551     swpCmpOps = !swpCmpOps;
3552     swpVselOps = !swpVselOps;
3553     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3554   }
3555
3556   // 'ordered' is 'anything but unordered', so use the VS condition code and
3557   // swap the VSEL operands.
3558   if (CC == ISD::SETO) {
3559     CondCode = ARMCC::VS;
3560     swpVselOps = true;
3561   }
3562
3563   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3564   // code and swap the VSEL operands.
3565   if (CC == ISD::SETUNE) {
3566     CondCode = ARMCC::EQ;
3567     swpVselOps = true;
3568   }
3569 }
3570
3571 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3572                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3573                                    SDValue Cmp, SelectionDAG &DAG) const {
3574   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3575     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3576                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3577     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3578                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3579
3580     SDValue TrueLow = TrueVal.getValue(0);
3581     SDValue TrueHigh = TrueVal.getValue(1);
3582     SDValue FalseLow = FalseVal.getValue(0);
3583     SDValue FalseHigh = FalseVal.getValue(1);
3584
3585     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3586                               ARMcc, CCR, Cmp);
3587     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3588                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3589
3590     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3591   } else {
3592     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3593                        Cmp);
3594   }
3595 }
3596
3597 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3598   EVT VT = Op.getValueType();
3599   SDValue LHS = Op.getOperand(0);
3600   SDValue RHS = Op.getOperand(1);
3601   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3602   SDValue TrueVal = Op.getOperand(2);
3603   SDValue FalseVal = Op.getOperand(3);
3604   SDLoc dl(Op);
3605
3606   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3607     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3608                                                     dl);
3609
3610     // If softenSetCCOperands only returned one value, we should compare it to
3611     // zero.
3612     if (!RHS.getNode()) {
3613       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3614       CC = ISD::SETNE;
3615     }
3616   }
3617
3618   if (LHS.getValueType() == MVT::i32) {
3619     // Try to generate VSEL on ARMv8.
3620     // The VSEL instruction can't use all the usual ARM condition
3621     // codes: it only has two bits to select the condition code, so it's
3622     // constrained to use only GE, GT, VS and EQ.
3623     //
3624     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3625     // swap the operands of the previous compare instruction (effectively
3626     // inverting the compare condition, swapping 'less' and 'greater') and
3627     // sometimes need to swap the operands to the VSEL (which inverts the
3628     // condition in the sense of firing whenever the previous condition didn't)
3629     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3630                                     TrueVal.getValueType() == MVT::f64)) {
3631       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3632       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3633           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3634         CC = ISD::getSetCCInverse(CC, true);
3635         std::swap(TrueVal, FalseVal);
3636       }
3637     }
3638
3639     SDValue ARMcc;
3640     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3641     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3642     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3643   }
3644
3645   ARMCC::CondCodes CondCode, CondCode2;
3646   FPCCToARMCC(CC, CondCode, CondCode2);
3647
3648   // Try to generate VMAXNM/VMINNM on ARMv8.
3649   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3650                                   TrueVal.getValueType() == MVT::f64)) {
3651     bool swpCmpOps = false;
3652     bool swpVselOps = false;
3653     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3654
3655     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3656         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3657       if (swpCmpOps)
3658         std::swap(LHS, RHS);
3659       if (swpVselOps)
3660         std::swap(TrueVal, FalseVal);
3661     }
3662   }
3663
3664   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3665   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3666   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3667   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3668   if (CondCode2 != ARMCC::AL) {
3669     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3670     // FIXME: Needs another CMP because flag can have but one use.
3671     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3672     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3673   }
3674   return Result;
3675 }
3676
3677 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3678 /// to morph to an integer compare sequence.
3679 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3680                            const ARMSubtarget *Subtarget) {
3681   SDNode *N = Op.getNode();
3682   if (!N->hasOneUse())
3683     // Otherwise it requires moving the value from fp to integer registers.
3684     return false;
3685   if (!N->getNumValues())
3686     return false;
3687   EVT VT = Op.getValueType();
3688   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3689     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3690     // vmrs are very slow, e.g. cortex-a8.
3691     return false;
3692
3693   if (isFloatingPointZero(Op)) {
3694     SeenZero = true;
3695     return true;
3696   }
3697   return ISD::isNormalLoad(N);
3698 }
3699
3700 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3701   if (isFloatingPointZero(Op))
3702     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3703
3704   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3705     return DAG.getLoad(MVT::i32, SDLoc(Op),
3706                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3707                        Ld->isVolatile(), Ld->isNonTemporal(),
3708                        Ld->isInvariant(), Ld->getAlignment());
3709
3710   llvm_unreachable("Unknown VFP cmp argument!");
3711 }
3712
3713 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3714                            SDValue &RetVal1, SDValue &RetVal2) {
3715   SDLoc dl(Op);
3716
3717   if (isFloatingPointZero(Op)) {
3718     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3719     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3720     return;
3721   }
3722
3723   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3724     SDValue Ptr = Ld->getBasePtr();
3725     RetVal1 = DAG.getLoad(MVT::i32, dl,
3726                           Ld->getChain(), Ptr,
3727                           Ld->getPointerInfo(),
3728                           Ld->isVolatile(), Ld->isNonTemporal(),
3729                           Ld->isInvariant(), Ld->getAlignment());
3730
3731     EVT PtrType = Ptr.getValueType();
3732     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3733     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3734                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3735     RetVal2 = DAG.getLoad(MVT::i32, dl,
3736                           Ld->getChain(), NewPtr,
3737                           Ld->getPointerInfo().getWithOffset(4),
3738                           Ld->isVolatile(), Ld->isNonTemporal(),
3739                           Ld->isInvariant(), NewAlign);
3740     return;
3741   }
3742
3743   llvm_unreachable("Unknown VFP cmp argument!");
3744 }
3745
3746 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3747 /// f32 and even f64 comparisons to integer ones.
3748 SDValue
3749 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3750   SDValue Chain = Op.getOperand(0);
3751   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3752   SDValue LHS = Op.getOperand(2);
3753   SDValue RHS = Op.getOperand(3);
3754   SDValue Dest = Op.getOperand(4);
3755   SDLoc dl(Op);
3756
3757   bool LHSSeenZero = false;
3758   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3759   bool RHSSeenZero = false;
3760   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3761   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3762     // If unsafe fp math optimization is enabled and there are no other uses of
3763     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3764     // to an integer comparison.
3765     if (CC == ISD::SETOEQ)
3766       CC = ISD::SETEQ;
3767     else if (CC == ISD::SETUNE)
3768       CC = ISD::SETNE;
3769
3770     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3771     SDValue ARMcc;
3772     if (LHS.getValueType() == MVT::f32) {
3773       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3774                         bitcastf32Toi32(LHS, DAG), Mask);
3775       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3776                         bitcastf32Toi32(RHS, DAG), Mask);
3777       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3778       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3779       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3780                          Chain, Dest, ARMcc, CCR, Cmp);
3781     }
3782
3783     SDValue LHS1, LHS2;
3784     SDValue RHS1, RHS2;
3785     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3786     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3787     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3788     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3789     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3790     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3791     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3792     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3793     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3794   }
3795
3796   return SDValue();
3797 }
3798
3799 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3800   SDValue Chain = Op.getOperand(0);
3801   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3802   SDValue LHS = Op.getOperand(2);
3803   SDValue RHS = Op.getOperand(3);
3804   SDValue Dest = Op.getOperand(4);
3805   SDLoc dl(Op);
3806
3807   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3808     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3809                                                     dl);
3810
3811     // If softenSetCCOperands only returned one value, we should compare it to
3812     // zero.
3813     if (!RHS.getNode()) {
3814       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3815       CC = ISD::SETNE;
3816     }
3817   }
3818
3819   if (LHS.getValueType() == MVT::i32) {
3820     SDValue ARMcc;
3821     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3822     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3823     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3824                        Chain, Dest, ARMcc, CCR, Cmp);
3825   }
3826
3827   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3828
3829   if (getTargetMachine().Options.UnsafeFPMath &&
3830       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3831        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3832     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3833     if (Result.getNode())
3834       return Result;
3835   }
3836
3837   ARMCC::CondCodes CondCode, CondCode2;
3838   FPCCToARMCC(CC, CondCode, CondCode2);
3839
3840   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3841   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3842   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3843   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3844   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3845   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3846   if (CondCode2 != ARMCC::AL) {
3847     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3848     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3849     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3850   }
3851   return Res;
3852 }
3853
3854 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3855   SDValue Chain = Op.getOperand(0);
3856   SDValue Table = Op.getOperand(1);
3857   SDValue Index = Op.getOperand(2);
3858   SDLoc dl(Op);
3859
3860   EVT PTy = getPointerTy(DAG.getDataLayout());
3861   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3862   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3863   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3864   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3865   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3866   if (Subtarget->isThumb2()) {
3867     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3868     // which does another jump to the destination. This also makes it easier
3869     // to translate it to TBB / TBH later.
3870     // FIXME: This might not work if the function is extremely large.
3871     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3872                        Addr, Op.getOperand(2), JTI);
3873   }
3874   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3875     Addr =
3876         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3877                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3878                     false, false, false, 0);
3879     Chain = Addr.getValue(1);
3880     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3881     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3882   } else {
3883     Addr =
3884         DAG.getLoad(PTy, dl, Chain, Addr,
3885                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3886                     false, false, false, 0);
3887     Chain = Addr.getValue(1);
3888     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3889   }
3890 }
3891
3892 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3893   EVT VT = Op.getValueType();
3894   SDLoc dl(Op);
3895
3896   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3897     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3898       return Op;
3899     return DAG.UnrollVectorOp(Op.getNode());
3900   }
3901
3902   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3903          "Invalid type for custom lowering!");
3904   if (VT != MVT::v4i16)
3905     return DAG.UnrollVectorOp(Op.getNode());
3906
3907   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3908   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3909 }
3910
3911 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3912   EVT VT = Op.getValueType();
3913   if (VT.isVector())
3914     return LowerVectorFP_TO_INT(Op, DAG);
3915   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3916     RTLIB::Libcall LC;
3917     if (Op.getOpcode() == ISD::FP_TO_SINT)
3918       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3919                               Op.getValueType());
3920     else
3921       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3922                               Op.getValueType());
3923     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3924                        /*isSigned*/ false, SDLoc(Op)).first;
3925   }
3926
3927   return Op;
3928 }
3929
3930 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3931   EVT VT = Op.getValueType();
3932   SDLoc dl(Op);
3933
3934   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3935     if (VT.getVectorElementType() == MVT::f32)
3936       return Op;
3937     return DAG.UnrollVectorOp(Op.getNode());
3938   }
3939
3940   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3941          "Invalid type for custom lowering!");
3942   if (VT != MVT::v4f32)
3943     return DAG.UnrollVectorOp(Op.getNode());
3944
3945   unsigned CastOpc;
3946   unsigned Opc;
3947   switch (Op.getOpcode()) {
3948   default: llvm_unreachable("Invalid opcode!");
3949   case ISD::SINT_TO_FP:
3950     CastOpc = ISD::SIGN_EXTEND;
3951     Opc = ISD::SINT_TO_FP;
3952     break;
3953   case ISD::UINT_TO_FP:
3954     CastOpc = ISD::ZERO_EXTEND;
3955     Opc = ISD::UINT_TO_FP;
3956     break;
3957   }
3958
3959   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3960   return DAG.getNode(Opc, dl, VT, Op);
3961 }
3962
3963 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3964   EVT VT = Op.getValueType();
3965   if (VT.isVector())
3966     return LowerVectorINT_TO_FP(Op, DAG);
3967   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3968     RTLIB::Libcall LC;
3969     if (Op.getOpcode() == ISD::SINT_TO_FP)
3970       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3971                               Op.getValueType());
3972     else
3973       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3974                               Op.getValueType());
3975     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3976                        /*isSigned*/ false, SDLoc(Op)).first;
3977   }
3978
3979   return Op;
3980 }
3981
3982 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3983   // Implement fcopysign with a fabs and a conditional fneg.
3984   SDValue Tmp0 = Op.getOperand(0);
3985   SDValue Tmp1 = Op.getOperand(1);
3986   SDLoc dl(Op);
3987   EVT VT = Op.getValueType();
3988   EVT SrcVT = Tmp1.getValueType();
3989   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3990     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3991   bool UseNEON = !InGPR && Subtarget->hasNEON();
3992
3993   if (UseNEON) {
3994     // Use VBSL to copy the sign bit.
3995     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3996     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3997                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3998     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3999     if (VT == MVT::f64)
4000       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4001                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4002                          DAG.getConstant(32, dl, MVT::i32));
4003     else /*if (VT == MVT::f32)*/
4004       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4005     if (SrcVT == MVT::f32) {
4006       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4007       if (VT == MVT::f64)
4008         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4009                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4010                            DAG.getConstant(32, dl, MVT::i32));
4011     } else if (VT == MVT::f32)
4012       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4013                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4014                          DAG.getConstant(32, dl, MVT::i32));
4015     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4016     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4017
4018     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4019                                             dl, MVT::i32);
4020     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4021     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4022                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4023
4024     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4025                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4026                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4027     if (VT == MVT::f32) {
4028       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4029       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4030                         DAG.getConstant(0, dl, MVT::i32));
4031     } else {
4032       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4033     }
4034
4035     return Res;
4036   }
4037
4038   // Bitcast operand 1 to i32.
4039   if (SrcVT == MVT::f64)
4040     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4041                        Tmp1).getValue(1);
4042   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4043
4044   // Or in the signbit with integer operations.
4045   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4046   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4047   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4048   if (VT == MVT::f32) {
4049     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4050                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4051     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4052                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4053   }
4054
4055   // f64: Or the high part with signbit and then combine two parts.
4056   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4057                      Tmp0);
4058   SDValue Lo = Tmp0.getValue(0);
4059   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4060   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4061   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4062 }
4063
4064 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4065   MachineFunction &MF = DAG.getMachineFunction();
4066   MachineFrameInfo *MFI = MF.getFrameInfo();
4067   MFI->setReturnAddressIsTaken(true);
4068
4069   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4070     return SDValue();
4071
4072   EVT VT = Op.getValueType();
4073   SDLoc dl(Op);
4074   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4075   if (Depth) {
4076     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4077     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4078     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4079                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4080                        MachinePointerInfo(), false, false, false, 0);
4081   }
4082
4083   // Return LR, which contains the return address. Mark it an implicit live-in.
4084   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4085   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4086 }
4087
4088 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4089   const ARMBaseRegisterInfo &ARI =
4090     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4091   MachineFunction &MF = DAG.getMachineFunction();
4092   MachineFrameInfo *MFI = MF.getFrameInfo();
4093   MFI->setFrameAddressIsTaken(true);
4094
4095   EVT VT = Op.getValueType();
4096   SDLoc dl(Op);  // FIXME probably not meaningful
4097   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4098   unsigned FrameReg = ARI.getFrameRegister(MF);
4099   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4100   while (Depth--)
4101     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4102                             MachinePointerInfo(),
4103                             false, false, false, 0);
4104   return FrameAddr;
4105 }
4106
4107 // FIXME? Maybe this could be a TableGen attribute on some registers and
4108 // this table could be generated automatically from RegInfo.
4109 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4110                                               SelectionDAG &DAG) const {
4111   unsigned Reg = StringSwitch<unsigned>(RegName)
4112                        .Case("sp", ARM::SP)
4113                        .Default(0);
4114   if (Reg)
4115     return Reg;
4116   report_fatal_error(Twine("Invalid register name \""
4117                               + StringRef(RegName)  + "\"."));
4118 }
4119
4120 // Result is 64 bit value so split into two 32 bit values and return as a
4121 // pair of values.
4122 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4123                                 SelectionDAG &DAG) {
4124   SDLoc DL(N);
4125
4126   // This function is only supposed to be called for i64 type destination.
4127   assert(N->getValueType(0) == MVT::i64
4128           && "ExpandREAD_REGISTER called for non-i64 type result.");
4129
4130   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4131                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4132                              N->getOperand(0),
4133                              N->getOperand(1));
4134
4135   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4136                     Read.getValue(1)));
4137   Results.push_back(Read.getOperand(0));
4138 }
4139
4140 /// ExpandBITCAST - If the target supports VFP, this function is called to
4141 /// expand a bit convert where either the source or destination type is i64 to
4142 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4143 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4144 /// vectors), since the legalizer won't know what to do with that.
4145 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4146   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4147   SDLoc dl(N);
4148   SDValue Op = N->getOperand(0);
4149
4150   // This function is only supposed to be called for i64 types, either as the
4151   // source or destination of the bit convert.
4152   EVT SrcVT = Op.getValueType();
4153   EVT DstVT = N->getValueType(0);
4154   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4155          "ExpandBITCAST called for non-i64 type");
4156
4157   // Turn i64->f64 into VMOVDRR.
4158   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4159     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4160                              DAG.getConstant(0, dl, MVT::i32));
4161     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4162                              DAG.getConstant(1, dl, MVT::i32));
4163     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4164                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4165   }
4166
4167   // Turn f64->i64 into VMOVRRD.
4168   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4169     SDValue Cvt;
4170     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4171         SrcVT.getVectorNumElements() > 1)
4172       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4173                         DAG.getVTList(MVT::i32, MVT::i32),
4174                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4175     else
4176       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4177                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4178     // Merge the pieces into a single i64 value.
4179     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4180   }
4181
4182   return SDValue();
4183 }
4184
4185 /// getZeroVector - Returns a vector of specified type with all zero elements.
4186 /// Zero vectors are used to represent vector negation and in those cases
4187 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4188 /// not support i64 elements, so sometimes the zero vectors will need to be
4189 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4190 /// zero vector.
4191 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4192   assert(VT.isVector() && "Expected a vector type");
4193   // The canonical modified immediate encoding of a zero vector is....0!
4194   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4195   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4196   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4197   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4198 }
4199
4200 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4201 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4202 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4203                                                 SelectionDAG &DAG) const {
4204   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4205   EVT VT = Op.getValueType();
4206   unsigned VTBits = VT.getSizeInBits();
4207   SDLoc dl(Op);
4208   SDValue ShOpLo = Op.getOperand(0);
4209   SDValue ShOpHi = Op.getOperand(1);
4210   SDValue ShAmt  = Op.getOperand(2);
4211   SDValue ARMcc;
4212   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4213
4214   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4215
4216   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4217                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4218   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4219   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4220                                    DAG.getConstant(VTBits, dl, MVT::i32));
4221   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4222   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4223   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4224
4225   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4226   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4227                           ISD::SETGE, ARMcc, DAG, dl);
4228   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4229   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4230                            CCR, Cmp);
4231
4232   SDValue Ops[2] = { Lo, Hi };
4233   return DAG.getMergeValues(Ops, dl);
4234 }
4235
4236 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4237 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4238 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4239                                                SelectionDAG &DAG) const {
4240   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4241   EVT VT = Op.getValueType();
4242   unsigned VTBits = VT.getSizeInBits();
4243   SDLoc dl(Op);
4244   SDValue ShOpLo = Op.getOperand(0);
4245   SDValue ShOpHi = Op.getOperand(1);
4246   SDValue ShAmt  = Op.getOperand(2);
4247   SDValue ARMcc;
4248
4249   assert(Op.getOpcode() == ISD::SHL_PARTS);
4250   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4251                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4252   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4253   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4254                                    DAG.getConstant(VTBits, dl, MVT::i32));
4255   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4256   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4257
4258   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4259   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4260   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4261                           ISD::SETGE, ARMcc, DAG, dl);
4262   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4263   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4264                            CCR, Cmp);
4265
4266   SDValue Ops[2] = { Lo, Hi };
4267   return DAG.getMergeValues(Ops, dl);
4268 }
4269
4270 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4271                                             SelectionDAG &DAG) const {
4272   // The rounding mode is in bits 23:22 of the FPSCR.
4273   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4274   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4275   // so that the shift + and get folded into a bitfield extract.
4276   SDLoc dl(Op);
4277   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4278                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4279                                               MVT::i32));
4280   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4281                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4282   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4283                               DAG.getConstant(22, dl, MVT::i32));
4284   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4285                      DAG.getConstant(3, dl, MVT::i32));
4286 }
4287
4288 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4289                          const ARMSubtarget *ST) {
4290   SDLoc dl(N);
4291   EVT VT = N->getValueType(0);
4292   if (VT.isVector()) {
4293     assert(ST->hasNEON());
4294
4295     // Compute the least significant set bit: LSB = X & -X
4296     SDValue X = N->getOperand(0);
4297     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4298     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4299
4300     EVT ElemTy = VT.getVectorElementType();
4301
4302     if (ElemTy == MVT::i8) {
4303       // Compute with: cttz(x) = ctpop(lsb - 1)
4304       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4305                                 DAG.getTargetConstant(1, dl, ElemTy));
4306       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4307       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4308     }
4309
4310     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4311         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4312       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4313       unsigned NumBits = ElemTy.getSizeInBits();
4314       SDValue WidthMinus1 =
4315           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4316                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4317       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4318       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4319     }
4320
4321     // Compute with: cttz(x) = ctpop(lsb - 1)
4322
4323     // Since we can only compute the number of bits in a byte with vcnt.8, we
4324     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4325     // and i64.
4326
4327     // Compute LSB - 1.
4328     SDValue Bits;
4329     if (ElemTy == MVT::i64) {
4330       // Load constant 0xffff'ffff'ffff'ffff to register.
4331       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4332                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4333       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4334     } else {
4335       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4336                                 DAG.getTargetConstant(1, dl, ElemTy));
4337       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4338     }
4339
4340     // Count #bits with vcnt.8.
4341     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4342     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4343     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4344
4345     // Gather the #bits with vpaddl (pairwise add.)
4346     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4347     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4348         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4349         Cnt8);
4350     if (ElemTy == MVT::i16)
4351       return Cnt16;
4352
4353     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4354     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4355         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4356         Cnt16);
4357     if (ElemTy == MVT::i32)
4358       return Cnt32;
4359
4360     assert(ElemTy == MVT::i64);
4361     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4362         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4363         Cnt32);
4364     return Cnt64;
4365   }
4366
4367   if (!ST->hasV6T2Ops())
4368     return SDValue();
4369
4370   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4371   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4372 }
4373
4374 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4375 /// for each 16-bit element from operand, repeated.  The basic idea is to
4376 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4377 ///
4378 /// Trace for v4i16:
4379 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4380 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4381 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4382 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4383 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4384 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4385 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4386 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4387 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4388   EVT VT = N->getValueType(0);
4389   SDLoc DL(N);
4390
4391   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4392   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4393   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4394   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4395   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4396   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4397 }
4398
4399 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4400 /// bit-count for each 16-bit element from the operand.  We need slightly
4401 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4402 /// 64/128-bit registers.
4403 ///
4404 /// Trace for v4i16:
4405 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4406 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4407 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4408 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4409 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4410   EVT VT = N->getValueType(0);
4411   SDLoc DL(N);
4412
4413   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4414   if (VT.is64BitVector()) {
4415     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4416     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4417                        DAG.getIntPtrConstant(0, DL));
4418   } else {
4419     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4420                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4421     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4422   }
4423 }
4424
4425 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4426 /// bit-count for each 32-bit element from the operand.  The idea here is
4427 /// to split the vector into 16-bit elements, leverage the 16-bit count
4428 /// routine, and then combine the results.
4429 ///
4430 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4431 /// input    = [v0    v1    ] (vi: 32-bit elements)
4432 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4433 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4434 /// vrev: N0 = [k1 k0 k3 k2 ]
4435 ///            [k0 k1 k2 k3 ]
4436 ///       N1 =+[k1 k0 k3 k2 ]
4437 ///            [k0 k2 k1 k3 ]
4438 ///       N2 =+[k1 k3 k0 k2 ]
4439 ///            [k0    k2    k1    k3    ]
4440 /// Extended =+[k1    k3    k0    k2    ]
4441 ///            [k0    k2    ]
4442 /// Extracted=+[k1    k3    ]
4443 ///
4444 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4445   EVT VT = N->getValueType(0);
4446   SDLoc DL(N);
4447
4448   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4449
4450   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4451   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4452   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4453   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4454   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4455
4456   if (VT.is64BitVector()) {
4457     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4458     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4459                        DAG.getIntPtrConstant(0, DL));
4460   } else {
4461     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4462                                     DAG.getIntPtrConstant(0, DL));
4463     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4464   }
4465 }
4466
4467 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4468                           const ARMSubtarget *ST) {
4469   EVT VT = N->getValueType(0);
4470
4471   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4472   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4473           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4474          "Unexpected type for custom ctpop lowering");
4475
4476   if (VT.getVectorElementType() == MVT::i32)
4477     return lowerCTPOP32BitElements(N, DAG);
4478   else
4479     return lowerCTPOP16BitElements(N, DAG);
4480 }
4481
4482 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4483                           const ARMSubtarget *ST) {
4484   EVT VT = N->getValueType(0);
4485   SDLoc dl(N);
4486
4487   if (!VT.isVector())
4488     return SDValue();
4489
4490   // Lower vector shifts on NEON to use VSHL.
4491   assert(ST->hasNEON() && "unexpected vector shift");
4492
4493   // Left shifts translate directly to the vshiftu intrinsic.
4494   if (N->getOpcode() == ISD::SHL)
4495     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4496                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4497                                        MVT::i32),
4498                        N->getOperand(0), N->getOperand(1));
4499
4500   assert((N->getOpcode() == ISD::SRA ||
4501           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4502
4503   // NEON uses the same intrinsics for both left and right shifts.  For
4504   // right shifts, the shift amounts are negative, so negate the vector of
4505   // shift amounts.
4506   EVT ShiftVT = N->getOperand(1).getValueType();
4507   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4508                                      getZeroVector(ShiftVT, DAG, dl),
4509                                      N->getOperand(1));
4510   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4511                              Intrinsic::arm_neon_vshifts :
4512                              Intrinsic::arm_neon_vshiftu);
4513   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4514                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4515                      N->getOperand(0), NegatedCount);
4516 }
4517
4518 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4519                                 const ARMSubtarget *ST) {
4520   EVT VT = N->getValueType(0);
4521   SDLoc dl(N);
4522
4523   // We can get here for a node like i32 = ISD::SHL i32, i64
4524   if (VT != MVT::i64)
4525     return SDValue();
4526
4527   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4528          "Unknown shift to lower!");
4529
4530   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4531   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4532       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4533     return SDValue();
4534
4535   // If we are in thumb mode, we don't have RRX.
4536   if (ST->isThumb1Only()) return SDValue();
4537
4538   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4539   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4540                            DAG.getConstant(0, dl, MVT::i32));
4541   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4542                            DAG.getConstant(1, dl, MVT::i32));
4543
4544   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4545   // captures the result into a carry flag.
4546   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4547   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4548
4549   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4550   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4551
4552   // Merge the pieces into a single i64 value.
4553  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4554 }
4555
4556 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4557   SDValue TmpOp0, TmpOp1;
4558   bool Invert = false;
4559   bool Swap = false;
4560   unsigned Opc = 0;
4561
4562   SDValue Op0 = Op.getOperand(0);
4563   SDValue Op1 = Op.getOperand(1);
4564   SDValue CC = Op.getOperand(2);
4565   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4566   EVT VT = Op.getValueType();
4567   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4568   SDLoc dl(Op);
4569
4570   if (CmpVT.getVectorElementType() == MVT::i64)
4571     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4572     // but it's possible that our operands are 64-bit but our result is 32-bit.
4573     // Bail in this case.
4574     return SDValue();
4575
4576   if (Op1.getValueType().isFloatingPoint()) {
4577     switch (SetCCOpcode) {
4578     default: llvm_unreachable("Illegal FP comparison");
4579     case ISD::SETUNE:
4580     case ISD::SETNE:  Invert = true; // Fallthrough
4581     case ISD::SETOEQ:
4582     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4583     case ISD::SETOLT:
4584     case ISD::SETLT: Swap = true; // Fallthrough
4585     case ISD::SETOGT:
4586     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4587     case ISD::SETOLE:
4588     case ISD::SETLE:  Swap = true; // Fallthrough
4589     case ISD::SETOGE:
4590     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4591     case ISD::SETUGE: Swap = true; // Fallthrough
4592     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4593     case ISD::SETUGT: Swap = true; // Fallthrough
4594     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4595     case ISD::SETUEQ: Invert = true; // Fallthrough
4596     case ISD::SETONE:
4597       // Expand this to (OLT | OGT).
4598       TmpOp0 = Op0;
4599       TmpOp1 = Op1;
4600       Opc = ISD::OR;
4601       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4602       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4603       break;
4604     case ISD::SETUO: Invert = true; // Fallthrough
4605     case ISD::SETO:
4606       // Expand this to (OLT | OGE).
4607       TmpOp0 = Op0;
4608       TmpOp1 = Op1;
4609       Opc = ISD::OR;
4610       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4611       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4612       break;
4613     }
4614   } else {
4615     // Integer comparisons.
4616     switch (SetCCOpcode) {
4617     default: llvm_unreachable("Illegal integer comparison");
4618     case ISD::SETNE:  Invert = true;
4619     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4620     case ISD::SETLT:  Swap = true;
4621     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4622     case ISD::SETLE:  Swap = true;
4623     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4624     case ISD::SETULT: Swap = true;
4625     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4626     case ISD::SETULE: Swap = true;
4627     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4628     }
4629
4630     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4631     if (Opc == ARMISD::VCEQ) {
4632
4633       SDValue AndOp;
4634       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4635         AndOp = Op0;
4636       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4637         AndOp = Op1;
4638
4639       // Ignore bitconvert.
4640       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4641         AndOp = AndOp.getOperand(0);
4642
4643       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4644         Opc = ARMISD::VTST;
4645         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4646         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4647         Invert = !Invert;
4648       }
4649     }
4650   }
4651
4652   if (Swap)
4653     std::swap(Op0, Op1);
4654
4655   // If one of the operands is a constant vector zero, attempt to fold the
4656   // comparison to a specialized compare-against-zero form.
4657   SDValue SingleOp;
4658   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4659     SingleOp = Op0;
4660   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4661     if (Opc == ARMISD::VCGE)
4662       Opc = ARMISD::VCLEZ;
4663     else if (Opc == ARMISD::VCGT)
4664       Opc = ARMISD::VCLTZ;
4665     SingleOp = Op1;
4666   }
4667
4668   SDValue Result;
4669   if (SingleOp.getNode()) {
4670     switch (Opc) {
4671     case ARMISD::VCEQ:
4672       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4673     case ARMISD::VCGE:
4674       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4675     case ARMISD::VCLEZ:
4676       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4677     case ARMISD::VCGT:
4678       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4679     case ARMISD::VCLTZ:
4680       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4681     default:
4682       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4683     }
4684   } else {
4685      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4686   }
4687
4688   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4689
4690   if (Invert)
4691     Result = DAG.getNOT(dl, Result, VT);
4692
4693   return Result;
4694 }
4695
4696 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4697 /// valid vector constant for a NEON instruction with a "modified immediate"
4698 /// operand (e.g., VMOV).  If so, return the encoded value.
4699 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4700                                  unsigned SplatBitSize, SelectionDAG &DAG,
4701                                  SDLoc dl, EVT &VT, bool is128Bits,
4702                                  NEONModImmType type) {
4703   unsigned OpCmode, Imm;
4704
4705   // SplatBitSize is set to the smallest size that splats the vector, so a
4706   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4707   // immediate instructions others than VMOV do not support the 8-bit encoding
4708   // of a zero vector, and the default encoding of zero is supposed to be the
4709   // 32-bit version.
4710   if (SplatBits == 0)
4711     SplatBitSize = 32;
4712
4713   switch (SplatBitSize) {
4714   case 8:
4715     if (type != VMOVModImm)
4716       return SDValue();
4717     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4718     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4719     OpCmode = 0xe;
4720     Imm = SplatBits;
4721     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4722     break;
4723
4724   case 16:
4725     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4726     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4727     if ((SplatBits & ~0xff) == 0) {
4728       // Value = 0x00nn: Op=x, Cmode=100x.
4729       OpCmode = 0x8;
4730       Imm = SplatBits;
4731       break;
4732     }
4733     if ((SplatBits & ~0xff00) == 0) {
4734       // Value = 0xnn00: Op=x, Cmode=101x.
4735       OpCmode = 0xa;
4736       Imm = SplatBits >> 8;
4737       break;
4738     }
4739     return SDValue();
4740
4741   case 32:
4742     // NEON's 32-bit VMOV supports splat values where:
4743     // * only one byte is nonzero, or
4744     // * the least significant byte is 0xff and the second byte is nonzero, or
4745     // * the least significant 2 bytes are 0xff and the third is nonzero.
4746     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4747     if ((SplatBits & ~0xff) == 0) {
4748       // Value = 0x000000nn: Op=x, Cmode=000x.
4749       OpCmode = 0;
4750       Imm = SplatBits;
4751       break;
4752     }
4753     if ((SplatBits & ~0xff00) == 0) {
4754       // Value = 0x0000nn00: Op=x, Cmode=001x.
4755       OpCmode = 0x2;
4756       Imm = SplatBits >> 8;
4757       break;
4758     }
4759     if ((SplatBits & ~0xff0000) == 0) {
4760       // Value = 0x00nn0000: Op=x, Cmode=010x.
4761       OpCmode = 0x4;
4762       Imm = SplatBits >> 16;
4763       break;
4764     }
4765     if ((SplatBits & ~0xff000000) == 0) {
4766       // Value = 0xnn000000: Op=x, Cmode=011x.
4767       OpCmode = 0x6;
4768       Imm = SplatBits >> 24;
4769       break;
4770     }
4771
4772     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4773     if (type == OtherModImm) return SDValue();
4774
4775     if ((SplatBits & ~0xffff) == 0 &&
4776         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4777       // Value = 0x0000nnff: Op=x, Cmode=1100.
4778       OpCmode = 0xc;
4779       Imm = SplatBits >> 8;
4780       break;
4781     }
4782
4783     if ((SplatBits & ~0xffffff) == 0 &&
4784         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4785       // Value = 0x00nnffff: Op=x, Cmode=1101.
4786       OpCmode = 0xd;
4787       Imm = SplatBits >> 16;
4788       break;
4789     }
4790
4791     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4792     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4793     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4794     // and fall through here to test for a valid 64-bit splat.  But, then the
4795     // caller would also need to check and handle the change in size.
4796     return SDValue();
4797
4798   case 64: {
4799     if (type != VMOVModImm)
4800       return SDValue();
4801     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4802     uint64_t BitMask = 0xff;
4803     uint64_t Val = 0;
4804     unsigned ImmMask = 1;
4805     Imm = 0;
4806     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4807       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4808         Val |= BitMask;
4809         Imm |= ImmMask;
4810       } else if ((SplatBits & BitMask) != 0) {
4811         return SDValue();
4812       }
4813       BitMask <<= 8;
4814       ImmMask <<= 1;
4815     }
4816
4817     if (DAG.getDataLayout().isBigEndian())
4818       // swap higher and lower 32 bit word
4819       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4820
4821     // Op=1, Cmode=1110.
4822     OpCmode = 0x1e;
4823     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4824     break;
4825   }
4826
4827   default:
4828     llvm_unreachable("unexpected size for isNEONModifiedImm");
4829   }
4830
4831   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4832   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4833 }
4834
4835 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4836                                            const ARMSubtarget *ST) const {
4837   if (!ST->hasVFP3())
4838     return SDValue();
4839
4840   bool IsDouble = Op.getValueType() == MVT::f64;
4841   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4842
4843   // Use the default (constant pool) lowering for double constants when we have
4844   // an SP-only FPU
4845   if (IsDouble && Subtarget->isFPOnlySP())
4846     return SDValue();
4847
4848   // Try splatting with a VMOV.f32...
4849   APFloat FPVal = CFP->getValueAPF();
4850   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4851
4852   if (ImmVal != -1) {
4853     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4854       // We have code in place to select a valid ConstantFP already, no need to
4855       // do any mangling.
4856       return Op;
4857     }
4858
4859     // It's a float and we are trying to use NEON operations where
4860     // possible. Lower it to a splat followed by an extract.
4861     SDLoc DL(Op);
4862     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4863     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4864                                       NewVal);
4865     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4866                        DAG.getConstant(0, DL, MVT::i32));
4867   }
4868
4869   // The rest of our options are NEON only, make sure that's allowed before
4870   // proceeding..
4871   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4872     return SDValue();
4873
4874   EVT VMovVT;
4875   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4876
4877   // It wouldn't really be worth bothering for doubles except for one very
4878   // important value, which does happen to match: 0.0. So make sure we don't do
4879   // anything stupid.
4880   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4881     return SDValue();
4882
4883   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4884   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4885                                      VMovVT, false, VMOVModImm);
4886   if (NewVal != SDValue()) {
4887     SDLoc DL(Op);
4888     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4889                                       NewVal);
4890     if (IsDouble)
4891       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4892
4893     // It's a float: cast and extract a vector element.
4894     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4895                                        VecConstant);
4896     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4897                        DAG.getConstant(0, DL, MVT::i32));
4898   }
4899
4900   // Finally, try a VMVN.i32
4901   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4902                              false, VMVNModImm);
4903   if (NewVal != SDValue()) {
4904     SDLoc DL(Op);
4905     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4906
4907     if (IsDouble)
4908       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4909
4910     // It's a float: cast and extract a vector element.
4911     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4912                                        VecConstant);
4913     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4914                        DAG.getConstant(0, DL, MVT::i32));
4915   }
4916
4917   return SDValue();
4918 }
4919
4920 // check if an VEXT instruction can handle the shuffle mask when the
4921 // vector sources of the shuffle are the same.
4922 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4923   unsigned NumElts = VT.getVectorNumElements();
4924
4925   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4926   if (M[0] < 0)
4927     return false;
4928
4929   Imm = M[0];
4930
4931   // If this is a VEXT shuffle, the immediate value is the index of the first
4932   // element.  The other shuffle indices must be the successive elements after
4933   // the first one.
4934   unsigned ExpectedElt = Imm;
4935   for (unsigned i = 1; i < NumElts; ++i) {
4936     // Increment the expected index.  If it wraps around, just follow it
4937     // back to index zero and keep going.
4938     ++ExpectedElt;
4939     if (ExpectedElt == NumElts)
4940       ExpectedElt = 0;
4941
4942     if (M[i] < 0) continue; // ignore UNDEF indices
4943     if (ExpectedElt != static_cast<unsigned>(M[i]))
4944       return false;
4945   }
4946
4947   return true;
4948 }
4949
4950
4951 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4952                        bool &ReverseVEXT, unsigned &Imm) {
4953   unsigned NumElts = VT.getVectorNumElements();
4954   ReverseVEXT = false;
4955
4956   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4957   if (M[0] < 0)
4958     return false;
4959
4960   Imm = M[0];
4961
4962   // If this is a VEXT shuffle, the immediate value is the index of the first
4963   // element.  The other shuffle indices must be the successive elements after
4964   // the first one.
4965   unsigned ExpectedElt = Imm;
4966   for (unsigned i = 1; i < NumElts; ++i) {
4967     // Increment the expected index.  If it wraps around, it may still be
4968     // a VEXT but the source vectors must be swapped.
4969     ExpectedElt += 1;
4970     if (ExpectedElt == NumElts * 2) {
4971       ExpectedElt = 0;
4972       ReverseVEXT = true;
4973     }
4974
4975     if (M[i] < 0) continue; // ignore UNDEF indices
4976     if (ExpectedElt != static_cast<unsigned>(M[i]))
4977       return false;
4978   }
4979
4980   // Adjust the index value if the source operands will be swapped.
4981   if (ReverseVEXT)
4982     Imm -= NumElts;
4983
4984   return true;
4985 }
4986
4987 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4988 /// instruction with the specified blocksize.  (The order of the elements
4989 /// within each block of the vector is reversed.)
4990 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4991   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4992          "Only possible block sizes for VREV are: 16, 32, 64");
4993
4994   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4995   if (EltSz == 64)
4996     return false;
4997
4998   unsigned NumElts = VT.getVectorNumElements();
4999   unsigned BlockElts = M[0] + 1;
5000   // If the first shuffle index is UNDEF, be optimistic.
5001   if (M[0] < 0)
5002     BlockElts = BlockSize / EltSz;
5003
5004   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5005     return false;
5006
5007   for (unsigned i = 0; i < NumElts; ++i) {
5008     if (M[i] < 0) continue; // ignore UNDEF indices
5009     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5010       return false;
5011   }
5012
5013   return true;
5014 }
5015
5016 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5017   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5018   // range, then 0 is placed into the resulting vector. So pretty much any mask
5019   // of 8 elements can work here.
5020   return VT == MVT::v8i8 && M.size() == 8;
5021 }
5022
5023 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5024 // checking that pairs of elements in the shuffle mask represent the same index
5025 // in each vector, incrementing the expected index by 2 at each step.
5026 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5027 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5028 //  v2={e,f,g,h}
5029 // WhichResult gives the offset for each element in the mask based on which
5030 // of the two results it belongs to.
5031 //
5032 // The transpose can be represented either as:
5033 // result1 = shufflevector v1, v2, result1_shuffle_mask
5034 // result2 = shufflevector v1, v2, result2_shuffle_mask
5035 // where v1/v2 and the shuffle masks have the same number of elements
5036 // (here WhichResult (see below) indicates which result is being checked)
5037 //
5038 // or as:
5039 // results = shufflevector v1, v2, shuffle_mask
5040 // where both results are returned in one vector and the shuffle mask has twice
5041 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5042 // want to check the low half and high half of the shuffle mask as if it were
5043 // the other case
5044 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5045   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5046   if (EltSz == 64)
5047     return false;
5048
5049   unsigned NumElts = VT.getVectorNumElements();
5050   if (M.size() != NumElts && M.size() != NumElts*2)
5051     return false;
5052
5053   // If the mask is twice as long as the input vector then we need to check the
5054   // upper and lower parts of the mask with a matching value for WhichResult
5055   // FIXME: A mask with only even values will be rejected in case the first
5056   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5057   // M[0] is used to determine WhichResult
5058   for (unsigned i = 0; i < M.size(); i += NumElts) {
5059     if (M.size() == NumElts * 2)
5060       WhichResult = i / NumElts;
5061     else
5062       WhichResult = M[i] == 0 ? 0 : 1;
5063     for (unsigned j = 0; j < NumElts; j += 2) {
5064       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5065           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5066         return false;
5067     }
5068   }
5069
5070   if (M.size() == NumElts*2)
5071     WhichResult = 0;
5072
5073   return true;
5074 }
5075
5076 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5077 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5078 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5079 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5080   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5081   if (EltSz == 64)
5082     return false;
5083
5084   unsigned NumElts = VT.getVectorNumElements();
5085   if (M.size() != NumElts && M.size() != NumElts*2)
5086     return false;
5087
5088   for (unsigned i = 0; i < M.size(); i += NumElts) {
5089     if (M.size() == NumElts * 2)
5090       WhichResult = i / NumElts;
5091     else
5092       WhichResult = M[i] == 0 ? 0 : 1;
5093     for (unsigned j = 0; j < NumElts; j += 2) {
5094       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5095           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5096         return false;
5097     }
5098   }
5099
5100   if (M.size() == NumElts*2)
5101     WhichResult = 0;
5102
5103   return true;
5104 }
5105
5106 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5107 // that the mask elements are either all even and in steps of size 2 or all odd
5108 // and in steps of size 2.
5109 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5110 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5111 //  v2={e,f,g,h}
5112 // Requires similar checks to that of isVTRNMask with
5113 // respect the how results are returned.
5114 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5115   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5116   if (EltSz == 64)
5117     return false;
5118
5119   unsigned NumElts = VT.getVectorNumElements();
5120   if (M.size() != NumElts && M.size() != NumElts*2)
5121     return false;
5122
5123   for (unsigned i = 0; i < M.size(); i += NumElts) {
5124     WhichResult = M[i] == 0 ? 0 : 1;
5125     for (unsigned j = 0; j < NumElts; ++j) {
5126       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5127         return false;
5128     }
5129   }
5130
5131   if (M.size() == NumElts*2)
5132     WhichResult = 0;
5133
5134   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5135   if (VT.is64BitVector() && EltSz == 32)
5136     return false;
5137
5138   return true;
5139 }
5140
5141 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5142 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5143 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5144 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5145   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5146   if (EltSz == 64)
5147     return false;
5148
5149   unsigned NumElts = VT.getVectorNumElements();
5150   if (M.size() != NumElts && M.size() != NumElts*2)
5151     return false;
5152
5153   unsigned Half = NumElts / 2;
5154   for (unsigned i = 0; i < M.size(); i += NumElts) {
5155     WhichResult = M[i] == 0 ? 0 : 1;
5156     for (unsigned j = 0; j < NumElts; j += Half) {
5157       unsigned Idx = WhichResult;
5158       for (unsigned k = 0; k < Half; ++k) {
5159         int MIdx = M[i + j + k];
5160         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5161           return false;
5162         Idx += 2;
5163       }
5164     }
5165   }
5166
5167   if (M.size() == NumElts*2)
5168     WhichResult = 0;
5169
5170   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5171   if (VT.is64BitVector() && EltSz == 32)
5172     return false;
5173
5174   return true;
5175 }
5176
5177 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5178 // that pairs of elements of the shufflemask represent the same index in each
5179 // vector incrementing sequentially through the vectors.
5180 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5181 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5182 //  v2={e,f,g,h}
5183 // Requires similar checks to that of isVTRNMask with respect the how results
5184 // are returned.
5185 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5186   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5187   if (EltSz == 64)
5188     return false;
5189
5190   unsigned NumElts = VT.getVectorNumElements();
5191   if (M.size() != NumElts && M.size() != NumElts*2)
5192     return false;
5193
5194   for (unsigned i = 0; i < M.size(); i += NumElts) {
5195     WhichResult = M[i] == 0 ? 0 : 1;
5196     unsigned Idx = WhichResult * NumElts / 2;
5197     for (unsigned j = 0; j < NumElts; j += 2) {
5198       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5199           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5200         return false;
5201       Idx += 1;
5202     }
5203   }
5204
5205   if (M.size() == NumElts*2)
5206     WhichResult = 0;
5207
5208   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5209   if (VT.is64BitVector() && EltSz == 32)
5210     return false;
5211
5212   return true;
5213 }
5214
5215 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5216 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5217 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5218 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5219   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5220   if (EltSz == 64)
5221     return false;
5222
5223   unsigned NumElts = VT.getVectorNumElements();
5224   if (M.size() != NumElts && M.size() != NumElts*2)
5225     return false;
5226
5227   for (unsigned i = 0; i < M.size(); i += NumElts) {
5228     WhichResult = M[i] == 0 ? 0 : 1;
5229     unsigned Idx = WhichResult * NumElts / 2;
5230     for (unsigned j = 0; j < NumElts; j += 2) {
5231       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5232           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5233         return false;
5234       Idx += 1;
5235     }
5236   }
5237
5238   if (M.size() == NumElts*2)
5239     WhichResult = 0;
5240
5241   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5242   if (VT.is64BitVector() && EltSz == 32)
5243     return false;
5244
5245   return true;
5246 }
5247
5248 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5249 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5250 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5251                                            unsigned &WhichResult,
5252                                            bool &isV_UNDEF) {
5253   isV_UNDEF = false;
5254   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5255     return ARMISD::VTRN;
5256   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5257     return ARMISD::VUZP;
5258   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5259     return ARMISD::VZIP;
5260
5261   isV_UNDEF = true;
5262   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5263     return ARMISD::VTRN;
5264   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5265     return ARMISD::VUZP;
5266   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5267     return ARMISD::VZIP;
5268
5269   return 0;
5270 }
5271
5272 /// \return true if this is a reverse operation on an vector.
5273 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5274   unsigned NumElts = VT.getVectorNumElements();
5275   // Make sure the mask has the right size.
5276   if (NumElts != M.size())
5277       return false;
5278
5279   // Look for <15, ..., 3, -1, 1, 0>.
5280   for (unsigned i = 0; i != NumElts; ++i)
5281     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5282       return false;
5283
5284   return true;
5285 }
5286
5287 // If N is an integer constant that can be moved into a register in one
5288 // instruction, return an SDValue of such a constant (will become a MOV
5289 // instruction).  Otherwise return null.
5290 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5291                                      const ARMSubtarget *ST, SDLoc dl) {
5292   uint64_t Val;
5293   if (!isa<ConstantSDNode>(N))
5294     return SDValue();
5295   Val = cast<ConstantSDNode>(N)->getZExtValue();
5296
5297   if (ST->isThumb1Only()) {
5298     if (Val <= 255 || ~Val <= 255)
5299       return DAG.getConstant(Val, dl, MVT::i32);
5300   } else {
5301     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5302       return DAG.getConstant(Val, dl, MVT::i32);
5303   }
5304   return SDValue();
5305 }
5306
5307 // If this is a case we can't handle, return null and let the default
5308 // expansion code take care of it.
5309 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5310                                              const ARMSubtarget *ST) const {
5311   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5312   SDLoc dl(Op);
5313   EVT VT = Op.getValueType();
5314
5315   APInt SplatBits, SplatUndef;
5316   unsigned SplatBitSize;
5317   bool HasAnyUndefs;
5318   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5319     if (SplatBitSize <= 64) {
5320       // Check if an immediate VMOV works.
5321       EVT VmovVT;
5322       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5323                                       SplatUndef.getZExtValue(), SplatBitSize,
5324                                       DAG, dl, VmovVT, VT.is128BitVector(),
5325                                       VMOVModImm);
5326       if (Val.getNode()) {
5327         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5328         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5329       }
5330
5331       // Try an immediate VMVN.
5332       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5333       Val = isNEONModifiedImm(NegatedImm,
5334                                       SplatUndef.getZExtValue(), SplatBitSize,
5335                                       DAG, dl, VmovVT, VT.is128BitVector(),
5336                                       VMVNModImm);
5337       if (Val.getNode()) {
5338         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5339         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5340       }
5341
5342       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5343       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5344         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5345         if (ImmVal != -1) {
5346           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5347           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5348         }
5349       }
5350     }
5351   }
5352
5353   // Scan through the operands to see if only one value is used.
5354   //
5355   // As an optimisation, even if more than one value is used it may be more
5356   // profitable to splat with one value then change some lanes.
5357   //
5358   // Heuristically we decide to do this if the vector has a "dominant" value,
5359   // defined as splatted to more than half of the lanes.
5360   unsigned NumElts = VT.getVectorNumElements();
5361   bool isOnlyLowElement = true;
5362   bool usesOnlyOneValue = true;
5363   bool hasDominantValue = false;
5364   bool isConstant = true;
5365
5366   // Map of the number of times a particular SDValue appears in the
5367   // element list.
5368   DenseMap<SDValue, unsigned> ValueCounts;
5369   SDValue Value;
5370   for (unsigned i = 0; i < NumElts; ++i) {
5371     SDValue V = Op.getOperand(i);
5372     if (V.getOpcode() == ISD::UNDEF)
5373       continue;
5374     if (i > 0)
5375       isOnlyLowElement = false;
5376     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5377       isConstant = false;
5378
5379     ValueCounts.insert(std::make_pair(V, 0));
5380     unsigned &Count = ValueCounts[V];
5381
5382     // Is this value dominant? (takes up more than half of the lanes)
5383     if (++Count > (NumElts / 2)) {
5384       hasDominantValue = true;
5385       Value = V;
5386     }
5387   }
5388   if (ValueCounts.size() != 1)
5389     usesOnlyOneValue = false;
5390   if (!Value.getNode() && ValueCounts.size() > 0)
5391     Value = ValueCounts.begin()->first;
5392
5393   if (ValueCounts.size() == 0)
5394     return DAG.getUNDEF(VT);
5395
5396   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5397   // Keep going if we are hitting this case.
5398   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5399     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5400
5401   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5402
5403   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5404   // i32 and try again.
5405   if (hasDominantValue && EltSize <= 32) {
5406     if (!isConstant) {
5407       SDValue N;
5408
5409       // If we are VDUPing a value that comes directly from a vector, that will
5410       // cause an unnecessary move to and from a GPR, where instead we could
5411       // just use VDUPLANE. We can only do this if the lane being extracted
5412       // is at a constant index, as the VDUP from lane instructions only have
5413       // constant-index forms.
5414       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5415           isa<ConstantSDNode>(Value->getOperand(1))) {
5416         // We need to create a new undef vector to use for the VDUPLANE if the
5417         // size of the vector from which we get the value is different than the
5418         // size of the vector that we need to create. We will insert the element
5419         // such that the register coalescer will remove unnecessary copies.
5420         if (VT != Value->getOperand(0).getValueType()) {
5421           ConstantSDNode *constIndex;
5422           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5423           assert(constIndex && "The index is not a constant!");
5424           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5425                              VT.getVectorNumElements();
5426           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5427                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5428                         Value, DAG.getConstant(index, dl, MVT::i32)),
5429                            DAG.getConstant(index, dl, MVT::i32));
5430         } else
5431           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5432                         Value->getOperand(0), Value->getOperand(1));
5433       } else
5434         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5435
5436       if (!usesOnlyOneValue) {
5437         // The dominant value was splatted as 'N', but we now have to insert
5438         // all differing elements.
5439         for (unsigned I = 0; I < NumElts; ++I) {
5440           if (Op.getOperand(I) == Value)
5441             continue;
5442           SmallVector<SDValue, 3> Ops;
5443           Ops.push_back(N);
5444           Ops.push_back(Op.getOperand(I));
5445           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5446           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5447         }
5448       }
5449       return N;
5450     }
5451     if (VT.getVectorElementType().isFloatingPoint()) {
5452       SmallVector<SDValue, 8> Ops;
5453       for (unsigned i = 0; i < NumElts; ++i)
5454         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5455                                   Op.getOperand(i)));
5456       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5457       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5458       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5459       if (Val.getNode())
5460         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5461     }
5462     if (usesOnlyOneValue) {
5463       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5464       if (isConstant && Val.getNode())
5465         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5466     }
5467   }
5468
5469   // If all elements are constants and the case above didn't get hit, fall back
5470   // to the default expansion, which will generate a load from the constant
5471   // pool.
5472   if (isConstant)
5473     return SDValue();
5474
5475   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5476   if (NumElts >= 4) {
5477     SDValue shuffle = ReconstructShuffle(Op, DAG);
5478     if (shuffle != SDValue())
5479       return shuffle;
5480   }
5481
5482   // Vectors with 32- or 64-bit elements can be built by directly assigning
5483   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5484   // will be legalized.
5485   if (EltSize >= 32) {
5486     // Do the expansion with floating-point types, since that is what the VFP
5487     // registers are defined to use, and since i64 is not legal.
5488     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5489     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5490     SmallVector<SDValue, 8> Ops;
5491     for (unsigned i = 0; i < NumElts; ++i)
5492       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5493     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5494     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5495   }
5496
5497   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5498   // know the default expansion would otherwise fall back on something even
5499   // worse. For a vector with one or two non-undef values, that's
5500   // scalar_to_vector for the elements followed by a shuffle (provided the
5501   // shuffle is valid for the target) and materialization element by element
5502   // on the stack followed by a load for everything else.
5503   if (!isConstant && !usesOnlyOneValue) {
5504     SDValue Vec = DAG.getUNDEF(VT);
5505     for (unsigned i = 0 ; i < NumElts; ++i) {
5506       SDValue V = Op.getOperand(i);
5507       if (V.getOpcode() == ISD::UNDEF)
5508         continue;
5509       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5510       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5511     }
5512     return Vec;
5513   }
5514
5515   return SDValue();
5516 }
5517
5518 /// getExtFactor - Determine the adjustment factor for the position when
5519 /// generating an "extract from vector registers" instruction.
5520 static unsigned getExtFactor(SDValue &V) {
5521   EVT EltType = V.getValueType().getVectorElementType();
5522   return EltType.getSizeInBits() / 8;
5523 }
5524
5525 // Gather data to see if the operation can be modelled as a
5526 // shuffle in combination with VEXTs.
5527 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5528                                               SelectionDAG &DAG) const {
5529   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5530   SDLoc dl(Op);
5531   EVT VT = Op.getValueType();
5532   unsigned NumElts = VT.getVectorNumElements();
5533
5534   struct ShuffleSourceInfo {
5535     SDValue Vec;
5536     unsigned MinElt;
5537     unsigned MaxElt;
5538
5539     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5540     // be compatible with the shuffle we intend to construct. As a result
5541     // ShuffleVec will be some sliding window into the original Vec.
5542     SDValue ShuffleVec;
5543
5544     // Code should guarantee that element i in Vec starts at element "WindowBase
5545     // + i * WindowScale in ShuffleVec".
5546     int WindowBase;
5547     int WindowScale;
5548
5549     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5550     ShuffleSourceInfo(SDValue Vec)
5551         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5552           WindowScale(1) {}
5553   };
5554
5555   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5556   // node.
5557   SmallVector<ShuffleSourceInfo, 2> Sources;
5558   for (unsigned i = 0; i < NumElts; ++i) {
5559     SDValue V = Op.getOperand(i);
5560     if (V.getOpcode() == ISD::UNDEF)
5561       continue;
5562     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5563       // A shuffle can only come from building a vector from various
5564       // elements of other vectors.
5565       return SDValue();
5566     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5567       // Furthermore, shuffles require a constant mask, whereas extractelts
5568       // accept variable indices.
5569       return SDValue();
5570     }
5571
5572     // Add this element source to the list if it's not already there.
5573     SDValue SourceVec = V.getOperand(0);
5574     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5575     if (Source == Sources.end())
5576       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5577
5578     // Update the minimum and maximum lane number seen.
5579     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5580     Source->MinElt = std::min(Source->MinElt, EltNo);
5581     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5582   }
5583
5584   // Currently only do something sane when at most two source vectors
5585   // are involved.
5586   if (Sources.size() > 2)
5587     return SDValue();
5588
5589   // Find out the smallest element size among result and two sources, and use
5590   // it as element size to build the shuffle_vector.
5591   EVT SmallestEltTy = VT.getVectorElementType();
5592   for (auto &Source : Sources) {
5593     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5594     if (SrcEltTy.bitsLT(SmallestEltTy))
5595       SmallestEltTy = SrcEltTy;
5596   }
5597   unsigned ResMultiplier =
5598       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5599   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5600   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5601
5602   // If the source vector is too wide or too narrow, we may nevertheless be able
5603   // to construct a compatible shuffle either by concatenating it with UNDEF or
5604   // extracting a suitable range of elements.
5605   for (auto &Src : Sources) {
5606     EVT SrcVT = Src.ShuffleVec.getValueType();
5607
5608     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5609       continue;
5610
5611     // This stage of the search produces a source with the same element type as
5612     // the original, but with a total width matching the BUILD_VECTOR output.
5613     EVT EltVT = SrcVT.getVectorElementType();
5614     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5615     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5616
5617     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5618       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5619         return SDValue();
5620       // We can pad out the smaller vector for free, so if it's part of a
5621       // shuffle...
5622       Src.ShuffleVec =
5623           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5624                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5625       continue;
5626     }
5627
5628     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5629       return SDValue();
5630
5631     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5632       // Span too large for a VEXT to cope
5633       return SDValue();
5634     }
5635
5636     if (Src.MinElt >= NumSrcElts) {
5637       // The extraction can just take the second half
5638       Src.ShuffleVec =
5639           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5640                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5641       Src.WindowBase = -NumSrcElts;
5642     } else if (Src.MaxElt < NumSrcElts) {
5643       // The extraction can just take the first half
5644       Src.ShuffleVec =
5645           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5646                       DAG.getConstant(0, dl, MVT::i32));
5647     } else {
5648       // An actual VEXT is needed
5649       SDValue VEXTSrc1 =
5650           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5651                       DAG.getConstant(0, dl, MVT::i32));
5652       SDValue VEXTSrc2 =
5653           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5654                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5655       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5656
5657       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5658                                    VEXTSrc2,
5659                                    DAG.getConstant(Imm, dl, MVT::i32));
5660       Src.WindowBase = -Src.MinElt;
5661     }
5662   }
5663
5664   // Another possible incompatibility occurs from the vector element types. We
5665   // can fix this by bitcasting the source vectors to the same type we intend
5666   // for the shuffle.
5667   for (auto &Src : Sources) {
5668     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5669     if (SrcEltTy == SmallestEltTy)
5670       continue;
5671     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5672     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5673     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5674     Src.WindowBase *= Src.WindowScale;
5675   }
5676
5677   // Final sanity check before we try to actually produce a shuffle.
5678   DEBUG(
5679     for (auto Src : Sources)
5680       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5681   );
5682
5683   // The stars all align, our next step is to produce the mask for the shuffle.
5684   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5685   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5686   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5687     SDValue Entry = Op.getOperand(i);
5688     if (Entry.getOpcode() == ISD::UNDEF)
5689       continue;
5690
5691     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5692     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5693
5694     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5695     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5696     // segment.
5697     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5698     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5699                                VT.getVectorElementType().getSizeInBits());
5700     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5701
5702     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5703     // starting at the appropriate offset.
5704     int *LaneMask = &Mask[i * ResMultiplier];
5705
5706     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5707     ExtractBase += NumElts * (Src - Sources.begin());
5708     for (int j = 0; j < LanesDefined; ++j)
5709       LaneMask[j] = ExtractBase + j;
5710   }
5711
5712   // Final check before we try to produce nonsense...
5713   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5714     return SDValue();
5715
5716   // We can't handle more than two sources. This should have already
5717   // been checked before this point.
5718   assert(Sources.size() <= 2 && "Too many sources!");
5719
5720   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5721   for (unsigned i = 0; i < Sources.size(); ++i)
5722     ShuffleOps[i] = Sources[i].ShuffleVec;
5723
5724   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5725                                          ShuffleOps[1], &Mask[0]);
5726   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5727 }
5728
5729 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5730 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5731 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5732 /// are assumed to be legal.
5733 bool
5734 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5735                                       EVT VT) const {
5736   if (VT.getVectorNumElements() == 4 &&
5737       (VT.is128BitVector() || VT.is64BitVector())) {
5738     unsigned PFIndexes[4];
5739     for (unsigned i = 0; i != 4; ++i) {
5740       if (M[i] < 0)
5741         PFIndexes[i] = 8;
5742       else
5743         PFIndexes[i] = M[i];
5744     }
5745
5746     // Compute the index in the perfect shuffle table.
5747     unsigned PFTableIndex =
5748       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5749     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5750     unsigned Cost = (PFEntry >> 30);
5751
5752     if (Cost <= 4)
5753       return true;
5754   }
5755
5756   bool ReverseVEXT, isV_UNDEF;
5757   unsigned Imm, WhichResult;
5758
5759   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5760   return (EltSize >= 32 ||
5761           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5762           isVREVMask(M, VT, 64) ||
5763           isVREVMask(M, VT, 32) ||
5764           isVREVMask(M, VT, 16) ||
5765           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5766           isVTBLMask(M, VT) ||
5767           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5768           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5769 }
5770
5771 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5772 /// the specified operations to build the shuffle.
5773 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5774                                       SDValue RHS, SelectionDAG &DAG,
5775                                       SDLoc dl) {
5776   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5777   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5778   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5779
5780   enum {
5781     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5782     OP_VREV,
5783     OP_VDUP0,
5784     OP_VDUP1,
5785     OP_VDUP2,
5786     OP_VDUP3,
5787     OP_VEXT1,
5788     OP_VEXT2,
5789     OP_VEXT3,
5790     OP_VUZPL, // VUZP, left result
5791     OP_VUZPR, // VUZP, right result
5792     OP_VZIPL, // VZIP, left result
5793     OP_VZIPR, // VZIP, right result
5794     OP_VTRNL, // VTRN, left result
5795     OP_VTRNR  // VTRN, right result
5796   };
5797
5798   if (OpNum == OP_COPY) {
5799     if (LHSID == (1*9+2)*9+3) return LHS;
5800     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5801     return RHS;
5802   }
5803
5804   SDValue OpLHS, OpRHS;
5805   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5806   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5807   EVT VT = OpLHS.getValueType();
5808
5809   switch (OpNum) {
5810   default: llvm_unreachable("Unknown shuffle opcode!");
5811   case OP_VREV:
5812     // VREV divides the vector in half and swaps within the half.
5813     if (VT.getVectorElementType() == MVT::i32 ||
5814         VT.getVectorElementType() == MVT::f32)
5815       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5816     // vrev <4 x i16> -> VREV32
5817     if (VT.getVectorElementType() == MVT::i16)
5818       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5819     // vrev <4 x i8> -> VREV16
5820     assert(VT.getVectorElementType() == MVT::i8);
5821     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5822   case OP_VDUP0:
5823   case OP_VDUP1:
5824   case OP_VDUP2:
5825   case OP_VDUP3:
5826     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5827                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5828   case OP_VEXT1:
5829   case OP_VEXT2:
5830   case OP_VEXT3:
5831     return DAG.getNode(ARMISD::VEXT, dl, VT,
5832                        OpLHS, OpRHS,
5833                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5834   case OP_VUZPL:
5835   case OP_VUZPR:
5836     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5837                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5838   case OP_VZIPL:
5839   case OP_VZIPR:
5840     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5841                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5842   case OP_VTRNL:
5843   case OP_VTRNR:
5844     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5845                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5846   }
5847 }
5848
5849 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5850                                        ArrayRef<int> ShuffleMask,
5851                                        SelectionDAG &DAG) {
5852   // Check to see if we can use the VTBL instruction.
5853   SDValue V1 = Op.getOperand(0);
5854   SDValue V2 = Op.getOperand(1);
5855   SDLoc DL(Op);
5856
5857   SmallVector<SDValue, 8> VTBLMask;
5858   for (ArrayRef<int>::iterator
5859          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5860     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5861
5862   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5863     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5864                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5865
5866   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5867                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5868 }
5869
5870 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5871                                                       SelectionDAG &DAG) {
5872   SDLoc DL(Op);
5873   SDValue OpLHS = Op.getOperand(0);
5874   EVT VT = OpLHS.getValueType();
5875
5876   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5877          "Expect an v8i16/v16i8 type");
5878   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5879   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5880   // extract the first 8 bytes into the top double word and the last 8 bytes
5881   // into the bottom double word. The v8i16 case is similar.
5882   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5883   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5884                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5885 }
5886
5887 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5888   SDValue V1 = Op.getOperand(0);
5889   SDValue V2 = Op.getOperand(1);
5890   SDLoc dl(Op);
5891   EVT VT = Op.getValueType();
5892   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5893
5894   // Convert shuffles that are directly supported on NEON to target-specific
5895   // DAG nodes, instead of keeping them as shuffles and matching them again
5896   // during code selection.  This is more efficient and avoids the possibility
5897   // of inconsistencies between legalization and selection.
5898   // FIXME: floating-point vectors should be canonicalized to integer vectors
5899   // of the same time so that they get CSEd properly.
5900   ArrayRef<int> ShuffleMask = SVN->getMask();
5901
5902   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5903   if (EltSize <= 32) {
5904     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5905       int Lane = SVN->getSplatIndex();
5906       // If this is undef splat, generate it via "just" vdup, if possible.
5907       if (Lane == -1) Lane = 0;
5908
5909       // Test if V1 is a SCALAR_TO_VECTOR.
5910       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5911         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5912       }
5913       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5914       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5915       // reaches it).
5916       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5917           !isa<ConstantSDNode>(V1.getOperand(0))) {
5918         bool IsScalarToVector = true;
5919         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5920           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5921             IsScalarToVector = false;
5922             break;
5923           }
5924         if (IsScalarToVector)
5925           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5926       }
5927       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5928                          DAG.getConstant(Lane, dl, MVT::i32));
5929     }
5930
5931     bool ReverseVEXT;
5932     unsigned Imm;
5933     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5934       if (ReverseVEXT)
5935         std::swap(V1, V2);
5936       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5937                          DAG.getConstant(Imm, dl, MVT::i32));
5938     }
5939
5940     if (isVREVMask(ShuffleMask, VT, 64))
5941       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5942     if (isVREVMask(ShuffleMask, VT, 32))
5943       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5944     if (isVREVMask(ShuffleMask, VT, 16))
5945       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5946
5947     if (V2->getOpcode() == ISD::UNDEF &&
5948         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5949       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5950                          DAG.getConstant(Imm, dl, MVT::i32));
5951     }
5952
5953     // Check for Neon shuffles that modify both input vectors in place.
5954     // If both results are used, i.e., if there are two shuffles with the same
5955     // source operands and with masks corresponding to both results of one of
5956     // these operations, DAG memoization will ensure that a single node is
5957     // used for both shuffles.
5958     unsigned WhichResult;
5959     bool isV_UNDEF;
5960     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5961             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5962       if (isV_UNDEF)
5963         V2 = V1;
5964       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5965           .getValue(WhichResult);
5966     }
5967
5968     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5969     // shuffles that produce a result larger than their operands with:
5970     //   shuffle(concat(v1, undef), concat(v2, undef))
5971     // ->
5972     //   shuffle(concat(v1, v2), undef)
5973     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5974     //
5975     // This is useful in the general case, but there are special cases where
5976     // native shuffles produce larger results: the two-result ops.
5977     //
5978     // Look through the concat when lowering them:
5979     //   shuffle(concat(v1, v2), undef)
5980     // ->
5981     //   concat(VZIP(v1, v2):0, :1)
5982     //
5983     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5984         V2->getOpcode() == ISD::UNDEF) {
5985       SDValue SubV1 = V1->getOperand(0);
5986       SDValue SubV2 = V1->getOperand(1);
5987       EVT SubVT = SubV1.getValueType();
5988
5989       // We expect these to have been canonicalized to -1.
5990       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5991         return i < (int)VT.getVectorNumElements();
5992       }) && "Unexpected shuffle index into UNDEF operand!");
5993
5994       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5995               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5996         if (isV_UNDEF)
5997           SubV2 = SubV1;
5998         assert((WhichResult == 0) &&
5999                "In-place shuffle of concat can only have one result!");
6000         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6001                                   SubV1, SubV2);
6002         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6003                            Res.getValue(1));
6004       }
6005     }
6006   }
6007
6008   // If the shuffle is not directly supported and it has 4 elements, use
6009   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6010   unsigned NumElts = VT.getVectorNumElements();
6011   if (NumElts == 4) {
6012     unsigned PFIndexes[4];
6013     for (unsigned i = 0; i != 4; ++i) {
6014       if (ShuffleMask[i] < 0)
6015         PFIndexes[i] = 8;
6016       else
6017         PFIndexes[i] = ShuffleMask[i];
6018     }
6019
6020     // Compute the index in the perfect shuffle table.
6021     unsigned PFTableIndex =
6022       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6023     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6024     unsigned Cost = (PFEntry >> 30);
6025
6026     if (Cost <= 4)
6027       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6028   }
6029
6030   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6031   if (EltSize >= 32) {
6032     // Do the expansion with floating-point types, since that is what the VFP
6033     // registers are defined to use, and since i64 is not legal.
6034     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6035     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6036     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6037     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6038     SmallVector<SDValue, 8> Ops;
6039     for (unsigned i = 0; i < NumElts; ++i) {
6040       if (ShuffleMask[i] < 0)
6041         Ops.push_back(DAG.getUNDEF(EltVT));
6042       else
6043         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6044                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6045                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6046                                                   dl, MVT::i32)));
6047     }
6048     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6049     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6050   }
6051
6052   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6053     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6054
6055   if (VT == MVT::v8i8) {
6056     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6057     if (NewOp.getNode())
6058       return NewOp;
6059   }
6060
6061   return SDValue();
6062 }
6063
6064 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6065   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6066   SDValue Lane = Op.getOperand(2);
6067   if (!isa<ConstantSDNode>(Lane))
6068     return SDValue();
6069
6070   return Op;
6071 }
6072
6073 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6074   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6075   SDValue Lane = Op.getOperand(1);
6076   if (!isa<ConstantSDNode>(Lane))
6077     return SDValue();
6078
6079   SDValue Vec = Op.getOperand(0);
6080   if (Op.getValueType() == MVT::i32 &&
6081       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6082     SDLoc dl(Op);
6083     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6084   }
6085
6086   return Op;
6087 }
6088
6089 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6090   // The only time a CONCAT_VECTORS operation can have legal types is when
6091   // two 64-bit vectors are concatenated to a 128-bit vector.
6092   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6093          "unexpected CONCAT_VECTORS");
6094   SDLoc dl(Op);
6095   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6096   SDValue Op0 = Op.getOperand(0);
6097   SDValue Op1 = Op.getOperand(1);
6098   if (Op0.getOpcode() != ISD::UNDEF)
6099     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6100                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6101                       DAG.getIntPtrConstant(0, dl));
6102   if (Op1.getOpcode() != ISD::UNDEF)
6103     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6104                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6105                       DAG.getIntPtrConstant(1, dl));
6106   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6107 }
6108
6109 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6110 /// element has been zero/sign-extended, depending on the isSigned parameter,
6111 /// from an integer type half its size.
6112 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6113                                    bool isSigned) {
6114   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6115   EVT VT = N->getValueType(0);
6116   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6117     SDNode *BVN = N->getOperand(0).getNode();
6118     if (BVN->getValueType(0) != MVT::v4i32 ||
6119         BVN->getOpcode() != ISD::BUILD_VECTOR)
6120       return false;
6121     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6122     unsigned HiElt = 1 - LoElt;
6123     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6124     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6125     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6126     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6127     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6128       return false;
6129     if (isSigned) {
6130       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6131           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6132         return true;
6133     } else {
6134       if (Hi0->isNullValue() && Hi1->isNullValue())
6135         return true;
6136     }
6137     return false;
6138   }
6139
6140   if (N->getOpcode() != ISD::BUILD_VECTOR)
6141     return false;
6142
6143   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6144     SDNode *Elt = N->getOperand(i).getNode();
6145     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6146       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6147       unsigned HalfSize = EltSize / 2;
6148       if (isSigned) {
6149         if (!isIntN(HalfSize, C->getSExtValue()))
6150           return false;
6151       } else {
6152         if (!isUIntN(HalfSize, C->getZExtValue()))
6153           return false;
6154       }
6155       continue;
6156     }
6157     return false;
6158   }
6159
6160   return true;
6161 }
6162
6163 /// isSignExtended - Check if a node is a vector value that is sign-extended
6164 /// or a constant BUILD_VECTOR with sign-extended elements.
6165 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6166   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6167     return true;
6168   if (isExtendedBUILD_VECTOR(N, DAG, true))
6169     return true;
6170   return false;
6171 }
6172
6173 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6174 /// or a constant BUILD_VECTOR with zero-extended elements.
6175 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6176   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6177     return true;
6178   if (isExtendedBUILD_VECTOR(N, DAG, false))
6179     return true;
6180   return false;
6181 }
6182
6183 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6184   if (OrigVT.getSizeInBits() >= 64)
6185     return OrigVT;
6186
6187   assert(OrigVT.isSimple() && "Expecting a simple value type");
6188
6189   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6190   switch (OrigSimpleTy) {
6191   default: llvm_unreachable("Unexpected Vector Type");
6192   case MVT::v2i8:
6193   case MVT::v2i16:
6194      return MVT::v2i32;
6195   case MVT::v4i8:
6196     return  MVT::v4i16;
6197   }
6198 }
6199
6200 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6201 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6202 /// We insert the required extension here to get the vector to fill a D register.
6203 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6204                                             const EVT &OrigTy,
6205                                             const EVT &ExtTy,
6206                                             unsigned ExtOpcode) {
6207   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6208   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6209   // 64-bits we need to insert a new extension so that it will be 64-bits.
6210   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6211   if (OrigTy.getSizeInBits() >= 64)
6212     return N;
6213
6214   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6215   EVT NewVT = getExtensionTo64Bits(OrigTy);
6216
6217   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6218 }
6219
6220 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6221 /// does not do any sign/zero extension. If the original vector is less
6222 /// than 64 bits, an appropriate extension will be added after the load to
6223 /// reach a total size of 64 bits. We have to add the extension separately
6224 /// because ARM does not have a sign/zero extending load for vectors.
6225 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6226   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6227
6228   // The load already has the right type.
6229   if (ExtendedTy == LD->getMemoryVT())
6230     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6231                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6232                 LD->isNonTemporal(), LD->isInvariant(),
6233                 LD->getAlignment());
6234
6235   // We need to create a zextload/sextload. We cannot just create a load
6236   // followed by a zext/zext node because LowerMUL is also run during normal
6237   // operation legalization where we can't create illegal types.
6238   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6239                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6240                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6241                         LD->isNonTemporal(), LD->getAlignment());
6242 }
6243
6244 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6245 /// extending load, or BUILD_VECTOR with extended elements, return the
6246 /// unextended value. The unextended vector should be 64 bits so that it can
6247 /// be used as an operand to a VMULL instruction. If the original vector size
6248 /// before extension is less than 64 bits we add a an extension to resize
6249 /// the vector to 64 bits.
6250 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6251   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6252     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6253                                         N->getOperand(0)->getValueType(0),
6254                                         N->getValueType(0),
6255                                         N->getOpcode());
6256
6257   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6258     return SkipLoadExtensionForVMULL(LD, DAG);
6259
6260   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6261   // have been legalized as a BITCAST from v4i32.
6262   if (N->getOpcode() == ISD::BITCAST) {
6263     SDNode *BVN = N->getOperand(0).getNode();
6264     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6265            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6266     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6267     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6268                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6269   }
6270   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6271   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6272   EVT VT = N->getValueType(0);
6273   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6274   unsigned NumElts = VT.getVectorNumElements();
6275   MVT TruncVT = MVT::getIntegerVT(EltSize);
6276   SmallVector<SDValue, 8> Ops;
6277   SDLoc dl(N);
6278   for (unsigned i = 0; i != NumElts; ++i) {
6279     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6280     const APInt &CInt = C->getAPIntValue();
6281     // Element types smaller than 32 bits are not legal, so use i32 elements.
6282     // The values are implicitly truncated so sext vs. zext doesn't matter.
6283     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6284   }
6285   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6286                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6287 }
6288
6289 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6290   unsigned Opcode = N->getOpcode();
6291   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6292     SDNode *N0 = N->getOperand(0).getNode();
6293     SDNode *N1 = N->getOperand(1).getNode();
6294     return N0->hasOneUse() && N1->hasOneUse() &&
6295       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6296   }
6297   return false;
6298 }
6299
6300 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6301   unsigned Opcode = N->getOpcode();
6302   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6303     SDNode *N0 = N->getOperand(0).getNode();
6304     SDNode *N1 = N->getOperand(1).getNode();
6305     return N0->hasOneUse() && N1->hasOneUse() &&
6306       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6307   }
6308   return false;
6309 }
6310
6311 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6312   // Multiplications are only custom-lowered for 128-bit vectors so that
6313   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6314   EVT VT = Op.getValueType();
6315   assert(VT.is128BitVector() && VT.isInteger() &&
6316          "unexpected type for custom-lowering ISD::MUL");
6317   SDNode *N0 = Op.getOperand(0).getNode();
6318   SDNode *N1 = Op.getOperand(1).getNode();
6319   unsigned NewOpc = 0;
6320   bool isMLA = false;
6321   bool isN0SExt = isSignExtended(N0, DAG);
6322   bool isN1SExt = isSignExtended(N1, DAG);
6323   if (isN0SExt && isN1SExt)
6324     NewOpc = ARMISD::VMULLs;
6325   else {
6326     bool isN0ZExt = isZeroExtended(N0, DAG);
6327     bool isN1ZExt = isZeroExtended(N1, DAG);
6328     if (isN0ZExt && isN1ZExt)
6329       NewOpc = ARMISD::VMULLu;
6330     else if (isN1SExt || isN1ZExt) {
6331       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6332       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6333       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6334         NewOpc = ARMISD::VMULLs;
6335         isMLA = true;
6336       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6337         NewOpc = ARMISD::VMULLu;
6338         isMLA = true;
6339       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6340         std::swap(N0, N1);
6341         NewOpc = ARMISD::VMULLu;
6342         isMLA = true;
6343       }
6344     }
6345
6346     if (!NewOpc) {
6347       if (VT == MVT::v2i64)
6348         // Fall through to expand this.  It is not legal.
6349         return SDValue();
6350       else
6351         // Other vector multiplications are legal.
6352         return Op;
6353     }
6354   }
6355
6356   // Legalize to a VMULL instruction.
6357   SDLoc DL(Op);
6358   SDValue Op0;
6359   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6360   if (!isMLA) {
6361     Op0 = SkipExtensionForVMULL(N0, DAG);
6362     assert(Op0.getValueType().is64BitVector() &&
6363            Op1.getValueType().is64BitVector() &&
6364            "unexpected types for extended operands to VMULL");
6365     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6366   }
6367
6368   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6369   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6370   //   vmull q0, d4, d6
6371   //   vmlal q0, d5, d6
6372   // is faster than
6373   //   vaddl q0, d4, d5
6374   //   vmovl q1, d6
6375   //   vmul  q0, q0, q1
6376   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6377   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6378   EVT Op1VT = Op1.getValueType();
6379   return DAG.getNode(N0->getOpcode(), DL, VT,
6380                      DAG.getNode(NewOpc, DL, VT,
6381                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6382                      DAG.getNode(NewOpc, DL, VT,
6383                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6384 }
6385
6386 static SDValue
6387 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6388   // Convert to float
6389   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6390   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6391   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6392   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6393   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6394   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6395   // Get reciprocal estimate.
6396   // float4 recip = vrecpeq_f32(yf);
6397   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6398                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6399                    Y);
6400   // Because char has a smaller range than uchar, we can actually get away
6401   // without any newton steps.  This requires that we use a weird bias
6402   // of 0xb000, however (again, this has been exhaustively tested).
6403   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6404   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6405   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6406   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6407   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6408   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6409   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6410   // Convert back to short.
6411   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6412   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6413   return X;
6414 }
6415
6416 static SDValue
6417 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6418   SDValue N2;
6419   // Convert to float.
6420   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6421   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6422   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6423   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6424   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6425   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6426
6427   // Use reciprocal estimate and one refinement step.
6428   // float4 recip = vrecpeq_f32(yf);
6429   // recip *= vrecpsq_f32(yf, recip);
6430   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6431                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6432                    N1);
6433   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6434                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6435                    N1, N2);
6436   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6437   // Because short has a smaller range than ushort, we can actually get away
6438   // with only a single newton step.  This requires that we use a weird bias
6439   // of 89, however (again, this has been exhaustively tested).
6440   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6441   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6442   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6443   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6444   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6445   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6446   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6447   // Convert back to integer and return.
6448   // return vmovn_s32(vcvt_s32_f32(result));
6449   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6450   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6451   return N0;
6452 }
6453
6454 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6455   EVT VT = Op.getValueType();
6456   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6457          "unexpected type for custom-lowering ISD::SDIV");
6458
6459   SDLoc dl(Op);
6460   SDValue N0 = Op.getOperand(0);
6461   SDValue N1 = Op.getOperand(1);
6462   SDValue N2, N3;
6463
6464   if (VT == MVT::v8i8) {
6465     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6466     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6467
6468     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6469                      DAG.getIntPtrConstant(4, dl));
6470     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6471                      DAG.getIntPtrConstant(4, dl));
6472     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6473                      DAG.getIntPtrConstant(0, dl));
6474     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6475                      DAG.getIntPtrConstant(0, dl));
6476
6477     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6478     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6479
6480     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6481     N0 = LowerCONCAT_VECTORS(N0, DAG);
6482
6483     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6484     return N0;
6485   }
6486   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6487 }
6488
6489 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6490   EVT VT = Op.getValueType();
6491   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6492          "unexpected type for custom-lowering ISD::UDIV");
6493
6494   SDLoc dl(Op);
6495   SDValue N0 = Op.getOperand(0);
6496   SDValue N1 = Op.getOperand(1);
6497   SDValue N2, N3;
6498
6499   if (VT == MVT::v8i8) {
6500     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6501     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6502
6503     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6504                      DAG.getIntPtrConstant(4, dl));
6505     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6506                      DAG.getIntPtrConstant(4, dl));
6507     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6508                      DAG.getIntPtrConstant(0, dl));
6509     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6510                      DAG.getIntPtrConstant(0, dl));
6511
6512     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6513     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6514
6515     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6516     N0 = LowerCONCAT_VECTORS(N0, DAG);
6517
6518     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6519                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6520                                      MVT::i32),
6521                      N0);
6522     return N0;
6523   }
6524
6525   // v4i16 sdiv ... Convert to float.
6526   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6527   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6528   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6529   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6530   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6531   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6532
6533   // Use reciprocal estimate and two refinement steps.
6534   // float4 recip = vrecpeq_f32(yf);
6535   // recip *= vrecpsq_f32(yf, recip);
6536   // recip *= vrecpsq_f32(yf, recip);
6537   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6538                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6539                    BN1);
6540   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6541                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6542                    BN1, N2);
6543   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6544   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6545                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6546                    BN1, N2);
6547   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6548   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6549   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6550   // and that it will never cause us to return an answer too large).
6551   // float4 result = as_float4(as_int4(xf*recip) + 2);
6552   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6553   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6554   N1 = DAG.getConstant(2, dl, MVT::i32);
6555   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6556   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6557   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6558   // Convert back to integer and return.
6559   // return vmovn_u32(vcvt_s32_f32(result));
6560   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6561   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6562   return N0;
6563 }
6564
6565 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6566   EVT VT = Op.getNode()->getValueType(0);
6567   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6568
6569   unsigned Opc;
6570   bool ExtraOp = false;
6571   switch (Op.getOpcode()) {
6572   default: llvm_unreachable("Invalid code");
6573   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6574   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6575   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6576   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6577   }
6578
6579   if (!ExtraOp)
6580     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6581                        Op.getOperand(1));
6582   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6583                      Op.getOperand(1), Op.getOperand(2));
6584 }
6585
6586 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6587   assert(Subtarget->isTargetDarwin());
6588
6589   // For iOS, we want to call an alternative entry point: __sincos_stret,
6590   // return values are passed via sret.
6591   SDLoc dl(Op);
6592   SDValue Arg = Op.getOperand(0);
6593   EVT ArgVT = Arg.getValueType();
6594   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6595   auto PtrVT = getPointerTy(DAG.getDataLayout());
6596
6597   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6598
6599   // Pair of floats / doubles used to pass the result.
6600   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6601
6602   // Create stack object for sret.
6603   auto &DL = DAG.getDataLayout();
6604   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6605   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6606   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6607   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6608
6609   ArgListTy Args;
6610   ArgListEntry Entry;
6611
6612   Entry.Node = SRet;
6613   Entry.Ty = RetTy->getPointerTo();
6614   Entry.isSExt = false;
6615   Entry.isZExt = false;
6616   Entry.isSRet = true;
6617   Args.push_back(Entry);
6618
6619   Entry.Node = Arg;
6620   Entry.Ty = ArgTy;
6621   Entry.isSExt = false;
6622   Entry.isZExt = false;
6623   Args.push_back(Entry);
6624
6625   const char *LibcallName  = (ArgVT == MVT::f64)
6626   ? "__sincos_stret" : "__sincosf_stret";
6627   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6628
6629   TargetLowering::CallLoweringInfo CLI(DAG);
6630   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6631     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6632                std::move(Args), 0)
6633     .setDiscardResult();
6634
6635   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6636
6637   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6638                                 MachinePointerInfo(), false, false, false, 0);
6639
6640   // Address of cos field.
6641   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6642                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6643   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6644                                 MachinePointerInfo(), false, false, false, 0);
6645
6646   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6647   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6648                      LoadSin.getValue(0), LoadCos.getValue(0));
6649 }
6650
6651 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6652   // Monotonic load/store is legal for all targets
6653   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6654     return Op;
6655
6656   // Acquire/Release load/store is not legal for targets without a
6657   // dmb or equivalent available.
6658   return SDValue();
6659 }
6660
6661 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6662                                     SmallVectorImpl<SDValue> &Results,
6663                                     SelectionDAG &DAG,
6664                                     const ARMSubtarget *Subtarget) {
6665   SDLoc DL(N);
6666   // Under Power Management extensions, the cycle-count is:
6667   //    mrc p15, #0, <Rt>, c9, c13, #0
6668   SDValue Ops[] = { N->getOperand(0), // Chain
6669                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6670                     DAG.getConstant(15, DL, MVT::i32),
6671                     DAG.getConstant(0, DL, MVT::i32),
6672                     DAG.getConstant(9, DL, MVT::i32),
6673                     DAG.getConstant(13, DL, MVT::i32),
6674                     DAG.getConstant(0, DL, MVT::i32)
6675   };
6676
6677   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6678                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6679   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6680                                 DAG.getConstant(0, DL, MVT::i32)));
6681   Results.push_back(Cycles32.getValue(1));
6682 }
6683
6684 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6685   switch (Op.getOpcode()) {
6686   default: llvm_unreachable("Don't know how to custom lower this!");
6687   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6688   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6689   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6690   case ISD::GlobalAddress:
6691     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6692     default: llvm_unreachable("unknown object format");
6693     case Triple::COFF:
6694       return LowerGlobalAddressWindows(Op, DAG);
6695     case Triple::ELF:
6696       return LowerGlobalAddressELF(Op, DAG);
6697     case Triple::MachO:
6698       return LowerGlobalAddressDarwin(Op, DAG);
6699     }
6700   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6701   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6702   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6703   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6704   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6705   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6706   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6707   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6708   case ISD::SINT_TO_FP:
6709   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6710   case ISD::FP_TO_SINT:
6711   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6712   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6713   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6714   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6715   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6716   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6717   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6718   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6719   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6720                                                                Subtarget);
6721   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6722   case ISD::SHL:
6723   case ISD::SRL:
6724   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6725   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6726   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6727   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6728   case ISD::SRL_PARTS:
6729   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6730   case ISD::CTTZ:
6731   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6732   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6733   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6734   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6735   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6736   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6737   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6738   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6739   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6740   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6741   case ISD::MUL:           return LowerMUL(Op, DAG);
6742   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6743   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6744   case ISD::ADDC:
6745   case ISD::ADDE:
6746   case ISD::SUBC:
6747   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6748   case ISD::SADDO:
6749   case ISD::UADDO:
6750   case ISD::SSUBO:
6751   case ISD::USUBO:
6752     return LowerXALUO(Op, DAG);
6753   case ISD::ATOMIC_LOAD:
6754   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6755   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6756   case ISD::SDIVREM:
6757   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6758   case ISD::DYNAMIC_STACKALLOC:
6759     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6760       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6761     llvm_unreachable("Don't know how to custom lower this!");
6762   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6763   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6764   }
6765 }
6766
6767 /// ReplaceNodeResults - Replace the results of node with an illegal result
6768 /// type with new values built out of custom code.
6769 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6770                                            SmallVectorImpl<SDValue>&Results,
6771                                            SelectionDAG &DAG) const {
6772   SDValue Res;
6773   switch (N->getOpcode()) {
6774   default:
6775     llvm_unreachable("Don't know how to custom expand this!");
6776   case ISD::READ_REGISTER:
6777     ExpandREAD_REGISTER(N, Results, DAG);
6778     break;
6779   case ISD::BITCAST:
6780     Res = ExpandBITCAST(N, DAG);
6781     break;
6782   case ISD::SRL:
6783   case ISD::SRA:
6784     Res = Expand64BitShift(N, DAG, Subtarget);
6785     break;
6786   case ISD::SREM:
6787   case ISD::UREM:
6788     Res = LowerREM(N, DAG);
6789     break;
6790   case ISD::READCYCLECOUNTER:
6791     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6792     return;
6793   }
6794   if (Res.getNode())
6795     Results.push_back(Res);
6796 }
6797
6798 //===----------------------------------------------------------------------===//
6799 //                           ARM Scheduler Hooks
6800 //===----------------------------------------------------------------------===//
6801
6802 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6803 /// registers the function context.
6804 void ARMTargetLowering::
6805 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6806                        MachineBasicBlock *DispatchBB, int FI) const {
6807   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6808   DebugLoc dl = MI->getDebugLoc();
6809   MachineFunction *MF = MBB->getParent();
6810   MachineRegisterInfo *MRI = &MF->getRegInfo();
6811   MachineConstantPool *MCP = MF->getConstantPool();
6812   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6813   const Function *F = MF->getFunction();
6814
6815   bool isThumb = Subtarget->isThumb();
6816   bool isThumb2 = Subtarget->isThumb2();
6817
6818   unsigned PCLabelId = AFI->createPICLabelUId();
6819   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6820   ARMConstantPoolValue *CPV =
6821     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6822   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6823
6824   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6825                                            : &ARM::GPRRegClass;
6826
6827   // Grab constant pool and fixed stack memory operands.
6828   MachineMemOperand *CPMMO =
6829       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6830                                MachineMemOperand::MOLoad, 4, 4);
6831
6832   MachineMemOperand *FIMMOSt =
6833       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6834                                MachineMemOperand::MOStore, 4, 4);
6835
6836   // Load the address of the dispatch MBB into the jump buffer.
6837   if (isThumb2) {
6838     // Incoming value: jbuf
6839     //   ldr.n  r5, LCPI1_1
6840     //   orr    r5, r5, #1
6841     //   add    r5, pc
6842     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6843     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6844     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6845                    .addConstantPoolIndex(CPI)
6846                    .addMemOperand(CPMMO));
6847     // Set the low bit because of thumb mode.
6848     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6849     AddDefaultCC(
6850       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6851                      .addReg(NewVReg1, RegState::Kill)
6852                      .addImm(0x01)));
6853     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6854     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6855       .addReg(NewVReg2, RegState::Kill)
6856       .addImm(PCLabelId);
6857     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6858                    .addReg(NewVReg3, RegState::Kill)
6859                    .addFrameIndex(FI)
6860                    .addImm(36)  // &jbuf[1] :: pc
6861                    .addMemOperand(FIMMOSt));
6862   } else if (isThumb) {
6863     // Incoming value: jbuf
6864     //   ldr.n  r1, LCPI1_4
6865     //   add    r1, pc
6866     //   mov    r2, #1
6867     //   orrs   r1, r2
6868     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6869     //   str    r1, [r2]
6870     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6871     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6872                    .addConstantPoolIndex(CPI)
6873                    .addMemOperand(CPMMO));
6874     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6875     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6876       .addReg(NewVReg1, RegState::Kill)
6877       .addImm(PCLabelId);
6878     // Set the low bit because of thumb mode.
6879     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6880     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6881                    .addReg(ARM::CPSR, RegState::Define)
6882                    .addImm(1));
6883     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6884     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6885                    .addReg(ARM::CPSR, RegState::Define)
6886                    .addReg(NewVReg2, RegState::Kill)
6887                    .addReg(NewVReg3, RegState::Kill));
6888     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6889     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6890             .addFrameIndex(FI)
6891             .addImm(36); // &jbuf[1] :: pc
6892     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6893                    .addReg(NewVReg4, RegState::Kill)
6894                    .addReg(NewVReg5, RegState::Kill)
6895                    .addImm(0)
6896                    .addMemOperand(FIMMOSt));
6897   } else {
6898     // Incoming value: jbuf
6899     //   ldr  r1, LCPI1_1
6900     //   add  r1, pc, r1
6901     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6902     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6903     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6904                    .addConstantPoolIndex(CPI)
6905                    .addImm(0)
6906                    .addMemOperand(CPMMO));
6907     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6908     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6909                    .addReg(NewVReg1, RegState::Kill)
6910                    .addImm(PCLabelId));
6911     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6912                    .addReg(NewVReg2, RegState::Kill)
6913                    .addFrameIndex(FI)
6914                    .addImm(36)  // &jbuf[1] :: pc
6915                    .addMemOperand(FIMMOSt));
6916   }
6917 }
6918
6919 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6920                                               MachineBasicBlock *MBB) const {
6921   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6922   DebugLoc dl = MI->getDebugLoc();
6923   MachineFunction *MF = MBB->getParent();
6924   MachineRegisterInfo *MRI = &MF->getRegInfo();
6925   MachineFrameInfo *MFI = MF->getFrameInfo();
6926   int FI = MFI->getFunctionContextIndex();
6927
6928   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6929                                                         : &ARM::GPRnopcRegClass;
6930
6931   // Get a mapping of the call site numbers to all of the landing pads they're
6932   // associated with.
6933   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6934   unsigned MaxCSNum = 0;
6935   MachineModuleInfo &MMI = MF->getMMI();
6936   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6937        ++BB) {
6938     if (!BB->isEHPad()) continue;
6939
6940     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6941     // pad.
6942     for (MachineBasicBlock::iterator
6943            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6944       if (!II->isEHLabel()) continue;
6945
6946       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6947       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6948
6949       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6950       for (SmallVectorImpl<unsigned>::iterator
6951              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6952            CSI != CSE; ++CSI) {
6953         CallSiteNumToLPad[*CSI].push_back(BB);
6954         MaxCSNum = std::max(MaxCSNum, *CSI);
6955       }
6956       break;
6957     }
6958   }
6959
6960   // Get an ordered list of the machine basic blocks for the jump table.
6961   std::vector<MachineBasicBlock*> LPadList;
6962   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6963   LPadList.reserve(CallSiteNumToLPad.size());
6964   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6965     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6966     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6967            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6968       LPadList.push_back(*II);
6969       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6970     }
6971   }
6972
6973   assert(!LPadList.empty() &&
6974          "No landing pad destinations for the dispatch jump table!");
6975
6976   // Create the jump table and associated information.
6977   MachineJumpTableInfo *JTI =
6978     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6979   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6980   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6981
6982   // Create the MBBs for the dispatch code.
6983
6984   // Shove the dispatch's address into the return slot in the function context.
6985   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6986   DispatchBB->setIsEHPad();
6987
6988   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6989   unsigned trap_opcode;
6990   if (Subtarget->isThumb())
6991     trap_opcode = ARM::tTRAP;
6992   else
6993     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6994
6995   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6996   DispatchBB->addSuccessor(TrapBB);
6997
6998   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6999   DispatchBB->addSuccessor(DispContBB);
7000
7001   // Insert and MBBs.
7002   MF->insert(MF->end(), DispatchBB);
7003   MF->insert(MF->end(), DispContBB);
7004   MF->insert(MF->end(), TrapBB);
7005
7006   // Insert code into the entry block that creates and registers the function
7007   // context.
7008   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7009
7010   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7011       MachinePointerInfo::getFixedStack(*MF, FI),
7012       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7013
7014   MachineInstrBuilder MIB;
7015   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7016
7017   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7018   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7019
7020   // Add a register mask with no preserved registers.  This results in all
7021   // registers being marked as clobbered.
7022   MIB.addRegMask(RI.getNoPreservedMask());
7023
7024   unsigned NumLPads = LPadList.size();
7025   if (Subtarget->isThumb2()) {
7026     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7027     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7028                    .addFrameIndex(FI)
7029                    .addImm(4)
7030                    .addMemOperand(FIMMOLd));
7031
7032     if (NumLPads < 256) {
7033       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7034                      .addReg(NewVReg1)
7035                      .addImm(LPadList.size()));
7036     } else {
7037       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7038       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7039                      .addImm(NumLPads & 0xFFFF));
7040
7041       unsigned VReg2 = VReg1;
7042       if ((NumLPads & 0xFFFF0000) != 0) {
7043         VReg2 = MRI->createVirtualRegister(TRC);
7044         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7045                        .addReg(VReg1)
7046                        .addImm(NumLPads >> 16));
7047       }
7048
7049       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7050                      .addReg(NewVReg1)
7051                      .addReg(VReg2));
7052     }
7053
7054     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7055       .addMBB(TrapBB)
7056       .addImm(ARMCC::HI)
7057       .addReg(ARM::CPSR);
7058
7059     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7060     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7061                    .addJumpTableIndex(MJTI));
7062
7063     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7064     AddDefaultCC(
7065       AddDefaultPred(
7066         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7067         .addReg(NewVReg3, RegState::Kill)
7068         .addReg(NewVReg1)
7069         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7070
7071     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7072       .addReg(NewVReg4, RegState::Kill)
7073       .addReg(NewVReg1)
7074       .addJumpTableIndex(MJTI);
7075   } else if (Subtarget->isThumb()) {
7076     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7077     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7078                    .addFrameIndex(FI)
7079                    .addImm(1)
7080                    .addMemOperand(FIMMOLd));
7081
7082     if (NumLPads < 256) {
7083       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7084                      .addReg(NewVReg1)
7085                      .addImm(NumLPads));
7086     } else {
7087       MachineConstantPool *ConstantPool = MF->getConstantPool();
7088       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7089       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7090
7091       // MachineConstantPool wants an explicit alignment.
7092       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7093       if (Align == 0)
7094         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7095       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7096
7097       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7098       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7099                      .addReg(VReg1, RegState::Define)
7100                      .addConstantPoolIndex(Idx));
7101       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7102                      .addReg(NewVReg1)
7103                      .addReg(VReg1));
7104     }
7105
7106     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7107       .addMBB(TrapBB)
7108       .addImm(ARMCC::HI)
7109       .addReg(ARM::CPSR);
7110
7111     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7112     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7113                    .addReg(ARM::CPSR, RegState::Define)
7114                    .addReg(NewVReg1)
7115                    .addImm(2));
7116
7117     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7118     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7119                    .addJumpTableIndex(MJTI));
7120
7121     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7122     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7123                    .addReg(ARM::CPSR, RegState::Define)
7124                    .addReg(NewVReg2, RegState::Kill)
7125                    .addReg(NewVReg3));
7126
7127     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7128         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7129
7130     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7131     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7132                    .addReg(NewVReg4, RegState::Kill)
7133                    .addImm(0)
7134                    .addMemOperand(JTMMOLd));
7135
7136     unsigned NewVReg6 = NewVReg5;
7137     if (RelocM == Reloc::PIC_) {
7138       NewVReg6 = MRI->createVirtualRegister(TRC);
7139       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7140                      .addReg(ARM::CPSR, RegState::Define)
7141                      .addReg(NewVReg5, RegState::Kill)
7142                      .addReg(NewVReg3));
7143     }
7144
7145     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7146       .addReg(NewVReg6, RegState::Kill)
7147       .addJumpTableIndex(MJTI);
7148   } else {
7149     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7150     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7151                    .addFrameIndex(FI)
7152                    .addImm(4)
7153                    .addMemOperand(FIMMOLd));
7154
7155     if (NumLPads < 256) {
7156       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7157                      .addReg(NewVReg1)
7158                      .addImm(NumLPads));
7159     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7160       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7161       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7162                      .addImm(NumLPads & 0xFFFF));
7163
7164       unsigned VReg2 = VReg1;
7165       if ((NumLPads & 0xFFFF0000) != 0) {
7166         VReg2 = MRI->createVirtualRegister(TRC);
7167         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7168                        .addReg(VReg1)
7169                        .addImm(NumLPads >> 16));
7170       }
7171
7172       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7173                      .addReg(NewVReg1)
7174                      .addReg(VReg2));
7175     } else {
7176       MachineConstantPool *ConstantPool = MF->getConstantPool();
7177       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7178       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7179
7180       // MachineConstantPool wants an explicit alignment.
7181       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7182       if (Align == 0)
7183         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7184       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7185
7186       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7187       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7188                      .addReg(VReg1, RegState::Define)
7189                      .addConstantPoolIndex(Idx)
7190                      .addImm(0));
7191       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7192                      .addReg(NewVReg1)
7193                      .addReg(VReg1, RegState::Kill));
7194     }
7195
7196     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7197       .addMBB(TrapBB)
7198       .addImm(ARMCC::HI)
7199       .addReg(ARM::CPSR);
7200
7201     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7202     AddDefaultCC(
7203       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7204                      .addReg(NewVReg1)
7205                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7206     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7207     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7208                    .addJumpTableIndex(MJTI));
7209
7210     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7211         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7212     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7213     AddDefaultPred(
7214       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7215       .addReg(NewVReg3, RegState::Kill)
7216       .addReg(NewVReg4)
7217       .addImm(0)
7218       .addMemOperand(JTMMOLd));
7219
7220     if (RelocM == Reloc::PIC_) {
7221       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7222         .addReg(NewVReg5, RegState::Kill)
7223         .addReg(NewVReg4)
7224         .addJumpTableIndex(MJTI);
7225     } else {
7226       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7227         .addReg(NewVReg5, RegState::Kill)
7228         .addJumpTableIndex(MJTI);
7229     }
7230   }
7231
7232   // Add the jump table entries as successors to the MBB.
7233   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7234   for (std::vector<MachineBasicBlock*>::iterator
7235          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7236     MachineBasicBlock *CurMBB = *I;
7237     if (SeenMBBs.insert(CurMBB).second)
7238       DispContBB->addSuccessor(CurMBB);
7239   }
7240
7241   // N.B. the order the invoke BBs are processed in doesn't matter here.
7242   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7243   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7244   for (MachineBasicBlock *BB : InvokeBBs) {
7245
7246     // Remove the landing pad successor from the invoke block and replace it
7247     // with the new dispatch block.
7248     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7249                                                   BB->succ_end());
7250     while (!Successors.empty()) {
7251       MachineBasicBlock *SMBB = Successors.pop_back_val();
7252       if (SMBB->isEHPad()) {
7253         BB->removeSuccessor(SMBB);
7254         MBBLPads.push_back(SMBB);
7255       }
7256     }
7257
7258     BB->addSuccessor(DispatchBB);
7259
7260     // Find the invoke call and mark all of the callee-saved registers as
7261     // 'implicit defined' so that they're spilled. This prevents code from
7262     // moving instructions to before the EH block, where they will never be
7263     // executed.
7264     for (MachineBasicBlock::reverse_iterator
7265            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7266       if (!II->isCall()) continue;
7267
7268       DenseMap<unsigned, bool> DefRegs;
7269       for (MachineInstr::mop_iterator
7270              OI = II->operands_begin(), OE = II->operands_end();
7271            OI != OE; ++OI) {
7272         if (!OI->isReg()) continue;
7273         DefRegs[OI->getReg()] = true;
7274       }
7275
7276       MachineInstrBuilder MIB(*MF, &*II);
7277
7278       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7279         unsigned Reg = SavedRegs[i];
7280         if (Subtarget->isThumb2() &&
7281             !ARM::tGPRRegClass.contains(Reg) &&
7282             !ARM::hGPRRegClass.contains(Reg))
7283           continue;
7284         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7285           continue;
7286         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7287           continue;
7288         if (!DefRegs[Reg])
7289           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7290       }
7291
7292       break;
7293     }
7294   }
7295
7296   // Mark all former landing pads as non-landing pads. The dispatch is the only
7297   // landing pad now.
7298   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7299          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7300     (*I)->setIsEHPad(false);
7301
7302   // The instruction is gone now.
7303   MI->eraseFromParent();
7304 }
7305
7306 static
7307 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7308   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7309        E = MBB->succ_end(); I != E; ++I)
7310     if (*I != Succ)
7311       return *I;
7312   llvm_unreachable("Expecting a BB with two successors!");
7313 }
7314
7315 /// Return the load opcode for a given load size. If load size >= 8,
7316 /// neon opcode will be returned.
7317 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7318   if (LdSize >= 8)
7319     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7320                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7321   if (IsThumb1)
7322     return LdSize == 4 ? ARM::tLDRi
7323                        : LdSize == 2 ? ARM::tLDRHi
7324                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7325   if (IsThumb2)
7326     return LdSize == 4 ? ARM::t2LDR_POST
7327                        : LdSize == 2 ? ARM::t2LDRH_POST
7328                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7329   return LdSize == 4 ? ARM::LDR_POST_IMM
7330                      : LdSize == 2 ? ARM::LDRH_POST
7331                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7332 }
7333
7334 /// Return the store opcode for a given store size. If store size >= 8,
7335 /// neon opcode will be returned.
7336 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7337   if (StSize >= 8)
7338     return StSize == 16 ? ARM::VST1q32wb_fixed
7339                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7340   if (IsThumb1)
7341     return StSize == 4 ? ARM::tSTRi
7342                        : StSize == 2 ? ARM::tSTRHi
7343                                      : StSize == 1 ? ARM::tSTRBi : 0;
7344   if (IsThumb2)
7345     return StSize == 4 ? ARM::t2STR_POST
7346                        : StSize == 2 ? ARM::t2STRH_POST
7347                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7348   return StSize == 4 ? ARM::STR_POST_IMM
7349                      : StSize == 2 ? ARM::STRH_POST
7350                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7351 }
7352
7353 /// Emit a post-increment load operation with given size. The instructions
7354 /// will be added to BB at Pos.
7355 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7356                        const TargetInstrInfo *TII, DebugLoc dl,
7357                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7358                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7359   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7360   assert(LdOpc != 0 && "Should have a load opcode");
7361   if (LdSize >= 8) {
7362     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7363                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7364                        .addImm(0));
7365   } else if (IsThumb1) {
7366     // load + update AddrIn
7367     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7368                        .addReg(AddrIn).addImm(0));
7369     MachineInstrBuilder MIB =
7370         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7371     MIB = AddDefaultT1CC(MIB);
7372     MIB.addReg(AddrIn).addImm(LdSize);
7373     AddDefaultPred(MIB);
7374   } else if (IsThumb2) {
7375     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7376                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7377                        .addImm(LdSize));
7378   } else { // arm
7379     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7380                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7381                        .addReg(0).addImm(LdSize));
7382   }
7383 }
7384
7385 /// Emit a post-increment store operation with given size. The instructions
7386 /// will be added to BB at Pos.
7387 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7388                        const TargetInstrInfo *TII, DebugLoc dl,
7389                        unsigned StSize, unsigned Data, unsigned AddrIn,
7390                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7391   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7392   assert(StOpc != 0 && "Should have a store opcode");
7393   if (StSize >= 8) {
7394     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7395                        .addReg(AddrIn).addImm(0).addReg(Data));
7396   } else if (IsThumb1) {
7397     // store + update AddrIn
7398     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7399                        .addReg(AddrIn).addImm(0));
7400     MachineInstrBuilder MIB =
7401         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7402     MIB = AddDefaultT1CC(MIB);
7403     MIB.addReg(AddrIn).addImm(StSize);
7404     AddDefaultPred(MIB);
7405   } else if (IsThumb2) {
7406     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7407                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7408   } else { // arm
7409     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7410                        .addReg(Data).addReg(AddrIn).addReg(0)
7411                        .addImm(StSize));
7412   }
7413 }
7414
7415 MachineBasicBlock *
7416 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7417                                    MachineBasicBlock *BB) const {
7418   // This pseudo instruction has 3 operands: dst, src, size
7419   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7420   // Otherwise, we will generate unrolled scalar copies.
7421   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7422   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7423   MachineFunction::iterator It = BB;
7424   ++It;
7425
7426   unsigned dest = MI->getOperand(0).getReg();
7427   unsigned src = MI->getOperand(1).getReg();
7428   unsigned SizeVal = MI->getOperand(2).getImm();
7429   unsigned Align = MI->getOperand(3).getImm();
7430   DebugLoc dl = MI->getDebugLoc();
7431
7432   MachineFunction *MF = BB->getParent();
7433   MachineRegisterInfo &MRI = MF->getRegInfo();
7434   unsigned UnitSize = 0;
7435   const TargetRegisterClass *TRC = nullptr;
7436   const TargetRegisterClass *VecTRC = nullptr;
7437
7438   bool IsThumb1 = Subtarget->isThumb1Only();
7439   bool IsThumb2 = Subtarget->isThumb2();
7440
7441   if (Align & 1) {
7442     UnitSize = 1;
7443   } else if (Align & 2) {
7444     UnitSize = 2;
7445   } else {
7446     // Check whether we can use NEON instructions.
7447     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7448         Subtarget->hasNEON()) {
7449       if ((Align % 16 == 0) && SizeVal >= 16)
7450         UnitSize = 16;
7451       else if ((Align % 8 == 0) && SizeVal >= 8)
7452         UnitSize = 8;
7453     }
7454     // Can't use NEON instructions.
7455     if (UnitSize == 0)
7456       UnitSize = 4;
7457   }
7458
7459   // Select the correct opcode and register class for unit size load/store
7460   bool IsNeon = UnitSize >= 8;
7461   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7462   if (IsNeon)
7463     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7464                             : UnitSize == 8 ? &ARM::DPRRegClass
7465                                             : nullptr;
7466
7467   unsigned BytesLeft = SizeVal % UnitSize;
7468   unsigned LoopSize = SizeVal - BytesLeft;
7469
7470   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7471     // Use LDR and STR to copy.
7472     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7473     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7474     unsigned srcIn = src;
7475     unsigned destIn = dest;
7476     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7477       unsigned srcOut = MRI.createVirtualRegister(TRC);
7478       unsigned destOut = MRI.createVirtualRegister(TRC);
7479       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7480       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7481                  IsThumb1, IsThumb2);
7482       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7483                  IsThumb1, IsThumb2);
7484       srcIn = srcOut;
7485       destIn = destOut;
7486     }
7487
7488     // Handle the leftover bytes with LDRB and STRB.
7489     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7490     // [destOut] = STRB_POST(scratch, destIn, 1)
7491     for (unsigned i = 0; i < BytesLeft; i++) {
7492       unsigned srcOut = MRI.createVirtualRegister(TRC);
7493       unsigned destOut = MRI.createVirtualRegister(TRC);
7494       unsigned scratch = MRI.createVirtualRegister(TRC);
7495       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7496                  IsThumb1, IsThumb2);
7497       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7498                  IsThumb1, IsThumb2);
7499       srcIn = srcOut;
7500       destIn = destOut;
7501     }
7502     MI->eraseFromParent();   // The instruction is gone now.
7503     return BB;
7504   }
7505
7506   // Expand the pseudo op to a loop.
7507   // thisMBB:
7508   //   ...
7509   //   movw varEnd, # --> with thumb2
7510   //   movt varEnd, #
7511   //   ldrcp varEnd, idx --> without thumb2
7512   //   fallthrough --> loopMBB
7513   // loopMBB:
7514   //   PHI varPhi, varEnd, varLoop
7515   //   PHI srcPhi, src, srcLoop
7516   //   PHI destPhi, dst, destLoop
7517   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7518   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7519   //   subs varLoop, varPhi, #UnitSize
7520   //   bne loopMBB
7521   //   fallthrough --> exitMBB
7522   // exitMBB:
7523   //   epilogue to handle left-over bytes
7524   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7525   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7526   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7527   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7528   MF->insert(It, loopMBB);
7529   MF->insert(It, exitMBB);
7530
7531   // Transfer the remainder of BB and its successor edges to exitMBB.
7532   exitMBB->splice(exitMBB->begin(), BB,
7533                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7534   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7535
7536   // Load an immediate to varEnd.
7537   unsigned varEnd = MRI.createVirtualRegister(TRC);
7538   if (Subtarget->useMovt(*MF)) {
7539     unsigned Vtmp = varEnd;
7540     if ((LoopSize & 0xFFFF0000) != 0)
7541       Vtmp = MRI.createVirtualRegister(TRC);
7542     AddDefaultPred(BuildMI(BB, dl,
7543                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7544                            Vtmp).addImm(LoopSize & 0xFFFF));
7545
7546     if ((LoopSize & 0xFFFF0000) != 0)
7547       AddDefaultPred(BuildMI(BB, dl,
7548                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7549                              varEnd)
7550                          .addReg(Vtmp)
7551                          .addImm(LoopSize >> 16));
7552   } else {
7553     MachineConstantPool *ConstantPool = MF->getConstantPool();
7554     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7555     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7556
7557     // MachineConstantPool wants an explicit alignment.
7558     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7559     if (Align == 0)
7560       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7561     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7562
7563     if (IsThumb1)
7564       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7565           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7566     else
7567       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7568           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7569   }
7570   BB->addSuccessor(loopMBB);
7571
7572   // Generate the loop body:
7573   //   varPhi = PHI(varLoop, varEnd)
7574   //   srcPhi = PHI(srcLoop, src)
7575   //   destPhi = PHI(destLoop, dst)
7576   MachineBasicBlock *entryBB = BB;
7577   BB = loopMBB;
7578   unsigned varLoop = MRI.createVirtualRegister(TRC);
7579   unsigned varPhi = MRI.createVirtualRegister(TRC);
7580   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7581   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7582   unsigned destLoop = MRI.createVirtualRegister(TRC);
7583   unsigned destPhi = MRI.createVirtualRegister(TRC);
7584
7585   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7586     .addReg(varLoop).addMBB(loopMBB)
7587     .addReg(varEnd).addMBB(entryBB);
7588   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7589     .addReg(srcLoop).addMBB(loopMBB)
7590     .addReg(src).addMBB(entryBB);
7591   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7592     .addReg(destLoop).addMBB(loopMBB)
7593     .addReg(dest).addMBB(entryBB);
7594
7595   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7596   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7597   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7598   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7599              IsThumb1, IsThumb2);
7600   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7601              IsThumb1, IsThumb2);
7602
7603   // Decrement loop variable by UnitSize.
7604   if (IsThumb1) {
7605     MachineInstrBuilder MIB =
7606         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7607     MIB = AddDefaultT1CC(MIB);
7608     MIB.addReg(varPhi).addImm(UnitSize);
7609     AddDefaultPred(MIB);
7610   } else {
7611     MachineInstrBuilder MIB =
7612         BuildMI(*BB, BB->end(), dl,
7613                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7614     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7615     MIB->getOperand(5).setReg(ARM::CPSR);
7616     MIB->getOperand(5).setIsDef(true);
7617   }
7618   BuildMI(*BB, BB->end(), dl,
7619           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7620       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7621
7622   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7623   BB->addSuccessor(loopMBB);
7624   BB->addSuccessor(exitMBB);
7625
7626   // Add epilogue to handle BytesLeft.
7627   BB = exitMBB;
7628   MachineInstr *StartOfExit = exitMBB->begin();
7629
7630   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7631   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7632   unsigned srcIn = srcLoop;
7633   unsigned destIn = destLoop;
7634   for (unsigned i = 0; i < BytesLeft; i++) {
7635     unsigned srcOut = MRI.createVirtualRegister(TRC);
7636     unsigned destOut = MRI.createVirtualRegister(TRC);
7637     unsigned scratch = MRI.createVirtualRegister(TRC);
7638     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7639                IsThumb1, IsThumb2);
7640     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7641                IsThumb1, IsThumb2);
7642     srcIn = srcOut;
7643     destIn = destOut;
7644   }
7645
7646   MI->eraseFromParent();   // The instruction is gone now.
7647   return BB;
7648 }
7649
7650 MachineBasicBlock *
7651 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7652                                        MachineBasicBlock *MBB) const {
7653   const TargetMachine &TM = getTargetMachine();
7654   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7655   DebugLoc DL = MI->getDebugLoc();
7656
7657   assert(Subtarget->isTargetWindows() &&
7658          "__chkstk is only supported on Windows");
7659   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7660
7661   // __chkstk takes the number of words to allocate on the stack in R4, and
7662   // returns the stack adjustment in number of bytes in R4.  This will not
7663   // clober any other registers (other than the obvious lr).
7664   //
7665   // Although, technically, IP should be considered a register which may be
7666   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7667   // thumb-2 environment, so there is no interworking required.  As a result, we
7668   // do not expect a veneer to be emitted by the linker, clobbering IP.
7669   //
7670   // Each module receives its own copy of __chkstk, so no import thunk is
7671   // required, again, ensuring that IP is not clobbered.
7672   //
7673   // Finally, although some linkers may theoretically provide a trampoline for
7674   // out of range calls (which is quite common due to a 32M range limitation of
7675   // branches for Thumb), we can generate the long-call version via
7676   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7677   // IP.
7678
7679   switch (TM.getCodeModel()) {
7680   case CodeModel::Small:
7681   case CodeModel::Medium:
7682   case CodeModel::Default:
7683   case CodeModel::Kernel:
7684     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7685       .addImm((unsigned)ARMCC::AL).addReg(0)
7686       .addExternalSymbol("__chkstk")
7687       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7688       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7689       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7690     break;
7691   case CodeModel::Large:
7692   case CodeModel::JITDefault: {
7693     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7694     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7695
7696     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7697       .addExternalSymbol("__chkstk");
7698     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7699       .addImm((unsigned)ARMCC::AL).addReg(0)
7700       .addReg(Reg, RegState::Kill)
7701       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7702       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7703       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7704     break;
7705   }
7706   }
7707
7708   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7709                                       ARM::SP)
7710                               .addReg(ARM::SP).addReg(ARM::R4)));
7711
7712   MI->eraseFromParent();
7713   return MBB;
7714 }
7715
7716 MachineBasicBlock *
7717 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7718                                                MachineBasicBlock *BB) const {
7719   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7720   DebugLoc dl = MI->getDebugLoc();
7721   bool isThumb2 = Subtarget->isThumb2();
7722   switch (MI->getOpcode()) {
7723   default: {
7724     MI->dump();
7725     llvm_unreachable("Unexpected instr type to insert");
7726   }
7727   // The Thumb2 pre-indexed stores have the same MI operands, they just
7728   // define them differently in the .td files from the isel patterns, so
7729   // they need pseudos.
7730   case ARM::t2STR_preidx:
7731     MI->setDesc(TII->get(ARM::t2STR_PRE));
7732     return BB;
7733   case ARM::t2STRB_preidx:
7734     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7735     return BB;
7736   case ARM::t2STRH_preidx:
7737     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7738     return BB;
7739
7740   case ARM::STRi_preidx:
7741   case ARM::STRBi_preidx: {
7742     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7743       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7744     // Decode the offset.
7745     unsigned Offset = MI->getOperand(4).getImm();
7746     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7747     Offset = ARM_AM::getAM2Offset(Offset);
7748     if (isSub)
7749       Offset = -Offset;
7750
7751     MachineMemOperand *MMO = *MI->memoperands_begin();
7752     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7753       .addOperand(MI->getOperand(0))  // Rn_wb
7754       .addOperand(MI->getOperand(1))  // Rt
7755       .addOperand(MI->getOperand(2))  // Rn
7756       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7757       .addOperand(MI->getOperand(5))  // pred
7758       .addOperand(MI->getOperand(6))
7759       .addMemOperand(MMO);
7760     MI->eraseFromParent();
7761     return BB;
7762   }
7763   case ARM::STRr_preidx:
7764   case ARM::STRBr_preidx:
7765   case ARM::STRH_preidx: {
7766     unsigned NewOpc;
7767     switch (MI->getOpcode()) {
7768     default: llvm_unreachable("unexpected opcode!");
7769     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7770     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7771     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7772     }
7773     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7774     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7775       MIB.addOperand(MI->getOperand(i));
7776     MI->eraseFromParent();
7777     return BB;
7778   }
7779
7780   case ARM::tMOVCCr_pseudo: {
7781     // To "insert" a SELECT_CC instruction, we actually have to insert the
7782     // diamond control-flow pattern.  The incoming instruction knows the
7783     // destination vreg to set, the condition code register to branch on, the
7784     // true/false values to select between, and a branch opcode to use.
7785     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7786     MachineFunction::iterator It = BB;
7787     ++It;
7788
7789     //  thisMBB:
7790     //  ...
7791     //   TrueVal = ...
7792     //   cmpTY ccX, r1, r2
7793     //   bCC copy1MBB
7794     //   fallthrough --> copy0MBB
7795     MachineBasicBlock *thisMBB  = BB;
7796     MachineFunction *F = BB->getParent();
7797     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7798     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7799     F->insert(It, copy0MBB);
7800     F->insert(It, sinkMBB);
7801
7802     // Transfer the remainder of BB and its successor edges to sinkMBB.
7803     sinkMBB->splice(sinkMBB->begin(), BB,
7804                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7805     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7806
7807     BB->addSuccessor(copy0MBB);
7808     BB->addSuccessor(sinkMBB);
7809
7810     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7811       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7812
7813     //  copy0MBB:
7814     //   %FalseValue = ...
7815     //   # fallthrough to sinkMBB
7816     BB = copy0MBB;
7817
7818     // Update machine-CFG edges
7819     BB->addSuccessor(sinkMBB);
7820
7821     //  sinkMBB:
7822     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7823     //  ...
7824     BB = sinkMBB;
7825     BuildMI(*BB, BB->begin(), dl,
7826             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7827       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7828       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7829
7830     MI->eraseFromParent();   // The pseudo instruction is gone now.
7831     return BB;
7832   }
7833
7834   case ARM::BCCi64:
7835   case ARM::BCCZi64: {
7836     // If there is an unconditional branch to the other successor, remove it.
7837     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7838
7839     // Compare both parts that make up the double comparison separately for
7840     // equality.
7841     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7842
7843     unsigned LHS1 = MI->getOperand(1).getReg();
7844     unsigned LHS2 = MI->getOperand(2).getReg();
7845     if (RHSisZero) {
7846       AddDefaultPred(BuildMI(BB, dl,
7847                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7848                      .addReg(LHS1).addImm(0));
7849       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7850         .addReg(LHS2).addImm(0)
7851         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7852     } else {
7853       unsigned RHS1 = MI->getOperand(3).getReg();
7854       unsigned RHS2 = MI->getOperand(4).getReg();
7855       AddDefaultPred(BuildMI(BB, dl,
7856                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7857                      .addReg(LHS1).addReg(RHS1));
7858       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7859         .addReg(LHS2).addReg(RHS2)
7860         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7861     }
7862
7863     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7864     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7865     if (MI->getOperand(0).getImm() == ARMCC::NE)
7866       std::swap(destMBB, exitMBB);
7867
7868     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7869       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7870     if (isThumb2)
7871       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7872     else
7873       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7874
7875     MI->eraseFromParent();   // The pseudo instruction is gone now.
7876     return BB;
7877   }
7878
7879   case ARM::Int_eh_sjlj_setjmp:
7880   case ARM::Int_eh_sjlj_setjmp_nofp:
7881   case ARM::tInt_eh_sjlj_setjmp:
7882   case ARM::t2Int_eh_sjlj_setjmp:
7883   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7884     return BB;
7885
7886   case ARM::Int_eh_sjlj_setup_dispatch:
7887     EmitSjLjDispatchBlock(MI, BB);
7888     return BB;
7889
7890   case ARM::ABS:
7891   case ARM::t2ABS: {
7892     // To insert an ABS instruction, we have to insert the
7893     // diamond control-flow pattern.  The incoming instruction knows the
7894     // source vreg to test against 0, the destination vreg to set,
7895     // the condition code register to branch on, the
7896     // true/false values to select between, and a branch opcode to use.
7897     // It transforms
7898     //     V1 = ABS V0
7899     // into
7900     //     V2 = MOVS V0
7901     //     BCC                      (branch to SinkBB if V0 >= 0)
7902     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7903     //     SinkBB: V1 = PHI(V2, V3)
7904     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7905     MachineFunction::iterator BBI = BB;
7906     ++BBI;
7907     MachineFunction *Fn = BB->getParent();
7908     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7909     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7910     Fn->insert(BBI, RSBBB);
7911     Fn->insert(BBI, SinkBB);
7912
7913     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7914     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7915     bool ABSSrcKIll = MI->getOperand(1).isKill();
7916     bool isThumb2 = Subtarget->isThumb2();
7917     MachineRegisterInfo &MRI = Fn->getRegInfo();
7918     // In Thumb mode S must not be specified if source register is the SP or
7919     // PC and if destination register is the SP, so restrict register class
7920     unsigned NewRsbDstReg =
7921       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7922
7923     // Transfer the remainder of BB and its successor edges to sinkMBB.
7924     SinkBB->splice(SinkBB->begin(), BB,
7925                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7926     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7927
7928     BB->addSuccessor(RSBBB);
7929     BB->addSuccessor(SinkBB);
7930
7931     // fall through to SinkMBB
7932     RSBBB->addSuccessor(SinkBB);
7933
7934     // insert a cmp at the end of BB
7935     AddDefaultPred(BuildMI(BB, dl,
7936                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7937                    .addReg(ABSSrcReg).addImm(0));
7938
7939     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7940     BuildMI(BB, dl,
7941       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7942       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7943
7944     // insert rsbri in RSBBB
7945     // Note: BCC and rsbri will be converted into predicated rsbmi
7946     // by if-conversion pass
7947     BuildMI(*RSBBB, RSBBB->begin(), dl,
7948       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7949       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7950       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7951
7952     // insert PHI in SinkBB,
7953     // reuse ABSDstReg to not change uses of ABS instruction
7954     BuildMI(*SinkBB, SinkBB->begin(), dl,
7955       TII->get(ARM::PHI), ABSDstReg)
7956       .addReg(NewRsbDstReg).addMBB(RSBBB)
7957       .addReg(ABSSrcReg).addMBB(BB);
7958
7959     // remove ABS instruction
7960     MI->eraseFromParent();
7961
7962     // return last added BB
7963     return SinkBB;
7964   }
7965   case ARM::COPY_STRUCT_BYVAL_I32:
7966     ++NumLoopByVals;
7967     return EmitStructByval(MI, BB);
7968   case ARM::WIN__CHKSTK:
7969     return EmitLowered__chkstk(MI, BB);
7970   }
7971 }
7972
7973 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7974                                                       SDNode *Node) const {
7975   const MCInstrDesc *MCID = &MI->getDesc();
7976   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7977   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7978   // operand is still set to noreg. If needed, set the optional operand's
7979   // register to CPSR, and remove the redundant implicit def.
7980   //
7981   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7982
7983   // Rename pseudo opcodes.
7984   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7985   if (NewOpc) {
7986     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7987     MCID = &TII->get(NewOpc);
7988
7989     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7990            "converted opcode should be the same except for cc_out");
7991
7992     MI->setDesc(*MCID);
7993
7994     // Add the optional cc_out operand
7995     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7996   }
7997   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7998
7999   // Any ARM instruction that sets the 's' bit should specify an optional
8000   // "cc_out" operand in the last operand position.
8001   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8002     assert(!NewOpc && "Optional cc_out operand required");
8003     return;
8004   }
8005   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8006   // since we already have an optional CPSR def.
8007   bool definesCPSR = false;
8008   bool deadCPSR = false;
8009   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8010        i != e; ++i) {
8011     const MachineOperand &MO = MI->getOperand(i);
8012     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8013       definesCPSR = true;
8014       if (MO.isDead())
8015         deadCPSR = true;
8016       MI->RemoveOperand(i);
8017       break;
8018     }
8019   }
8020   if (!definesCPSR) {
8021     assert(!NewOpc && "Optional cc_out operand required");
8022     return;
8023   }
8024   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8025   if (deadCPSR) {
8026     assert(!MI->getOperand(ccOutIdx).getReg() &&
8027            "expect uninitialized optional cc_out operand");
8028     return;
8029   }
8030
8031   // If this instruction was defined with an optional CPSR def and its dag node
8032   // had a live implicit CPSR def, then activate the optional CPSR def.
8033   MachineOperand &MO = MI->getOperand(ccOutIdx);
8034   MO.setReg(ARM::CPSR);
8035   MO.setIsDef(true);
8036 }
8037
8038 //===----------------------------------------------------------------------===//
8039 //                           ARM Optimization Hooks
8040 //===----------------------------------------------------------------------===//
8041
8042 // Helper function that checks if N is a null or all ones constant.
8043 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8044   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8045   if (!C)
8046     return false;
8047   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8048 }
8049
8050 // Return true if N is conditionally 0 or all ones.
8051 // Detects these expressions where cc is an i1 value:
8052 //
8053 //   (select cc 0, y)   [AllOnes=0]
8054 //   (select cc y, 0)   [AllOnes=0]
8055 //   (zext cc)          [AllOnes=0]
8056 //   (sext cc)          [AllOnes=0/1]
8057 //   (select cc -1, y)  [AllOnes=1]
8058 //   (select cc y, -1)  [AllOnes=1]
8059 //
8060 // Invert is set when N is the null/all ones constant when CC is false.
8061 // OtherOp is set to the alternative value of N.
8062 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8063                                        SDValue &CC, bool &Invert,
8064                                        SDValue &OtherOp,
8065                                        SelectionDAG &DAG) {
8066   switch (N->getOpcode()) {
8067   default: return false;
8068   case ISD::SELECT: {
8069     CC = N->getOperand(0);
8070     SDValue N1 = N->getOperand(1);
8071     SDValue N2 = N->getOperand(2);
8072     if (isZeroOrAllOnes(N1, AllOnes)) {
8073       Invert = false;
8074       OtherOp = N2;
8075       return true;
8076     }
8077     if (isZeroOrAllOnes(N2, AllOnes)) {
8078       Invert = true;
8079       OtherOp = N1;
8080       return true;
8081     }
8082     return false;
8083   }
8084   case ISD::ZERO_EXTEND:
8085     // (zext cc) can never be the all ones value.
8086     if (AllOnes)
8087       return false;
8088     // Fall through.
8089   case ISD::SIGN_EXTEND: {
8090     SDLoc dl(N);
8091     EVT VT = N->getValueType(0);
8092     CC = N->getOperand(0);
8093     if (CC.getValueType() != MVT::i1)
8094       return false;
8095     Invert = !AllOnes;
8096     if (AllOnes)
8097       // When looking for an AllOnes constant, N is an sext, and the 'other'
8098       // value is 0.
8099       OtherOp = DAG.getConstant(0, dl, VT);
8100     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8101       // When looking for a 0 constant, N can be zext or sext.
8102       OtherOp = DAG.getConstant(1, dl, VT);
8103     else
8104       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8105                                 VT);
8106     return true;
8107   }
8108   }
8109 }
8110
8111 // Combine a constant select operand into its use:
8112 //
8113 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8114 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8115 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8116 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8117 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8118 //
8119 // The transform is rejected if the select doesn't have a constant operand that
8120 // is null, or all ones when AllOnes is set.
8121 //
8122 // Also recognize sext/zext from i1:
8123 //
8124 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8125 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8126 //
8127 // These transformations eventually create predicated instructions.
8128 //
8129 // @param N       The node to transform.
8130 // @param Slct    The N operand that is a select.
8131 // @param OtherOp The other N operand (x above).
8132 // @param DCI     Context.
8133 // @param AllOnes Require the select constant to be all ones instead of null.
8134 // @returns The new node, or SDValue() on failure.
8135 static
8136 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8137                             TargetLowering::DAGCombinerInfo &DCI,
8138                             bool AllOnes = false) {
8139   SelectionDAG &DAG = DCI.DAG;
8140   EVT VT = N->getValueType(0);
8141   SDValue NonConstantVal;
8142   SDValue CCOp;
8143   bool SwapSelectOps;
8144   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8145                                   NonConstantVal, DAG))
8146     return SDValue();
8147
8148   // Slct is now know to be the desired identity constant when CC is true.
8149   SDValue TrueVal = OtherOp;
8150   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8151                                  OtherOp, NonConstantVal);
8152   // Unless SwapSelectOps says CC should be false.
8153   if (SwapSelectOps)
8154     std::swap(TrueVal, FalseVal);
8155
8156   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8157                      CCOp, TrueVal, FalseVal);
8158 }
8159
8160 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8161 static
8162 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8163                                        TargetLowering::DAGCombinerInfo &DCI) {
8164   SDValue N0 = N->getOperand(0);
8165   SDValue N1 = N->getOperand(1);
8166   if (N0.getNode()->hasOneUse()) {
8167     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8168     if (Result.getNode())
8169       return Result;
8170   }
8171   if (N1.getNode()->hasOneUse()) {
8172     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8173     if (Result.getNode())
8174       return Result;
8175   }
8176   return SDValue();
8177 }
8178
8179 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8180 // (only after legalization).
8181 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8182                                  TargetLowering::DAGCombinerInfo &DCI,
8183                                  const ARMSubtarget *Subtarget) {
8184
8185   // Only perform optimization if after legalize, and if NEON is available. We
8186   // also expected both operands to be BUILD_VECTORs.
8187   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8188       || N0.getOpcode() != ISD::BUILD_VECTOR
8189       || N1.getOpcode() != ISD::BUILD_VECTOR)
8190     return SDValue();
8191
8192   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8193   EVT VT = N->getValueType(0);
8194   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8195     return SDValue();
8196
8197   // Check that the vector operands are of the right form.
8198   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8199   // operands, where N is the size of the formed vector.
8200   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8201   // index such that we have a pair wise add pattern.
8202
8203   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8204   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8205     return SDValue();
8206   SDValue Vec = N0->getOperand(0)->getOperand(0);
8207   SDNode *V = Vec.getNode();
8208   unsigned nextIndex = 0;
8209
8210   // For each operands to the ADD which are BUILD_VECTORs,
8211   // check to see if each of their operands are an EXTRACT_VECTOR with
8212   // the same vector and appropriate index.
8213   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8214     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8215         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8216
8217       SDValue ExtVec0 = N0->getOperand(i);
8218       SDValue ExtVec1 = N1->getOperand(i);
8219
8220       // First operand is the vector, verify its the same.
8221       if (V != ExtVec0->getOperand(0).getNode() ||
8222           V != ExtVec1->getOperand(0).getNode())
8223         return SDValue();
8224
8225       // Second is the constant, verify its correct.
8226       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8227       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8228
8229       // For the constant, we want to see all the even or all the odd.
8230       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8231           || C1->getZExtValue() != nextIndex+1)
8232         return SDValue();
8233
8234       // Increment index.
8235       nextIndex+=2;
8236     } else
8237       return SDValue();
8238   }
8239
8240   // Create VPADDL node.
8241   SelectionDAG &DAG = DCI.DAG;
8242   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8243
8244   SDLoc dl(N);
8245
8246   // Build operand list.
8247   SmallVector<SDValue, 8> Ops;
8248   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8249                                 TLI.getPointerTy(DAG.getDataLayout())));
8250
8251   // Input is the vector.
8252   Ops.push_back(Vec);
8253
8254   // Get widened type and narrowed type.
8255   MVT widenType;
8256   unsigned numElem = VT.getVectorNumElements();
8257   
8258   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8259   switch (inputLaneType.getSimpleVT().SimpleTy) {
8260     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8261     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8262     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8263     default:
8264       llvm_unreachable("Invalid vector element type for padd optimization.");
8265   }
8266
8267   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8268   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8269   return DAG.getNode(ExtOp, dl, VT, tmp);
8270 }
8271
8272 static SDValue findMUL_LOHI(SDValue V) {
8273   if (V->getOpcode() == ISD::UMUL_LOHI ||
8274       V->getOpcode() == ISD::SMUL_LOHI)
8275     return V;
8276   return SDValue();
8277 }
8278
8279 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8280                                      TargetLowering::DAGCombinerInfo &DCI,
8281                                      const ARMSubtarget *Subtarget) {
8282
8283   if (Subtarget->isThumb1Only()) return SDValue();
8284
8285   // Only perform the checks after legalize when the pattern is available.
8286   if (DCI.isBeforeLegalize()) return SDValue();
8287
8288   // Look for multiply add opportunities.
8289   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8290   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8291   // a glue link from the first add to the second add.
8292   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8293   // a S/UMLAL instruction.
8294   //                  UMUL_LOHI
8295   //                 / :lo    \ :hi
8296   //                /          \          [no multiline comment]
8297   //    loAdd ->  ADDE         |
8298   //                 \ :glue  /
8299   //                  \      /
8300   //                    ADDC   <- hiAdd
8301   //
8302   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8303   SDValue AddcOp0 = AddcNode->getOperand(0);
8304   SDValue AddcOp1 = AddcNode->getOperand(1);
8305
8306   // Check if the two operands are from the same mul_lohi node.
8307   if (AddcOp0.getNode() == AddcOp1.getNode())
8308     return SDValue();
8309
8310   assert(AddcNode->getNumValues() == 2 &&
8311          AddcNode->getValueType(0) == MVT::i32 &&
8312          "Expect ADDC with two result values. First: i32");
8313
8314   // Check that we have a glued ADDC node.
8315   if (AddcNode->getValueType(1) != MVT::Glue)
8316     return SDValue();
8317
8318   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8319   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8320       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8321       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8322       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8323     return SDValue();
8324
8325   // Look for the glued ADDE.
8326   SDNode* AddeNode = AddcNode->getGluedUser();
8327   if (!AddeNode)
8328     return SDValue();
8329
8330   // Make sure it is really an ADDE.
8331   if (AddeNode->getOpcode() != ISD::ADDE)
8332     return SDValue();
8333
8334   assert(AddeNode->getNumOperands() == 3 &&
8335          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8336          "ADDE node has the wrong inputs");
8337
8338   // Check for the triangle shape.
8339   SDValue AddeOp0 = AddeNode->getOperand(0);
8340   SDValue AddeOp1 = AddeNode->getOperand(1);
8341
8342   // Make sure that the ADDE operands are not coming from the same node.
8343   if (AddeOp0.getNode() == AddeOp1.getNode())
8344     return SDValue();
8345
8346   // Find the MUL_LOHI node walking up ADDE's operands.
8347   bool IsLeftOperandMUL = false;
8348   SDValue MULOp = findMUL_LOHI(AddeOp0);
8349   if (MULOp == SDValue())
8350    MULOp = findMUL_LOHI(AddeOp1);
8351   else
8352     IsLeftOperandMUL = true;
8353   if (MULOp == SDValue())
8354     return SDValue();
8355
8356   // Figure out the right opcode.
8357   unsigned Opc = MULOp->getOpcode();
8358   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8359
8360   // Figure out the high and low input values to the MLAL node.
8361   SDValue* HiAdd = nullptr;
8362   SDValue* LoMul = nullptr;
8363   SDValue* LowAdd = nullptr;
8364
8365   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8366   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8367     return SDValue();
8368
8369   if (IsLeftOperandMUL)
8370     HiAdd = &AddeOp1;
8371   else
8372     HiAdd = &AddeOp0;
8373
8374
8375   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8376   // whose low result is fed to the ADDC we are checking.
8377
8378   if (AddcOp0 == MULOp.getValue(0)) {
8379     LoMul = &AddcOp0;
8380     LowAdd = &AddcOp1;
8381   }
8382   if (AddcOp1 == MULOp.getValue(0)) {
8383     LoMul = &AddcOp1;
8384     LowAdd = &AddcOp0;
8385   }
8386
8387   if (!LoMul)
8388     return SDValue();
8389
8390   // Create the merged node.
8391   SelectionDAG &DAG = DCI.DAG;
8392
8393   // Build operand list.
8394   SmallVector<SDValue, 8> Ops;
8395   Ops.push_back(LoMul->getOperand(0));
8396   Ops.push_back(LoMul->getOperand(1));
8397   Ops.push_back(*LowAdd);
8398   Ops.push_back(*HiAdd);
8399
8400   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8401                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8402
8403   // Replace the ADDs' nodes uses by the MLA node's values.
8404   SDValue HiMLALResult(MLALNode.getNode(), 1);
8405   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8406
8407   SDValue LoMLALResult(MLALNode.getNode(), 0);
8408   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8409
8410   // Return original node to notify the driver to stop replacing.
8411   SDValue resNode(AddcNode, 0);
8412   return resNode;
8413 }
8414
8415 /// PerformADDCCombine - Target-specific dag combine transform from
8416 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8417 static SDValue PerformADDCCombine(SDNode *N,
8418                                  TargetLowering::DAGCombinerInfo &DCI,
8419                                  const ARMSubtarget *Subtarget) {
8420
8421   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8422
8423 }
8424
8425 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8426 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8427 /// called with the default operands, and if that fails, with commuted
8428 /// operands.
8429 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8430                                           TargetLowering::DAGCombinerInfo &DCI,
8431                                           const ARMSubtarget *Subtarget){
8432
8433   // Attempt to create vpaddl for this add.
8434   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8435   if (Result.getNode())
8436     return Result;
8437
8438   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8439   if (N0.getNode()->hasOneUse()) {
8440     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8441     if (Result.getNode()) return Result;
8442   }
8443   return SDValue();
8444 }
8445
8446 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8447 ///
8448 static SDValue PerformADDCombine(SDNode *N,
8449                                  TargetLowering::DAGCombinerInfo &DCI,
8450                                  const ARMSubtarget *Subtarget) {
8451   SDValue N0 = N->getOperand(0);
8452   SDValue N1 = N->getOperand(1);
8453
8454   // First try with the default operand order.
8455   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8456   if (Result.getNode())
8457     return Result;
8458
8459   // If that didn't work, try again with the operands commuted.
8460   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8461 }
8462
8463 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8464 ///
8465 static SDValue PerformSUBCombine(SDNode *N,
8466                                  TargetLowering::DAGCombinerInfo &DCI) {
8467   SDValue N0 = N->getOperand(0);
8468   SDValue N1 = N->getOperand(1);
8469
8470   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8471   if (N1.getNode()->hasOneUse()) {
8472     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8473     if (Result.getNode()) return Result;
8474   }
8475
8476   return SDValue();
8477 }
8478
8479 /// PerformVMULCombine
8480 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8481 /// special multiplier accumulator forwarding.
8482 ///   vmul d3, d0, d2
8483 ///   vmla d3, d1, d2
8484 /// is faster than
8485 ///   vadd d3, d0, d1
8486 ///   vmul d3, d3, d2
8487 //  However, for (A + B) * (A + B),
8488 //    vadd d2, d0, d1
8489 //    vmul d3, d0, d2
8490 //    vmla d3, d1, d2
8491 //  is slower than
8492 //    vadd d2, d0, d1
8493 //    vmul d3, d2, d2
8494 static SDValue PerformVMULCombine(SDNode *N,
8495                                   TargetLowering::DAGCombinerInfo &DCI,
8496                                   const ARMSubtarget *Subtarget) {
8497   if (!Subtarget->hasVMLxForwarding())
8498     return SDValue();
8499
8500   SelectionDAG &DAG = DCI.DAG;
8501   SDValue N0 = N->getOperand(0);
8502   SDValue N1 = N->getOperand(1);
8503   unsigned Opcode = N0.getOpcode();
8504   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8505       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8506     Opcode = N1.getOpcode();
8507     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8508         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8509       return SDValue();
8510     std::swap(N0, N1);
8511   }
8512
8513   if (N0 == N1)
8514     return SDValue();
8515
8516   EVT VT = N->getValueType(0);
8517   SDLoc DL(N);
8518   SDValue N00 = N0->getOperand(0);
8519   SDValue N01 = N0->getOperand(1);
8520   return DAG.getNode(Opcode, DL, VT,
8521                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8522                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8523 }
8524
8525 static SDValue PerformMULCombine(SDNode *N,
8526                                  TargetLowering::DAGCombinerInfo &DCI,
8527                                  const ARMSubtarget *Subtarget) {
8528   SelectionDAG &DAG = DCI.DAG;
8529
8530   if (Subtarget->isThumb1Only())
8531     return SDValue();
8532
8533   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8534     return SDValue();
8535
8536   EVT VT = N->getValueType(0);
8537   if (VT.is64BitVector() || VT.is128BitVector())
8538     return PerformVMULCombine(N, DCI, Subtarget);
8539   if (VT != MVT::i32)
8540     return SDValue();
8541
8542   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8543   if (!C)
8544     return SDValue();
8545
8546   int64_t MulAmt = C->getSExtValue();
8547   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8548
8549   ShiftAmt = ShiftAmt & (32 - 1);
8550   SDValue V = N->getOperand(0);
8551   SDLoc DL(N);
8552
8553   SDValue Res;
8554   MulAmt >>= ShiftAmt;
8555
8556   if (MulAmt >= 0) {
8557     if (isPowerOf2_32(MulAmt - 1)) {
8558       // (mul x, 2^N + 1) => (add (shl x, N), x)
8559       Res = DAG.getNode(ISD::ADD, DL, VT,
8560                         V,
8561                         DAG.getNode(ISD::SHL, DL, VT,
8562                                     V,
8563                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8564                                                     MVT::i32)));
8565     } else if (isPowerOf2_32(MulAmt + 1)) {
8566       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8567       Res = DAG.getNode(ISD::SUB, DL, VT,
8568                         DAG.getNode(ISD::SHL, DL, VT,
8569                                     V,
8570                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8571                                                     MVT::i32)),
8572                         V);
8573     } else
8574       return SDValue();
8575   } else {
8576     uint64_t MulAmtAbs = -MulAmt;
8577     if (isPowerOf2_32(MulAmtAbs + 1)) {
8578       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8579       Res = DAG.getNode(ISD::SUB, DL, VT,
8580                         V,
8581                         DAG.getNode(ISD::SHL, DL, VT,
8582                                     V,
8583                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8584                                                     MVT::i32)));
8585     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8586       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8587       Res = DAG.getNode(ISD::ADD, DL, VT,
8588                         V,
8589                         DAG.getNode(ISD::SHL, DL, VT,
8590                                     V,
8591                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8592                                                     MVT::i32)));
8593       Res = DAG.getNode(ISD::SUB, DL, VT,
8594                         DAG.getConstant(0, DL, MVT::i32), Res);
8595
8596     } else
8597       return SDValue();
8598   }
8599
8600   if (ShiftAmt != 0)
8601     Res = DAG.getNode(ISD::SHL, DL, VT,
8602                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8603
8604   // Do not add new nodes to DAG combiner worklist.
8605   DCI.CombineTo(N, Res, false);
8606   return SDValue();
8607 }
8608
8609 static SDValue PerformANDCombine(SDNode *N,
8610                                  TargetLowering::DAGCombinerInfo &DCI,
8611                                  const ARMSubtarget *Subtarget) {
8612
8613   // Attempt to use immediate-form VBIC
8614   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8615   SDLoc dl(N);
8616   EVT VT = N->getValueType(0);
8617   SelectionDAG &DAG = DCI.DAG;
8618
8619   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8620     return SDValue();
8621
8622   APInt SplatBits, SplatUndef;
8623   unsigned SplatBitSize;
8624   bool HasAnyUndefs;
8625   if (BVN &&
8626       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8627     if (SplatBitSize <= 64) {
8628       EVT VbicVT;
8629       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8630                                       SplatUndef.getZExtValue(), SplatBitSize,
8631                                       DAG, dl, VbicVT, VT.is128BitVector(),
8632                                       OtherModImm);
8633       if (Val.getNode()) {
8634         SDValue Input =
8635           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8636         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8637         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8638       }
8639     }
8640   }
8641
8642   if (!Subtarget->isThumb1Only()) {
8643     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8644     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8645     if (Result.getNode())
8646       return Result;
8647   }
8648
8649   return SDValue();
8650 }
8651
8652 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8653 static SDValue PerformORCombine(SDNode *N,
8654                                 TargetLowering::DAGCombinerInfo &DCI,
8655                                 const ARMSubtarget *Subtarget) {
8656   // Attempt to use immediate-form VORR
8657   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8658   SDLoc dl(N);
8659   EVT VT = N->getValueType(0);
8660   SelectionDAG &DAG = DCI.DAG;
8661
8662   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8663     return SDValue();
8664
8665   APInt SplatBits, SplatUndef;
8666   unsigned SplatBitSize;
8667   bool HasAnyUndefs;
8668   if (BVN && Subtarget->hasNEON() &&
8669       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8670     if (SplatBitSize <= 64) {
8671       EVT VorrVT;
8672       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8673                                       SplatUndef.getZExtValue(), SplatBitSize,
8674                                       DAG, dl, VorrVT, VT.is128BitVector(),
8675                                       OtherModImm);
8676       if (Val.getNode()) {
8677         SDValue Input =
8678           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8679         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8680         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8681       }
8682     }
8683   }
8684
8685   if (!Subtarget->isThumb1Only()) {
8686     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8687     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8688     if (Result.getNode())
8689       return Result;
8690   }
8691
8692   // The code below optimizes (or (and X, Y), Z).
8693   // The AND operand needs to have a single user to make these optimizations
8694   // profitable.
8695   SDValue N0 = N->getOperand(0);
8696   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8697     return SDValue();
8698   SDValue N1 = N->getOperand(1);
8699
8700   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8701   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8702       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8703     APInt SplatUndef;
8704     unsigned SplatBitSize;
8705     bool HasAnyUndefs;
8706
8707     APInt SplatBits0, SplatBits1;
8708     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8709     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8710     // Ensure that the second operand of both ands are constants
8711     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8712                                       HasAnyUndefs) && !HasAnyUndefs) {
8713         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8714                                           HasAnyUndefs) && !HasAnyUndefs) {
8715             // Ensure that the bit width of the constants are the same and that
8716             // the splat arguments are logical inverses as per the pattern we
8717             // are trying to simplify.
8718             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8719                 SplatBits0 == ~SplatBits1) {
8720                 // Canonicalize the vector type to make instruction selection
8721                 // simpler.
8722                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8723                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8724                                              N0->getOperand(1),
8725                                              N0->getOperand(0),
8726                                              N1->getOperand(0));
8727                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8728             }
8729         }
8730     }
8731   }
8732
8733   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8734   // reasonable.
8735
8736   // BFI is only available on V6T2+
8737   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8738     return SDValue();
8739
8740   SDLoc DL(N);
8741   // 1) or (and A, mask), val => ARMbfi A, val, mask
8742   //      iff (val & mask) == val
8743   //
8744   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8745   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8746   //          && mask == ~mask2
8747   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8748   //          && ~mask == mask2
8749   //  (i.e., copy a bitfield value into another bitfield of the same width)
8750
8751   if (VT != MVT::i32)
8752     return SDValue();
8753
8754   SDValue N00 = N0.getOperand(0);
8755
8756   // The value and the mask need to be constants so we can verify this is
8757   // actually a bitfield set. If the mask is 0xffff, we can do better
8758   // via a movt instruction, so don't use BFI in that case.
8759   SDValue MaskOp = N0.getOperand(1);
8760   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8761   if (!MaskC)
8762     return SDValue();
8763   unsigned Mask = MaskC->getZExtValue();
8764   if (Mask == 0xffff)
8765     return SDValue();
8766   SDValue Res;
8767   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8769   if (N1C) {
8770     unsigned Val = N1C->getZExtValue();
8771     if ((Val & ~Mask) != Val)
8772       return SDValue();
8773
8774     if (ARM::isBitFieldInvertedMask(Mask)) {
8775       Val >>= countTrailingZeros(~Mask);
8776
8777       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8778                         DAG.getConstant(Val, DL, MVT::i32),
8779                         DAG.getConstant(Mask, DL, MVT::i32));
8780
8781       // Do not add new nodes to DAG combiner worklist.
8782       DCI.CombineTo(N, Res, false);
8783       return SDValue();
8784     }
8785   } else if (N1.getOpcode() == ISD::AND) {
8786     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8787     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8788     if (!N11C)
8789       return SDValue();
8790     unsigned Mask2 = N11C->getZExtValue();
8791
8792     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8793     // as is to match.
8794     if (ARM::isBitFieldInvertedMask(Mask) &&
8795         (Mask == ~Mask2)) {
8796       // The pack halfword instruction works better for masks that fit it,
8797       // so use that when it's available.
8798       if (Subtarget->hasT2ExtractPack() &&
8799           (Mask == 0xffff || Mask == 0xffff0000))
8800         return SDValue();
8801       // 2a
8802       unsigned amt = countTrailingZeros(Mask2);
8803       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8804                         DAG.getConstant(amt, DL, MVT::i32));
8805       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8806                         DAG.getConstant(Mask, DL, MVT::i32));
8807       // Do not add new nodes to DAG combiner worklist.
8808       DCI.CombineTo(N, Res, false);
8809       return SDValue();
8810     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8811                (~Mask == Mask2)) {
8812       // The pack halfword instruction works better for masks that fit it,
8813       // so use that when it's available.
8814       if (Subtarget->hasT2ExtractPack() &&
8815           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8816         return SDValue();
8817       // 2b
8818       unsigned lsb = countTrailingZeros(Mask);
8819       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8820                         DAG.getConstant(lsb, DL, MVT::i32));
8821       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8822                         DAG.getConstant(Mask2, DL, MVT::i32));
8823       // Do not add new nodes to DAG combiner worklist.
8824       DCI.CombineTo(N, Res, false);
8825       return SDValue();
8826     }
8827   }
8828
8829   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8830       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8831       ARM::isBitFieldInvertedMask(~Mask)) {
8832     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8833     // where lsb(mask) == #shamt and masked bits of B are known zero.
8834     SDValue ShAmt = N00.getOperand(1);
8835     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8836     unsigned LSB = countTrailingZeros(Mask);
8837     if (ShAmtC != LSB)
8838       return SDValue();
8839
8840     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8841                       DAG.getConstant(~Mask, DL, MVT::i32));
8842
8843     // Do not add new nodes to DAG combiner worklist.
8844     DCI.CombineTo(N, Res, false);
8845   }
8846
8847   return SDValue();
8848 }
8849
8850 static SDValue PerformXORCombine(SDNode *N,
8851                                  TargetLowering::DAGCombinerInfo &DCI,
8852                                  const ARMSubtarget *Subtarget) {
8853   EVT VT = N->getValueType(0);
8854   SelectionDAG &DAG = DCI.DAG;
8855
8856   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8857     return SDValue();
8858
8859   if (!Subtarget->isThumb1Only()) {
8860     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8861     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8862     if (Result.getNode())
8863       return Result;
8864   }
8865
8866   return SDValue();
8867 }
8868
8869 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8870 /// the bits being cleared by the AND are not demanded by the BFI.
8871 static SDValue PerformBFICombine(SDNode *N,
8872                                  TargetLowering::DAGCombinerInfo &DCI) {
8873   SDValue N1 = N->getOperand(1);
8874   if (N1.getOpcode() == ISD::AND) {
8875     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8876     if (!N11C)
8877       return SDValue();
8878     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8879     unsigned LSB = countTrailingZeros(~InvMask);
8880     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8881     assert(Width <
8882                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8883            "undefined behavior");
8884     unsigned Mask = (1u << Width) - 1;
8885     unsigned Mask2 = N11C->getZExtValue();
8886     if ((Mask & (~Mask2)) == 0)
8887       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8888                              N->getOperand(0), N1.getOperand(0),
8889                              N->getOperand(2));
8890   }
8891   return SDValue();
8892 }
8893
8894 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8895 /// ARMISD::VMOVRRD.
8896 static SDValue PerformVMOVRRDCombine(SDNode *N,
8897                                      TargetLowering::DAGCombinerInfo &DCI,
8898                                      const ARMSubtarget *Subtarget) {
8899   // vmovrrd(vmovdrr x, y) -> x,y
8900   SDValue InDouble = N->getOperand(0);
8901   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8902     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8903
8904   // vmovrrd(load f64) -> (load i32), (load i32)
8905   SDNode *InNode = InDouble.getNode();
8906   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8907       InNode->getValueType(0) == MVT::f64 &&
8908       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8909       !cast<LoadSDNode>(InNode)->isVolatile()) {
8910     // TODO: Should this be done for non-FrameIndex operands?
8911     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8912
8913     SelectionDAG &DAG = DCI.DAG;
8914     SDLoc DL(LD);
8915     SDValue BasePtr = LD->getBasePtr();
8916     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8917                                  LD->getPointerInfo(), LD->isVolatile(),
8918                                  LD->isNonTemporal(), LD->isInvariant(),
8919                                  LD->getAlignment());
8920
8921     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8922                                     DAG.getConstant(4, DL, MVT::i32));
8923     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8924                                  LD->getPointerInfo(), LD->isVolatile(),
8925                                  LD->isNonTemporal(), LD->isInvariant(),
8926                                  std::min(4U, LD->getAlignment() / 2));
8927
8928     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8929     if (DCI.DAG.getDataLayout().isBigEndian())
8930       std::swap (NewLD1, NewLD2);
8931     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8932     return Result;
8933   }
8934
8935   return SDValue();
8936 }
8937
8938 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8939 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8940 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8941   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8942   SDValue Op0 = N->getOperand(0);
8943   SDValue Op1 = N->getOperand(1);
8944   if (Op0.getOpcode() == ISD::BITCAST)
8945     Op0 = Op0.getOperand(0);
8946   if (Op1.getOpcode() == ISD::BITCAST)
8947     Op1 = Op1.getOperand(0);
8948   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8949       Op0.getNode() == Op1.getNode() &&
8950       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8951     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8952                        N->getValueType(0), Op0.getOperand(0));
8953   return SDValue();
8954 }
8955
8956 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8957 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8958 /// i64 vector to have f64 elements, since the value can then be loaded
8959 /// directly into a VFP register.
8960 static bool hasNormalLoadOperand(SDNode *N) {
8961   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8962   for (unsigned i = 0; i < NumElts; ++i) {
8963     SDNode *Elt = N->getOperand(i).getNode();
8964     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8965       return true;
8966   }
8967   return false;
8968 }
8969
8970 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8971 /// ISD::BUILD_VECTOR.
8972 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8973                                           TargetLowering::DAGCombinerInfo &DCI,
8974                                           const ARMSubtarget *Subtarget) {
8975   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8976   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8977   // into a pair of GPRs, which is fine when the value is used as a scalar,
8978   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8979   SelectionDAG &DAG = DCI.DAG;
8980   if (N->getNumOperands() == 2) {
8981     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8982     if (RV.getNode())
8983       return RV;
8984   }
8985
8986   // Load i64 elements as f64 values so that type legalization does not split
8987   // them up into i32 values.
8988   EVT VT = N->getValueType(0);
8989   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8990     return SDValue();
8991   SDLoc dl(N);
8992   SmallVector<SDValue, 8> Ops;
8993   unsigned NumElts = VT.getVectorNumElements();
8994   for (unsigned i = 0; i < NumElts; ++i) {
8995     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8996     Ops.push_back(V);
8997     // Make the DAGCombiner fold the bitcast.
8998     DCI.AddToWorklist(V.getNode());
8999   }
9000   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9001   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9002   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9003 }
9004
9005 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9006 static SDValue
9007 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9008   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9009   // At that time, we may have inserted bitcasts from integer to float.
9010   // If these bitcasts have survived DAGCombine, change the lowering of this
9011   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9012   // force to use floating point types.
9013
9014   // Make sure we can change the type of the vector.
9015   // This is possible iff:
9016   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9017   //    1.1. Vector is used only once.
9018   //    1.2. Use is a bit convert to an integer type.
9019   // 2. The size of its operands are 32-bits (64-bits are not legal).
9020   EVT VT = N->getValueType(0);
9021   EVT EltVT = VT.getVectorElementType();
9022
9023   // Check 1.1. and 2.
9024   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9025     return SDValue();
9026
9027   // By construction, the input type must be float.
9028   assert(EltVT == MVT::f32 && "Unexpected type!");
9029
9030   // Check 1.2.
9031   SDNode *Use = *N->use_begin();
9032   if (Use->getOpcode() != ISD::BITCAST ||
9033       Use->getValueType(0).isFloatingPoint())
9034     return SDValue();
9035
9036   // Check profitability.
9037   // Model is, if more than half of the relevant operands are bitcast from
9038   // i32, turn the build_vector into a sequence of insert_vector_elt.
9039   // Relevant operands are everything that is not statically
9040   // (i.e., at compile time) bitcasted.
9041   unsigned NumOfBitCastedElts = 0;
9042   unsigned NumElts = VT.getVectorNumElements();
9043   unsigned NumOfRelevantElts = NumElts;
9044   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9045     SDValue Elt = N->getOperand(Idx);
9046     if (Elt->getOpcode() == ISD::BITCAST) {
9047       // Assume only bit cast to i32 will go away.
9048       if (Elt->getOperand(0).getValueType() == MVT::i32)
9049         ++NumOfBitCastedElts;
9050     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9051       // Constants are statically casted, thus do not count them as
9052       // relevant operands.
9053       --NumOfRelevantElts;
9054   }
9055
9056   // Check if more than half of the elements require a non-free bitcast.
9057   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9058     return SDValue();
9059
9060   SelectionDAG &DAG = DCI.DAG;
9061   // Create the new vector type.
9062   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9063   // Check if the type is legal.
9064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9065   if (!TLI.isTypeLegal(VecVT))
9066     return SDValue();
9067
9068   // Combine:
9069   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9070   // => BITCAST INSERT_VECTOR_ELT
9071   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9072   //                      (BITCAST EN), N.
9073   SDValue Vec = DAG.getUNDEF(VecVT);
9074   SDLoc dl(N);
9075   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9076     SDValue V = N->getOperand(Idx);
9077     if (V.getOpcode() == ISD::UNDEF)
9078       continue;
9079     if (V.getOpcode() == ISD::BITCAST &&
9080         V->getOperand(0).getValueType() == MVT::i32)
9081       // Fold obvious case.
9082       V = V.getOperand(0);
9083     else {
9084       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9085       // Make the DAGCombiner fold the bitcasts.
9086       DCI.AddToWorklist(V.getNode());
9087     }
9088     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9089     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9090   }
9091   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9092   // Make the DAGCombiner fold the bitcasts.
9093   DCI.AddToWorklist(Vec.getNode());
9094   return Vec;
9095 }
9096
9097 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9098 /// ISD::INSERT_VECTOR_ELT.
9099 static SDValue PerformInsertEltCombine(SDNode *N,
9100                                        TargetLowering::DAGCombinerInfo &DCI) {
9101   // Bitcast an i64 load inserted into a vector to f64.
9102   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9103   EVT VT = N->getValueType(0);
9104   SDNode *Elt = N->getOperand(1).getNode();
9105   if (VT.getVectorElementType() != MVT::i64 ||
9106       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9107     return SDValue();
9108
9109   SelectionDAG &DAG = DCI.DAG;
9110   SDLoc dl(N);
9111   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9112                                  VT.getVectorNumElements());
9113   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9114   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9115   // Make the DAGCombiner fold the bitcasts.
9116   DCI.AddToWorklist(Vec.getNode());
9117   DCI.AddToWorklist(V.getNode());
9118   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9119                                Vec, V, N->getOperand(2));
9120   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9121 }
9122
9123 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9124 /// ISD::VECTOR_SHUFFLE.
9125 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9126   // The LLVM shufflevector instruction does not require the shuffle mask
9127   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9128   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9129   // operands do not match the mask length, they are extended by concatenating
9130   // them with undef vectors.  That is probably the right thing for other
9131   // targets, but for NEON it is better to concatenate two double-register
9132   // size vector operands into a single quad-register size vector.  Do that
9133   // transformation here:
9134   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9135   //   shuffle(concat(v1, v2), undef)
9136   SDValue Op0 = N->getOperand(0);
9137   SDValue Op1 = N->getOperand(1);
9138   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9139       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9140       Op0.getNumOperands() != 2 ||
9141       Op1.getNumOperands() != 2)
9142     return SDValue();
9143   SDValue Concat0Op1 = Op0.getOperand(1);
9144   SDValue Concat1Op1 = Op1.getOperand(1);
9145   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9146       Concat1Op1.getOpcode() != ISD::UNDEF)
9147     return SDValue();
9148   // Skip the transformation if any of the types are illegal.
9149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9150   EVT VT = N->getValueType(0);
9151   if (!TLI.isTypeLegal(VT) ||
9152       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9153       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9154     return SDValue();
9155
9156   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9157                                   Op0.getOperand(0), Op1.getOperand(0));
9158   // Translate the shuffle mask.
9159   SmallVector<int, 16> NewMask;
9160   unsigned NumElts = VT.getVectorNumElements();
9161   unsigned HalfElts = NumElts/2;
9162   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9163   for (unsigned n = 0; n < NumElts; ++n) {
9164     int MaskElt = SVN->getMaskElt(n);
9165     int NewElt = -1;
9166     if (MaskElt < (int)HalfElts)
9167       NewElt = MaskElt;
9168     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9169       NewElt = HalfElts + MaskElt - NumElts;
9170     NewMask.push_back(NewElt);
9171   }
9172   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9173                               DAG.getUNDEF(VT), NewMask.data());
9174 }
9175
9176 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9177 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9178 /// base address updates.
9179 /// For generic load/stores, the memory type is assumed to be a vector.
9180 /// The caller is assumed to have checked legality.
9181 static SDValue CombineBaseUpdate(SDNode *N,
9182                                  TargetLowering::DAGCombinerInfo &DCI) {
9183   SelectionDAG &DAG = DCI.DAG;
9184   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9185                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9186   const bool isStore = N->getOpcode() == ISD::STORE;
9187   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9188   SDValue Addr = N->getOperand(AddrOpIdx);
9189   MemSDNode *MemN = cast<MemSDNode>(N);
9190   SDLoc dl(N);
9191
9192   // Search for a use of the address operand that is an increment.
9193   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9194          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9195     SDNode *User = *UI;
9196     if (User->getOpcode() != ISD::ADD ||
9197         UI.getUse().getResNo() != Addr.getResNo())
9198       continue;
9199
9200     // Check that the add is independent of the load/store.  Otherwise, folding
9201     // it would create a cycle.
9202     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9203       continue;
9204
9205     // Find the new opcode for the updating load/store.
9206     bool isLoadOp = true;
9207     bool isLaneOp = false;
9208     unsigned NewOpc = 0;
9209     unsigned NumVecs = 0;
9210     if (isIntrinsic) {
9211       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9212       switch (IntNo) {
9213       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9214       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9215         NumVecs = 1; break;
9216       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9217         NumVecs = 2; break;
9218       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9219         NumVecs = 3; break;
9220       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9221         NumVecs = 4; break;
9222       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9223         NumVecs = 2; isLaneOp = true; break;
9224       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9225         NumVecs = 3; isLaneOp = true; break;
9226       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9227         NumVecs = 4; isLaneOp = true; break;
9228       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9229         NumVecs = 1; isLoadOp = false; break;
9230       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9231         NumVecs = 2; isLoadOp = false; break;
9232       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9233         NumVecs = 3; isLoadOp = false; break;
9234       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9235         NumVecs = 4; isLoadOp = false; break;
9236       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9237         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9238       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9239         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9240       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9241         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9242       }
9243     } else {
9244       isLaneOp = true;
9245       switch (N->getOpcode()) {
9246       default: llvm_unreachable("unexpected opcode for Neon base update");
9247       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9248       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9249       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9250       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9251         NumVecs = 1; isLaneOp = false; break;
9252       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9253         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9254       }
9255     }
9256
9257     // Find the size of memory referenced by the load/store.
9258     EVT VecTy;
9259     if (isLoadOp) {
9260       VecTy = N->getValueType(0);
9261     } else if (isIntrinsic) {
9262       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9263     } else {
9264       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9265       VecTy = N->getOperand(1).getValueType();
9266     }
9267
9268     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9269     if (isLaneOp)
9270       NumBytes /= VecTy.getVectorNumElements();
9271
9272     // If the increment is a constant, it must match the memory ref size.
9273     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9274     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9275       uint64_t IncVal = CInc->getZExtValue();
9276       if (IncVal != NumBytes)
9277         continue;
9278     } else if (NumBytes >= 3 * 16) {
9279       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9280       // separate instructions that make it harder to use a non-constant update.
9281       continue;
9282     }
9283
9284     // OK, we found an ADD we can fold into the base update.
9285     // Now, create a _UPD node, taking care of not breaking alignment.
9286
9287     EVT AlignedVecTy = VecTy;
9288     unsigned Alignment = MemN->getAlignment();
9289
9290     // If this is a less-than-standard-aligned load/store, change the type to
9291     // match the standard alignment.
9292     // The alignment is overlooked when selecting _UPD variants; and it's
9293     // easier to introduce bitcasts here than fix that.
9294     // There are 3 ways to get to this base-update combine:
9295     // - intrinsics: they are assumed to be properly aligned (to the standard
9296     //   alignment of the memory type), so we don't need to do anything.
9297     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9298     //   intrinsics, so, likewise, there's nothing to do.
9299     // - generic load/store instructions: the alignment is specified as an
9300     //   explicit operand, rather than implicitly as the standard alignment
9301     //   of the memory type (like the intrisics).  We need to change the
9302     //   memory type to match the explicit alignment.  That way, we don't
9303     //   generate non-standard-aligned ARMISD::VLDx nodes.
9304     if (isa<LSBaseSDNode>(N)) {
9305       if (Alignment == 0)
9306         Alignment = 1;
9307       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9308         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9309         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9310         assert(!isLaneOp && "Unexpected generic load/store lane.");
9311         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9312         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9313       }
9314       // Don't set an explicit alignment on regular load/stores that we want
9315       // to transform to VLD/VST 1_UPD nodes.
9316       // This matches the behavior of regular load/stores, which only get an
9317       // explicit alignment if the MMO alignment is larger than the standard
9318       // alignment of the memory type.
9319       // Intrinsics, however, always get an explicit alignment, set to the
9320       // alignment of the MMO.
9321       Alignment = 1;
9322     }
9323
9324     // Create the new updating load/store node.
9325     // First, create an SDVTList for the new updating node's results.
9326     EVT Tys[6];
9327     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9328     unsigned n;
9329     for (n = 0; n < NumResultVecs; ++n)
9330       Tys[n] = AlignedVecTy;
9331     Tys[n++] = MVT::i32;
9332     Tys[n] = MVT::Other;
9333     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9334
9335     // Then, gather the new node's operands.
9336     SmallVector<SDValue, 8> Ops;
9337     Ops.push_back(N->getOperand(0)); // incoming chain
9338     Ops.push_back(N->getOperand(AddrOpIdx));
9339     Ops.push_back(Inc);
9340
9341     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9342       // Try to match the intrinsic's signature
9343       Ops.push_back(StN->getValue());
9344     } else {
9345       // Loads (and of course intrinsics) match the intrinsics' signature,
9346       // so just add all but the alignment operand.
9347       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9348         Ops.push_back(N->getOperand(i));
9349     }
9350
9351     // For all node types, the alignment operand is always the last one.
9352     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9353
9354     // If this is a non-standard-aligned STORE, the penultimate operand is the
9355     // stored value.  Bitcast it to the aligned type.
9356     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9357       SDValue &StVal = Ops[Ops.size()-2];
9358       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9359     }
9360
9361     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9362                                            Ops, AlignedVecTy,
9363                                            MemN->getMemOperand());
9364
9365     // Update the uses.
9366     SmallVector<SDValue, 5> NewResults;
9367     for (unsigned i = 0; i < NumResultVecs; ++i)
9368       NewResults.push_back(SDValue(UpdN.getNode(), i));
9369
9370     // If this is an non-standard-aligned LOAD, the first result is the loaded
9371     // value.  Bitcast it to the expected result type.
9372     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9373       SDValue &LdVal = NewResults[0];
9374       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9375     }
9376
9377     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9378     DCI.CombineTo(N, NewResults);
9379     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9380
9381     break;
9382   }
9383   return SDValue();
9384 }
9385
9386 static SDValue PerformVLDCombine(SDNode *N,
9387                                  TargetLowering::DAGCombinerInfo &DCI) {
9388   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9389     return SDValue();
9390
9391   return CombineBaseUpdate(N, DCI);
9392 }
9393
9394 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9395 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9396 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9397 /// return true.
9398 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9399   SelectionDAG &DAG = DCI.DAG;
9400   EVT VT = N->getValueType(0);
9401   // vldN-dup instructions only support 64-bit vectors for N > 1.
9402   if (!VT.is64BitVector())
9403     return false;
9404
9405   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9406   SDNode *VLD = N->getOperand(0).getNode();
9407   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9408     return false;
9409   unsigned NumVecs = 0;
9410   unsigned NewOpc = 0;
9411   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9412   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9413     NumVecs = 2;
9414     NewOpc = ARMISD::VLD2DUP;
9415   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9416     NumVecs = 3;
9417     NewOpc = ARMISD::VLD3DUP;
9418   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9419     NumVecs = 4;
9420     NewOpc = ARMISD::VLD4DUP;
9421   } else {
9422     return false;
9423   }
9424
9425   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9426   // numbers match the load.
9427   unsigned VLDLaneNo =
9428     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9429   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9430        UI != UE; ++UI) {
9431     // Ignore uses of the chain result.
9432     if (UI.getUse().getResNo() == NumVecs)
9433       continue;
9434     SDNode *User = *UI;
9435     if (User->getOpcode() != ARMISD::VDUPLANE ||
9436         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9437       return false;
9438   }
9439
9440   // Create the vldN-dup node.
9441   EVT Tys[5];
9442   unsigned n;
9443   for (n = 0; n < NumVecs; ++n)
9444     Tys[n] = VT;
9445   Tys[n] = MVT::Other;
9446   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9447   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9448   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9449   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9450                                            Ops, VLDMemInt->getMemoryVT(),
9451                                            VLDMemInt->getMemOperand());
9452
9453   // Update the uses.
9454   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9455        UI != UE; ++UI) {
9456     unsigned ResNo = UI.getUse().getResNo();
9457     // Ignore uses of the chain result.
9458     if (ResNo == NumVecs)
9459       continue;
9460     SDNode *User = *UI;
9461     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9462   }
9463
9464   // Now the vldN-lane intrinsic is dead except for its chain result.
9465   // Update uses of the chain.
9466   std::vector<SDValue> VLDDupResults;
9467   for (unsigned n = 0; n < NumVecs; ++n)
9468     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9469   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9470   DCI.CombineTo(VLD, VLDDupResults);
9471
9472   return true;
9473 }
9474
9475 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9476 /// ARMISD::VDUPLANE.
9477 static SDValue PerformVDUPLANECombine(SDNode *N,
9478                                       TargetLowering::DAGCombinerInfo &DCI) {
9479   SDValue Op = N->getOperand(0);
9480
9481   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9482   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9483   if (CombineVLDDUP(N, DCI))
9484     return SDValue(N, 0);
9485
9486   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9487   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9488   while (Op.getOpcode() == ISD::BITCAST)
9489     Op = Op.getOperand(0);
9490   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9491     return SDValue();
9492
9493   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9494   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9495   // The canonical VMOV for a zero vector uses a 32-bit element size.
9496   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9497   unsigned EltBits;
9498   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9499     EltSize = 8;
9500   EVT VT = N->getValueType(0);
9501   if (EltSize > VT.getVectorElementType().getSizeInBits())
9502     return SDValue();
9503
9504   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9505 }
9506
9507 static SDValue PerformLOADCombine(SDNode *N,
9508                                   TargetLowering::DAGCombinerInfo &DCI) {
9509   EVT VT = N->getValueType(0);
9510
9511   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9512   if (ISD::isNormalLoad(N) && VT.isVector() &&
9513       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9514     return CombineBaseUpdate(N, DCI);
9515
9516   return SDValue();
9517 }
9518
9519 /// PerformSTORECombine - Target-specific dag combine xforms for
9520 /// ISD::STORE.
9521 static SDValue PerformSTORECombine(SDNode *N,
9522                                    TargetLowering::DAGCombinerInfo &DCI) {
9523   StoreSDNode *St = cast<StoreSDNode>(N);
9524   if (St->isVolatile())
9525     return SDValue();
9526
9527   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9528   // pack all of the elements in one place.  Next, store to memory in fewer
9529   // chunks.
9530   SDValue StVal = St->getValue();
9531   EVT VT = StVal.getValueType();
9532   if (St->isTruncatingStore() && VT.isVector()) {
9533     SelectionDAG &DAG = DCI.DAG;
9534     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9535     EVT StVT = St->getMemoryVT();
9536     unsigned NumElems = VT.getVectorNumElements();
9537     assert(StVT != VT && "Cannot truncate to the same type");
9538     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9539     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9540
9541     // From, To sizes and ElemCount must be pow of two
9542     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9543
9544     // We are going to use the original vector elt for storing.
9545     // Accumulated smaller vector elements must be a multiple of the store size.
9546     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9547
9548     unsigned SizeRatio  = FromEltSz / ToEltSz;
9549     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9550
9551     // Create a type on which we perform the shuffle.
9552     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9553                                      NumElems*SizeRatio);
9554     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9555
9556     SDLoc DL(St);
9557     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9558     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9559     for (unsigned i = 0; i < NumElems; ++i)
9560       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9561                           ? (i + 1) * SizeRatio - 1
9562                           : i * SizeRatio;
9563
9564     // Can't shuffle using an illegal type.
9565     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9566
9567     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9568                                 DAG.getUNDEF(WideVec.getValueType()),
9569                                 ShuffleVec.data());
9570     // At this point all of the data is stored at the bottom of the
9571     // register. We now need to save it to mem.
9572
9573     // Find the largest store unit
9574     MVT StoreType = MVT::i8;
9575     for (MVT Tp : MVT::integer_valuetypes()) {
9576       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9577         StoreType = Tp;
9578     }
9579     // Didn't find a legal store type.
9580     if (!TLI.isTypeLegal(StoreType))
9581       return SDValue();
9582
9583     // Bitcast the original vector into a vector of store-size units
9584     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9585             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9586     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9587     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9588     SmallVector<SDValue, 8> Chains;
9589     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9590                                         TLI.getPointerTy(DAG.getDataLayout()));
9591     SDValue BasePtr = St->getBasePtr();
9592
9593     // Perform one or more big stores into memory.
9594     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9595     for (unsigned I = 0; I < E; I++) {
9596       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9597                                    StoreType, ShuffWide,
9598                                    DAG.getIntPtrConstant(I, DL));
9599       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9600                                 St->getPointerInfo(), St->isVolatile(),
9601                                 St->isNonTemporal(), St->getAlignment());
9602       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9603                             Increment);
9604       Chains.push_back(Ch);
9605     }
9606     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9607   }
9608
9609   if (!ISD::isNormalStore(St))
9610     return SDValue();
9611
9612   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9613   // ARM stores of arguments in the same cache line.
9614   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9615       StVal.getNode()->hasOneUse()) {
9616     SelectionDAG  &DAG = DCI.DAG;
9617     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9618     SDLoc DL(St);
9619     SDValue BasePtr = St->getBasePtr();
9620     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9621                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9622                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9623                                   St->isNonTemporal(), St->getAlignment());
9624
9625     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9626                                     DAG.getConstant(4, DL, MVT::i32));
9627     return DAG.getStore(NewST1.getValue(0), DL,
9628                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9629                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9630                         St->isNonTemporal(),
9631                         std::min(4U, St->getAlignment() / 2));
9632   }
9633
9634   if (StVal.getValueType() == MVT::i64 &&
9635       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9636
9637     // Bitcast an i64 store extracted from a vector to f64.
9638     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9639     SelectionDAG &DAG = DCI.DAG;
9640     SDLoc dl(StVal);
9641     SDValue IntVec = StVal.getOperand(0);
9642     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9643                                    IntVec.getValueType().getVectorNumElements());
9644     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9645     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9646                                  Vec, StVal.getOperand(1));
9647     dl = SDLoc(N);
9648     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9649     // Make the DAGCombiner fold the bitcasts.
9650     DCI.AddToWorklist(Vec.getNode());
9651     DCI.AddToWorklist(ExtElt.getNode());
9652     DCI.AddToWorklist(V.getNode());
9653     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9654                         St->getPointerInfo(), St->isVolatile(),
9655                         St->isNonTemporal(), St->getAlignment(),
9656                         St->getAAInfo());
9657   }
9658
9659   // If this is a legal vector store, try to combine it into a VST1_UPD.
9660   if (ISD::isNormalStore(N) && VT.isVector() &&
9661       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9662     return CombineBaseUpdate(N, DCI);
9663
9664   return SDValue();
9665 }
9666
9667 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9668 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9669 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9670 {
9671   integerPart cN;
9672   integerPart c0 = 0;
9673   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9674        I != E; I++) {
9675     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9676     if (!C)
9677       return false;
9678
9679     bool isExact;
9680     APFloat APF = C->getValueAPF();
9681     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9682         != APFloat::opOK || !isExact)
9683       return false;
9684
9685     c0 = (I == 0) ? cN : c0;
9686     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9687       return false;
9688   }
9689   C = c0;
9690   return true;
9691 }
9692
9693 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9694 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9695 /// when the VMUL has a constant operand that is a power of 2.
9696 ///
9697 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9698 ///  vmul.f32        d16, d17, d16
9699 ///  vcvt.s32.f32    d16, d16
9700 /// becomes:
9701 ///  vcvt.s32.f32    d16, d16, #3
9702 static SDValue PerformVCVTCombine(SDNode *N,
9703                                   TargetLowering::DAGCombinerInfo &DCI,
9704                                   const ARMSubtarget *Subtarget) {
9705   SelectionDAG &DAG = DCI.DAG;
9706   SDValue Op = N->getOperand(0);
9707
9708   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9709       Op.getOpcode() != ISD::FMUL)
9710     return SDValue();
9711
9712   uint64_t C;
9713   SDValue N0 = Op->getOperand(0);
9714   SDValue ConstVec = Op->getOperand(1);
9715   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9716
9717   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9718       !isConstVecPow2(ConstVec, isSigned, C))
9719     return SDValue();
9720
9721   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9722   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9723   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9724   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9725       NumLanes > 4) {
9726     // These instructions only exist converting from f32 to i32. We can handle
9727     // smaller integers by generating an extra truncate, but larger ones would
9728     // be lossy. We also can't handle more then 4 lanes, since these intructions
9729     // only support v2i32/v4i32 types.
9730     return SDValue();
9731   }
9732
9733   SDLoc dl(N);
9734   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9735     Intrinsic::arm_neon_vcvtfp2fxu;
9736   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9737                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9738                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9739                                  N0,
9740                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9741
9742   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9743     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9744
9745   return FixConv;
9746 }
9747
9748 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9749 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9750 /// when the VDIV has a constant operand that is a power of 2.
9751 ///
9752 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9753 ///  vcvt.f32.s32    d16, d16
9754 ///  vdiv.f32        d16, d17, d16
9755 /// becomes:
9756 ///  vcvt.f32.s32    d16, d16, #3
9757 static SDValue PerformVDIVCombine(SDNode *N,
9758                                   TargetLowering::DAGCombinerInfo &DCI,
9759                                   const ARMSubtarget *Subtarget) {
9760   SelectionDAG &DAG = DCI.DAG;
9761   SDValue Op = N->getOperand(0);
9762   unsigned OpOpcode = Op.getNode()->getOpcode();
9763
9764   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9765       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9766     return SDValue();
9767
9768   uint64_t C;
9769   SDValue ConstVec = N->getOperand(1);
9770   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9771
9772   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9773       !isConstVecPow2(ConstVec, isSigned, C))
9774     return SDValue();
9775
9776   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9777   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9778   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9779     // These instructions only exist converting from i32 to f32. We can handle
9780     // smaller integers by generating an extra extend, but larger ones would
9781     // be lossy.
9782     return SDValue();
9783   }
9784
9785   SDLoc dl(N);
9786   SDValue ConvInput = Op.getOperand(0);
9787   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9788   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9789     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9790                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9791                             ConvInput);
9792
9793   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9794     Intrinsic::arm_neon_vcvtfxu2fp;
9795   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9796                      Op.getValueType(),
9797                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9798                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9799 }
9800
9801 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9802 /// operand of a vector shift operation, where all the elements of the
9803 /// build_vector must have the same constant integer value.
9804 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9805   // Ignore bit_converts.
9806   while (Op.getOpcode() == ISD::BITCAST)
9807     Op = Op.getOperand(0);
9808   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9809   APInt SplatBits, SplatUndef;
9810   unsigned SplatBitSize;
9811   bool HasAnyUndefs;
9812   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9813                                       HasAnyUndefs, ElementBits) ||
9814       SplatBitSize > ElementBits)
9815     return false;
9816   Cnt = SplatBits.getSExtValue();
9817   return true;
9818 }
9819
9820 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9821 /// operand of a vector shift left operation.  That value must be in the range:
9822 ///   0 <= Value < ElementBits for a left shift; or
9823 ///   0 <= Value <= ElementBits for a long left shift.
9824 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9825   assert(VT.isVector() && "vector shift count is not a vector type");
9826   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9827   if (! getVShiftImm(Op, ElementBits, Cnt))
9828     return false;
9829   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9830 }
9831
9832 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9833 /// operand of a vector shift right operation.  For a shift opcode, the value
9834 /// is positive, but for an intrinsic the value count must be negative. The
9835 /// absolute value must be in the range:
9836 ///   1 <= |Value| <= ElementBits for a right shift; or
9837 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9838 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9839                          int64_t &Cnt) {
9840   assert(VT.isVector() && "vector shift count is not a vector type");
9841   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9842   if (! getVShiftImm(Op, ElementBits, Cnt))
9843     return false;
9844   if (!isIntrinsic)
9845     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9846   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9847     Cnt = -Cnt;
9848     return true;
9849   }
9850   return false;
9851 }
9852
9853 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9854 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9855   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9856   switch (IntNo) {
9857   default:
9858     // Don't do anything for most intrinsics.
9859     break;
9860
9861   case Intrinsic::arm_neon_vabds:
9862     if (!N->getValueType(0).isInteger())
9863       return SDValue();
9864     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9865                        N->getOperand(1), N->getOperand(2));
9866   case Intrinsic::arm_neon_vabdu:
9867     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9868                        N->getOperand(1), N->getOperand(2));
9869
9870   // Vector shifts: check for immediate versions and lower them.
9871   // Note: This is done during DAG combining instead of DAG legalizing because
9872   // the build_vectors for 64-bit vector element shift counts are generally
9873   // not legal, and it is hard to see their values after they get legalized to
9874   // loads from a constant pool.
9875   case Intrinsic::arm_neon_vshifts:
9876   case Intrinsic::arm_neon_vshiftu:
9877   case Intrinsic::arm_neon_vrshifts:
9878   case Intrinsic::arm_neon_vrshiftu:
9879   case Intrinsic::arm_neon_vrshiftn:
9880   case Intrinsic::arm_neon_vqshifts:
9881   case Intrinsic::arm_neon_vqshiftu:
9882   case Intrinsic::arm_neon_vqshiftsu:
9883   case Intrinsic::arm_neon_vqshiftns:
9884   case Intrinsic::arm_neon_vqshiftnu:
9885   case Intrinsic::arm_neon_vqshiftnsu:
9886   case Intrinsic::arm_neon_vqrshiftns:
9887   case Intrinsic::arm_neon_vqrshiftnu:
9888   case Intrinsic::arm_neon_vqrshiftnsu: {
9889     EVT VT = N->getOperand(1).getValueType();
9890     int64_t Cnt;
9891     unsigned VShiftOpc = 0;
9892
9893     switch (IntNo) {
9894     case Intrinsic::arm_neon_vshifts:
9895     case Intrinsic::arm_neon_vshiftu:
9896       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9897         VShiftOpc = ARMISD::VSHL;
9898         break;
9899       }
9900       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9901         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9902                      ARMISD::VSHRs : ARMISD::VSHRu);
9903         break;
9904       }
9905       return SDValue();
9906
9907     case Intrinsic::arm_neon_vrshifts:
9908     case Intrinsic::arm_neon_vrshiftu:
9909       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9910         break;
9911       return SDValue();
9912
9913     case Intrinsic::arm_neon_vqshifts:
9914     case Intrinsic::arm_neon_vqshiftu:
9915       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9916         break;
9917       return SDValue();
9918
9919     case Intrinsic::arm_neon_vqshiftsu:
9920       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9921         break;
9922       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9923
9924     case Intrinsic::arm_neon_vrshiftn:
9925     case Intrinsic::arm_neon_vqshiftns:
9926     case Intrinsic::arm_neon_vqshiftnu:
9927     case Intrinsic::arm_neon_vqshiftnsu:
9928     case Intrinsic::arm_neon_vqrshiftns:
9929     case Intrinsic::arm_neon_vqrshiftnu:
9930     case Intrinsic::arm_neon_vqrshiftnsu:
9931       // Narrowing shifts require an immediate right shift.
9932       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9933         break;
9934       llvm_unreachable("invalid shift count for narrowing vector shift "
9935                        "intrinsic");
9936
9937     default:
9938       llvm_unreachable("unhandled vector shift");
9939     }
9940
9941     switch (IntNo) {
9942     case Intrinsic::arm_neon_vshifts:
9943     case Intrinsic::arm_neon_vshiftu:
9944       // Opcode already set above.
9945       break;
9946     case Intrinsic::arm_neon_vrshifts:
9947       VShiftOpc = ARMISD::VRSHRs; break;
9948     case Intrinsic::arm_neon_vrshiftu:
9949       VShiftOpc = ARMISD::VRSHRu; break;
9950     case Intrinsic::arm_neon_vrshiftn:
9951       VShiftOpc = ARMISD::VRSHRN; break;
9952     case Intrinsic::arm_neon_vqshifts:
9953       VShiftOpc = ARMISD::VQSHLs; break;
9954     case Intrinsic::arm_neon_vqshiftu:
9955       VShiftOpc = ARMISD::VQSHLu; break;
9956     case Intrinsic::arm_neon_vqshiftsu:
9957       VShiftOpc = ARMISD::VQSHLsu; break;
9958     case Intrinsic::arm_neon_vqshiftns:
9959       VShiftOpc = ARMISD::VQSHRNs; break;
9960     case Intrinsic::arm_neon_vqshiftnu:
9961       VShiftOpc = ARMISD::VQSHRNu; break;
9962     case Intrinsic::arm_neon_vqshiftnsu:
9963       VShiftOpc = ARMISD::VQSHRNsu; break;
9964     case Intrinsic::arm_neon_vqrshiftns:
9965       VShiftOpc = ARMISD::VQRSHRNs; break;
9966     case Intrinsic::arm_neon_vqrshiftnu:
9967       VShiftOpc = ARMISD::VQRSHRNu; break;
9968     case Intrinsic::arm_neon_vqrshiftnsu:
9969       VShiftOpc = ARMISD::VQRSHRNsu; break;
9970     }
9971
9972     SDLoc dl(N);
9973     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9974                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9975   }
9976
9977   case Intrinsic::arm_neon_vshiftins: {
9978     EVT VT = N->getOperand(1).getValueType();
9979     int64_t Cnt;
9980     unsigned VShiftOpc = 0;
9981
9982     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9983       VShiftOpc = ARMISD::VSLI;
9984     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9985       VShiftOpc = ARMISD::VSRI;
9986     else {
9987       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9988     }
9989
9990     SDLoc dl(N);
9991     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9992                        N->getOperand(1), N->getOperand(2),
9993                        DAG.getConstant(Cnt, dl, MVT::i32));
9994   }
9995
9996   case Intrinsic::arm_neon_vqrshifts:
9997   case Intrinsic::arm_neon_vqrshiftu:
9998     // No immediate versions of these to check for.
9999     break;
10000   }
10001
10002   return SDValue();
10003 }
10004
10005 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10006 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10007 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10008 /// vector element shift counts are generally not legal, and it is hard to see
10009 /// their values after they get legalized to loads from a constant pool.
10010 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10011                                    const ARMSubtarget *ST) {
10012   EVT VT = N->getValueType(0);
10013   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10014     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10015     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10016     SDValue N1 = N->getOperand(1);
10017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10018       SDValue N0 = N->getOperand(0);
10019       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10020           DAG.MaskedValueIsZero(N0.getOperand(0),
10021                                 APInt::getHighBitsSet(32, 16)))
10022         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10023     }
10024   }
10025
10026   // Nothing to be done for scalar shifts.
10027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10028   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10029     return SDValue();
10030
10031   assert(ST->hasNEON() && "unexpected vector shift");
10032   int64_t Cnt;
10033
10034   switch (N->getOpcode()) {
10035   default: llvm_unreachable("unexpected shift opcode");
10036
10037   case ISD::SHL:
10038     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10039       SDLoc dl(N);
10040       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10041                          DAG.getConstant(Cnt, dl, MVT::i32));
10042     }
10043     break;
10044
10045   case ISD::SRA:
10046   case ISD::SRL:
10047     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10048       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10049                             ARMISD::VSHRs : ARMISD::VSHRu);
10050       SDLoc dl(N);
10051       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10052                          DAG.getConstant(Cnt, dl, MVT::i32));
10053     }
10054   }
10055   return SDValue();
10056 }
10057
10058 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10059 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10060 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10061                                     const ARMSubtarget *ST) {
10062   SDValue N0 = N->getOperand(0);
10063
10064   // Check for sign- and zero-extensions of vector extract operations of 8-
10065   // and 16-bit vector elements.  NEON supports these directly.  They are
10066   // handled during DAG combining because type legalization will promote them
10067   // to 32-bit types and it is messy to recognize the operations after that.
10068   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10069     SDValue Vec = N0.getOperand(0);
10070     SDValue Lane = N0.getOperand(1);
10071     EVT VT = N->getValueType(0);
10072     EVT EltVT = N0.getValueType();
10073     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10074
10075     if (VT == MVT::i32 &&
10076         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10077         TLI.isTypeLegal(Vec.getValueType()) &&
10078         isa<ConstantSDNode>(Lane)) {
10079
10080       unsigned Opc = 0;
10081       switch (N->getOpcode()) {
10082       default: llvm_unreachable("unexpected opcode");
10083       case ISD::SIGN_EXTEND:
10084         Opc = ARMISD::VGETLANEs;
10085         break;
10086       case ISD::ZERO_EXTEND:
10087       case ISD::ANY_EXTEND:
10088         Opc = ARMISD::VGETLANEu;
10089         break;
10090       }
10091       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10092     }
10093   }
10094
10095   return SDValue();
10096 }
10097
10098 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10099 SDValue
10100 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10101   SDValue Cmp = N->getOperand(4);
10102   if (Cmp.getOpcode() != ARMISD::CMPZ)
10103     // Only looking at EQ and NE cases.
10104     return SDValue();
10105
10106   EVT VT = N->getValueType(0);
10107   SDLoc dl(N);
10108   SDValue LHS = Cmp.getOperand(0);
10109   SDValue RHS = Cmp.getOperand(1);
10110   SDValue FalseVal = N->getOperand(0);
10111   SDValue TrueVal = N->getOperand(1);
10112   SDValue ARMcc = N->getOperand(2);
10113   ARMCC::CondCodes CC =
10114     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10115
10116   // Simplify
10117   //   mov     r1, r0
10118   //   cmp     r1, x
10119   //   mov     r0, y
10120   //   moveq   r0, x
10121   // to
10122   //   cmp     r0, x
10123   //   movne   r0, y
10124   //
10125   //   mov     r1, r0
10126   //   cmp     r1, x
10127   //   mov     r0, x
10128   //   movne   r0, y
10129   // to
10130   //   cmp     r0, x
10131   //   movne   r0, y
10132   /// FIXME: Turn this into a target neutral optimization?
10133   SDValue Res;
10134   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10135     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10136                       N->getOperand(3), Cmp);
10137   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10138     SDValue ARMcc;
10139     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10140     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10141                       N->getOperand(3), NewCmp);
10142   }
10143
10144   if (Res.getNode()) {
10145     APInt KnownZero, KnownOne;
10146     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10147     // Capture demanded bits information that would be otherwise lost.
10148     if (KnownZero == 0xfffffffe)
10149       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10150                         DAG.getValueType(MVT::i1));
10151     else if (KnownZero == 0xffffff00)
10152       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10153                         DAG.getValueType(MVT::i8));
10154     else if (KnownZero == 0xffff0000)
10155       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10156                         DAG.getValueType(MVT::i16));
10157   }
10158
10159   return Res;
10160 }
10161
10162 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10163                                              DAGCombinerInfo &DCI) const {
10164   switch (N->getOpcode()) {
10165   default: break;
10166   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10167   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10168   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10169   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10170   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10171   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10172   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10173   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10174   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10175   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10176   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10177   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10178   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10179   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10180   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10181   case ISD::FP_TO_SINT:
10182   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10183   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10184   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10185   case ISD::SHL:
10186   case ISD::SRA:
10187   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10188   case ISD::SIGN_EXTEND:
10189   case ISD::ZERO_EXTEND:
10190   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10191   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10192   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10193   case ARMISD::VLD2DUP:
10194   case ARMISD::VLD3DUP:
10195   case ARMISD::VLD4DUP:
10196     return PerformVLDCombine(N, DCI);
10197   case ARMISD::BUILD_VECTOR:
10198     return PerformARMBUILD_VECTORCombine(N, DCI);
10199   case ISD::INTRINSIC_VOID:
10200   case ISD::INTRINSIC_W_CHAIN:
10201     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10202     case Intrinsic::arm_neon_vld1:
10203     case Intrinsic::arm_neon_vld2:
10204     case Intrinsic::arm_neon_vld3:
10205     case Intrinsic::arm_neon_vld4:
10206     case Intrinsic::arm_neon_vld2lane:
10207     case Intrinsic::arm_neon_vld3lane:
10208     case Intrinsic::arm_neon_vld4lane:
10209     case Intrinsic::arm_neon_vst1:
10210     case Intrinsic::arm_neon_vst2:
10211     case Intrinsic::arm_neon_vst3:
10212     case Intrinsic::arm_neon_vst4:
10213     case Intrinsic::arm_neon_vst2lane:
10214     case Intrinsic::arm_neon_vst3lane:
10215     case Intrinsic::arm_neon_vst4lane:
10216       return PerformVLDCombine(N, DCI);
10217     default: break;
10218     }
10219     break;
10220   }
10221   return SDValue();
10222 }
10223
10224 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10225                                                           EVT VT) const {
10226   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10227 }
10228
10229 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10230                                                        unsigned,
10231                                                        unsigned,
10232                                                        bool *Fast) const {
10233   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10234   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10235
10236   switch (VT.getSimpleVT().SimpleTy) {
10237   default:
10238     return false;
10239   case MVT::i8:
10240   case MVT::i16:
10241   case MVT::i32: {
10242     // Unaligned access can use (for example) LRDB, LRDH, LDR
10243     if (AllowsUnaligned) {
10244       if (Fast)
10245         *Fast = Subtarget->hasV7Ops();
10246       return true;
10247     }
10248     return false;
10249   }
10250   case MVT::f64:
10251   case MVT::v2f64: {
10252     // For any little-endian targets with neon, we can support unaligned ld/st
10253     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10254     // A big-endian target may also explicitly support unaligned accesses
10255     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10256       if (Fast)
10257         *Fast = true;
10258       return true;
10259     }
10260     return false;
10261   }
10262   }
10263 }
10264
10265 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10266                        unsigned AlignCheck) {
10267   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10268           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10269 }
10270
10271 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10272                                            unsigned DstAlign, unsigned SrcAlign,
10273                                            bool IsMemset, bool ZeroMemset,
10274                                            bool MemcpyStrSrc,
10275                                            MachineFunction &MF) const {
10276   const Function *F = MF.getFunction();
10277
10278   // See if we can use NEON instructions for this...
10279   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10280       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10281     bool Fast;
10282     if (Size >= 16 &&
10283         (memOpAlign(SrcAlign, DstAlign, 16) ||
10284          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10285       return MVT::v2f64;
10286     } else if (Size >= 8 &&
10287                (memOpAlign(SrcAlign, DstAlign, 8) ||
10288                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10289                  Fast))) {
10290       return MVT::f64;
10291     }
10292   }
10293
10294   // Lowering to i32/i16 if the size permits.
10295   if (Size >= 4)
10296     return MVT::i32;
10297   else if (Size >= 2)
10298     return MVT::i16;
10299
10300   // Let the target-independent logic figure it out.
10301   return MVT::Other;
10302 }
10303
10304 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10305   if (Val.getOpcode() != ISD::LOAD)
10306     return false;
10307
10308   EVT VT1 = Val.getValueType();
10309   if (!VT1.isSimple() || !VT1.isInteger() ||
10310       !VT2.isSimple() || !VT2.isInteger())
10311     return false;
10312
10313   switch (VT1.getSimpleVT().SimpleTy) {
10314   default: break;
10315   case MVT::i1:
10316   case MVT::i8:
10317   case MVT::i16:
10318     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10319     return true;
10320   }
10321
10322   return false;
10323 }
10324
10325 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10326   EVT VT = ExtVal.getValueType();
10327
10328   if (!isTypeLegal(VT))
10329     return false;
10330
10331   // Don't create a loadext if we can fold the extension into a wide/long
10332   // instruction.
10333   // If there's more than one user instruction, the loadext is desirable no
10334   // matter what.  There can be two uses by the same instruction.
10335   if (ExtVal->use_empty() ||
10336       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10337     return true;
10338
10339   SDNode *U = *ExtVal->use_begin();
10340   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10341        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10342     return false;
10343
10344   return true;
10345 }
10346
10347 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10348   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10349     return false;
10350
10351   if (!isTypeLegal(EVT::getEVT(Ty1)))
10352     return false;
10353
10354   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10355
10356   // Assuming the caller doesn't have a zeroext or signext return parameter,
10357   // truncation all the way down to i1 is valid.
10358   return true;
10359 }
10360
10361
10362 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10363   if (V < 0)
10364     return false;
10365
10366   unsigned Scale = 1;
10367   switch (VT.getSimpleVT().SimpleTy) {
10368   default: return false;
10369   case MVT::i1:
10370   case MVT::i8:
10371     // Scale == 1;
10372     break;
10373   case MVT::i16:
10374     // Scale == 2;
10375     Scale = 2;
10376     break;
10377   case MVT::i32:
10378     // Scale == 4;
10379     Scale = 4;
10380     break;
10381   }
10382
10383   if ((V & (Scale - 1)) != 0)
10384     return false;
10385   V /= Scale;
10386   return V == (V & ((1LL << 5) - 1));
10387 }
10388
10389 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10390                                       const ARMSubtarget *Subtarget) {
10391   bool isNeg = false;
10392   if (V < 0) {
10393     isNeg = true;
10394     V = - V;
10395   }
10396
10397   switch (VT.getSimpleVT().SimpleTy) {
10398   default: return false;
10399   case MVT::i1:
10400   case MVT::i8:
10401   case MVT::i16:
10402   case MVT::i32:
10403     // + imm12 or - imm8
10404     if (isNeg)
10405       return V == (V & ((1LL << 8) - 1));
10406     return V == (V & ((1LL << 12) - 1));
10407   case MVT::f32:
10408   case MVT::f64:
10409     // Same as ARM mode. FIXME: NEON?
10410     if (!Subtarget->hasVFP2())
10411       return false;
10412     if ((V & 3) != 0)
10413       return false;
10414     V >>= 2;
10415     return V == (V & ((1LL << 8) - 1));
10416   }
10417 }
10418
10419 /// isLegalAddressImmediate - Return true if the integer value can be used
10420 /// as the offset of the target addressing mode for load / store of the
10421 /// given type.
10422 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10423                                     const ARMSubtarget *Subtarget) {
10424   if (V == 0)
10425     return true;
10426
10427   if (!VT.isSimple())
10428     return false;
10429
10430   if (Subtarget->isThumb1Only())
10431     return isLegalT1AddressImmediate(V, VT);
10432   else if (Subtarget->isThumb2())
10433     return isLegalT2AddressImmediate(V, VT, Subtarget);
10434
10435   // ARM mode.
10436   if (V < 0)
10437     V = - V;
10438   switch (VT.getSimpleVT().SimpleTy) {
10439   default: return false;
10440   case MVT::i1:
10441   case MVT::i8:
10442   case MVT::i32:
10443     // +- imm12
10444     return V == (V & ((1LL << 12) - 1));
10445   case MVT::i16:
10446     // +- imm8
10447     return V == (V & ((1LL << 8) - 1));
10448   case MVT::f32:
10449   case MVT::f64:
10450     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10451       return false;
10452     if ((V & 3) != 0)
10453       return false;
10454     V >>= 2;
10455     return V == (V & ((1LL << 8) - 1));
10456   }
10457 }
10458
10459 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10460                                                       EVT VT) const {
10461   int Scale = AM.Scale;
10462   if (Scale < 0)
10463     return false;
10464
10465   switch (VT.getSimpleVT().SimpleTy) {
10466   default: return false;
10467   case MVT::i1:
10468   case MVT::i8:
10469   case MVT::i16:
10470   case MVT::i32:
10471     if (Scale == 1)
10472       return true;
10473     // r + r << imm
10474     Scale = Scale & ~1;
10475     return Scale == 2 || Scale == 4 || Scale == 8;
10476   case MVT::i64:
10477     // r + r
10478     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10479       return true;
10480     return false;
10481   case MVT::isVoid:
10482     // Note, we allow "void" uses (basically, uses that aren't loads or
10483     // stores), because arm allows folding a scale into many arithmetic
10484     // operations.  This should be made more precise and revisited later.
10485
10486     // Allow r << imm, but the imm has to be a multiple of two.
10487     if (Scale & 1) return false;
10488     return isPowerOf2_32(Scale);
10489   }
10490 }
10491
10492 /// isLegalAddressingMode - Return true if the addressing mode represented
10493 /// by AM is legal for this target, for a load/store of the specified type.
10494 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10495                                               const AddrMode &AM, Type *Ty,
10496                                               unsigned AS) const {
10497   EVT VT = getValueType(DL, Ty, true);
10498   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10499     return false;
10500
10501   // Can never fold addr of global into load/store.
10502   if (AM.BaseGV)
10503     return false;
10504
10505   switch (AM.Scale) {
10506   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10507     break;
10508   case 1:
10509     if (Subtarget->isThumb1Only())
10510       return false;
10511     // FALL THROUGH.
10512   default:
10513     // ARM doesn't support any R+R*scale+imm addr modes.
10514     if (AM.BaseOffs)
10515       return false;
10516
10517     if (!VT.isSimple())
10518       return false;
10519
10520     if (Subtarget->isThumb2())
10521       return isLegalT2ScaledAddressingMode(AM, VT);
10522
10523     int Scale = AM.Scale;
10524     switch (VT.getSimpleVT().SimpleTy) {
10525     default: return false;
10526     case MVT::i1:
10527     case MVT::i8:
10528     case MVT::i32:
10529       if (Scale < 0) Scale = -Scale;
10530       if (Scale == 1)
10531         return true;
10532       // r + r << imm
10533       return isPowerOf2_32(Scale & ~1);
10534     case MVT::i16:
10535     case MVT::i64:
10536       // r + r
10537       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10538         return true;
10539       return false;
10540
10541     case MVT::isVoid:
10542       // Note, we allow "void" uses (basically, uses that aren't loads or
10543       // stores), because arm allows folding a scale into many arithmetic
10544       // operations.  This should be made more precise and revisited later.
10545
10546       // Allow r << imm, but the imm has to be a multiple of two.
10547       if (Scale & 1) return false;
10548       return isPowerOf2_32(Scale);
10549     }
10550   }
10551   return true;
10552 }
10553
10554 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10555 /// icmp immediate, that is the target has icmp instructions which can compare
10556 /// a register against the immediate without having to materialize the
10557 /// immediate into a register.
10558 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10559   // Thumb2 and ARM modes can use cmn for negative immediates.
10560   if (!Subtarget->isThumb())
10561     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10562   if (Subtarget->isThumb2())
10563     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10564   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10565   return Imm >= 0 && Imm <= 255;
10566 }
10567
10568 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10569 /// *or sub* immediate, that is the target has add or sub instructions which can
10570 /// add a register with the immediate without having to materialize the
10571 /// immediate into a register.
10572 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10573   // Same encoding for add/sub, just flip the sign.
10574   int64_t AbsImm = std::abs(Imm);
10575   if (!Subtarget->isThumb())
10576     return ARM_AM::getSOImmVal(AbsImm) != -1;
10577   if (Subtarget->isThumb2())
10578     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10579   // Thumb1 only has 8-bit unsigned immediate.
10580   return AbsImm >= 0 && AbsImm <= 255;
10581 }
10582
10583 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10584                                       bool isSEXTLoad, SDValue &Base,
10585                                       SDValue &Offset, bool &isInc,
10586                                       SelectionDAG &DAG) {
10587   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10588     return false;
10589
10590   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10591     // AddressingMode 3
10592     Base = Ptr->getOperand(0);
10593     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10594       int RHSC = (int)RHS->getZExtValue();
10595       if (RHSC < 0 && RHSC > -256) {
10596         assert(Ptr->getOpcode() == ISD::ADD);
10597         isInc = false;
10598         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10599         return true;
10600       }
10601     }
10602     isInc = (Ptr->getOpcode() == ISD::ADD);
10603     Offset = Ptr->getOperand(1);
10604     return true;
10605   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10606     // AddressingMode 2
10607     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10608       int RHSC = (int)RHS->getZExtValue();
10609       if (RHSC < 0 && RHSC > -0x1000) {
10610         assert(Ptr->getOpcode() == ISD::ADD);
10611         isInc = false;
10612         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10613         Base = Ptr->getOperand(0);
10614         return true;
10615       }
10616     }
10617
10618     if (Ptr->getOpcode() == ISD::ADD) {
10619       isInc = true;
10620       ARM_AM::ShiftOpc ShOpcVal=
10621         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10622       if (ShOpcVal != ARM_AM::no_shift) {
10623         Base = Ptr->getOperand(1);
10624         Offset = Ptr->getOperand(0);
10625       } else {
10626         Base = Ptr->getOperand(0);
10627         Offset = Ptr->getOperand(1);
10628       }
10629       return true;
10630     }
10631
10632     isInc = (Ptr->getOpcode() == ISD::ADD);
10633     Base = Ptr->getOperand(0);
10634     Offset = Ptr->getOperand(1);
10635     return true;
10636   }
10637
10638   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10639   return false;
10640 }
10641
10642 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10643                                      bool isSEXTLoad, SDValue &Base,
10644                                      SDValue &Offset, bool &isInc,
10645                                      SelectionDAG &DAG) {
10646   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10647     return false;
10648
10649   Base = Ptr->getOperand(0);
10650   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10651     int RHSC = (int)RHS->getZExtValue();
10652     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10653       assert(Ptr->getOpcode() == ISD::ADD);
10654       isInc = false;
10655       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10656       return true;
10657     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10658       isInc = Ptr->getOpcode() == ISD::ADD;
10659       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10660       return true;
10661     }
10662   }
10663
10664   return false;
10665 }
10666
10667 /// getPreIndexedAddressParts - returns true by value, base pointer and
10668 /// offset pointer and addressing mode by reference if the node's address
10669 /// can be legally represented as pre-indexed load / store address.
10670 bool
10671 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10672                                              SDValue &Offset,
10673                                              ISD::MemIndexedMode &AM,
10674                                              SelectionDAG &DAG) const {
10675   if (Subtarget->isThumb1Only())
10676     return false;
10677
10678   EVT VT;
10679   SDValue Ptr;
10680   bool isSEXTLoad = false;
10681   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10682     Ptr = LD->getBasePtr();
10683     VT  = LD->getMemoryVT();
10684     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10685   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10686     Ptr = ST->getBasePtr();
10687     VT  = ST->getMemoryVT();
10688   } else
10689     return false;
10690
10691   bool isInc;
10692   bool isLegal = false;
10693   if (Subtarget->isThumb2())
10694     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10695                                        Offset, isInc, DAG);
10696   else
10697     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10698                                         Offset, isInc, DAG);
10699   if (!isLegal)
10700     return false;
10701
10702   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10703   return true;
10704 }
10705
10706 /// getPostIndexedAddressParts - returns true by value, base pointer and
10707 /// offset pointer and addressing mode by reference if this node can be
10708 /// combined with a load / store to form a post-indexed load / store.
10709 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10710                                                    SDValue &Base,
10711                                                    SDValue &Offset,
10712                                                    ISD::MemIndexedMode &AM,
10713                                                    SelectionDAG &DAG) const {
10714   if (Subtarget->isThumb1Only())
10715     return false;
10716
10717   EVT VT;
10718   SDValue Ptr;
10719   bool isSEXTLoad = false;
10720   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10721     VT  = LD->getMemoryVT();
10722     Ptr = LD->getBasePtr();
10723     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10724   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10725     VT  = ST->getMemoryVT();
10726     Ptr = ST->getBasePtr();
10727   } else
10728     return false;
10729
10730   bool isInc;
10731   bool isLegal = false;
10732   if (Subtarget->isThumb2())
10733     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10734                                        isInc, DAG);
10735   else
10736     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10737                                         isInc, DAG);
10738   if (!isLegal)
10739     return false;
10740
10741   if (Ptr != Base) {
10742     // Swap base ptr and offset to catch more post-index load / store when
10743     // it's legal. In Thumb2 mode, offset must be an immediate.
10744     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10745         !Subtarget->isThumb2())
10746       std::swap(Base, Offset);
10747
10748     // Post-indexed load / store update the base pointer.
10749     if (Ptr != Base)
10750       return false;
10751   }
10752
10753   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10754   return true;
10755 }
10756
10757 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10758                                                       APInt &KnownZero,
10759                                                       APInt &KnownOne,
10760                                                       const SelectionDAG &DAG,
10761                                                       unsigned Depth) const {
10762   unsigned BitWidth = KnownOne.getBitWidth();
10763   KnownZero = KnownOne = APInt(BitWidth, 0);
10764   switch (Op.getOpcode()) {
10765   default: break;
10766   case ARMISD::ADDC:
10767   case ARMISD::ADDE:
10768   case ARMISD::SUBC:
10769   case ARMISD::SUBE:
10770     // These nodes' second result is a boolean
10771     if (Op.getResNo() == 0)
10772       break;
10773     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10774     break;
10775   case ARMISD::CMOV: {
10776     // Bits are known zero/one if known on the LHS and RHS.
10777     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10778     if (KnownZero == 0 && KnownOne == 0) return;
10779
10780     APInt KnownZeroRHS, KnownOneRHS;
10781     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10782     KnownZero &= KnownZeroRHS;
10783     KnownOne  &= KnownOneRHS;
10784     return;
10785   }
10786   case ISD::INTRINSIC_W_CHAIN: {
10787     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10788     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10789     switch (IntID) {
10790     default: return;
10791     case Intrinsic::arm_ldaex:
10792     case Intrinsic::arm_ldrex: {
10793       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10794       unsigned MemBits = VT.getScalarType().getSizeInBits();
10795       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10796       return;
10797     }
10798     }
10799   }
10800   }
10801 }
10802
10803 //===----------------------------------------------------------------------===//
10804 //                           ARM Inline Assembly Support
10805 //===----------------------------------------------------------------------===//
10806
10807 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10808   // Looking for "rev" which is V6+.
10809   if (!Subtarget->hasV6Ops())
10810     return false;
10811
10812   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10813   std::string AsmStr = IA->getAsmString();
10814   SmallVector<StringRef, 4> AsmPieces;
10815   SplitString(AsmStr, AsmPieces, ";\n");
10816
10817   switch (AsmPieces.size()) {
10818   default: return false;
10819   case 1:
10820     AsmStr = AsmPieces[0];
10821     AsmPieces.clear();
10822     SplitString(AsmStr, AsmPieces, " \t,");
10823
10824     // rev $0, $1
10825     if (AsmPieces.size() == 3 &&
10826         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10827         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10828       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10829       if (Ty && Ty->getBitWidth() == 32)
10830         return IntrinsicLowering::LowerToByteSwap(CI);
10831     }
10832     break;
10833   }
10834
10835   return false;
10836 }
10837
10838 /// getConstraintType - Given a constraint letter, return the type of
10839 /// constraint it is for this target.
10840 ARMTargetLowering::ConstraintType
10841 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10842   if (Constraint.size() == 1) {
10843     switch (Constraint[0]) {
10844     default:  break;
10845     case 'l': return C_RegisterClass;
10846     case 'w': return C_RegisterClass;
10847     case 'h': return C_RegisterClass;
10848     case 'x': return C_RegisterClass;
10849     case 't': return C_RegisterClass;
10850     case 'j': return C_Other; // Constant for movw.
10851       // An address with a single base register. Due to the way we
10852       // currently handle addresses it is the same as an 'r' memory constraint.
10853     case 'Q': return C_Memory;
10854     }
10855   } else if (Constraint.size() == 2) {
10856     switch (Constraint[0]) {
10857     default: break;
10858     // All 'U+' constraints are addresses.
10859     case 'U': return C_Memory;
10860     }
10861   }
10862   return TargetLowering::getConstraintType(Constraint);
10863 }
10864
10865 /// Examine constraint type and operand type and determine a weight value.
10866 /// This object must already have been set up with the operand type
10867 /// and the current alternative constraint selected.
10868 TargetLowering::ConstraintWeight
10869 ARMTargetLowering::getSingleConstraintMatchWeight(
10870     AsmOperandInfo &info, const char *constraint) const {
10871   ConstraintWeight weight = CW_Invalid;
10872   Value *CallOperandVal = info.CallOperandVal;
10873     // If we don't have a value, we can't do a match,
10874     // but allow it at the lowest weight.
10875   if (!CallOperandVal)
10876     return CW_Default;
10877   Type *type = CallOperandVal->getType();
10878   // Look at the constraint type.
10879   switch (*constraint) {
10880   default:
10881     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10882     break;
10883   case 'l':
10884     if (type->isIntegerTy()) {
10885       if (Subtarget->isThumb())
10886         weight = CW_SpecificReg;
10887       else
10888         weight = CW_Register;
10889     }
10890     break;
10891   case 'w':
10892     if (type->isFloatingPointTy())
10893       weight = CW_Register;
10894     break;
10895   }
10896   return weight;
10897 }
10898
10899 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10900 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10901     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10902   if (Constraint.size() == 1) {
10903     // GCC ARM Constraint Letters
10904     switch (Constraint[0]) {
10905     case 'l': // Low regs or general regs.
10906       if (Subtarget->isThumb())
10907         return RCPair(0U, &ARM::tGPRRegClass);
10908       return RCPair(0U, &ARM::GPRRegClass);
10909     case 'h': // High regs or no regs.
10910       if (Subtarget->isThumb())
10911         return RCPair(0U, &ARM::hGPRRegClass);
10912       break;
10913     case 'r':
10914       if (Subtarget->isThumb1Only())
10915         return RCPair(0U, &ARM::tGPRRegClass);
10916       return RCPair(0U, &ARM::GPRRegClass);
10917     case 'w':
10918       if (VT == MVT::Other)
10919         break;
10920       if (VT == MVT::f32)
10921         return RCPair(0U, &ARM::SPRRegClass);
10922       if (VT.getSizeInBits() == 64)
10923         return RCPair(0U, &ARM::DPRRegClass);
10924       if (VT.getSizeInBits() == 128)
10925         return RCPair(0U, &ARM::QPRRegClass);
10926       break;
10927     case 'x':
10928       if (VT == MVT::Other)
10929         break;
10930       if (VT == MVT::f32)
10931         return RCPair(0U, &ARM::SPR_8RegClass);
10932       if (VT.getSizeInBits() == 64)
10933         return RCPair(0U, &ARM::DPR_8RegClass);
10934       if (VT.getSizeInBits() == 128)
10935         return RCPair(0U, &ARM::QPR_8RegClass);
10936       break;
10937     case 't':
10938       if (VT == MVT::f32)
10939         return RCPair(0U, &ARM::SPRRegClass);
10940       break;
10941     }
10942   }
10943   if (StringRef("{cc}").equals_lower(Constraint))
10944     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10945
10946   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10947 }
10948
10949 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10950 /// vector.  If it is invalid, don't add anything to Ops.
10951 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10952                                                      std::string &Constraint,
10953                                                      std::vector<SDValue>&Ops,
10954                                                      SelectionDAG &DAG) const {
10955   SDValue Result;
10956
10957   // Currently only support length 1 constraints.
10958   if (Constraint.length() != 1) return;
10959
10960   char ConstraintLetter = Constraint[0];
10961   switch (ConstraintLetter) {
10962   default: break;
10963   case 'j':
10964   case 'I': case 'J': case 'K': case 'L':
10965   case 'M': case 'N': case 'O':
10966     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10967     if (!C)
10968       return;
10969
10970     int64_t CVal64 = C->getSExtValue();
10971     int CVal = (int) CVal64;
10972     // None of these constraints allow values larger than 32 bits.  Check
10973     // that the value fits in an int.
10974     if (CVal != CVal64)
10975       return;
10976
10977     switch (ConstraintLetter) {
10978       case 'j':
10979         // Constant suitable for movw, must be between 0 and
10980         // 65535.
10981         if (Subtarget->hasV6T2Ops())
10982           if (CVal >= 0 && CVal <= 65535)
10983             break;
10984         return;
10985       case 'I':
10986         if (Subtarget->isThumb1Only()) {
10987           // This must be a constant between 0 and 255, for ADD
10988           // immediates.
10989           if (CVal >= 0 && CVal <= 255)
10990             break;
10991         } else if (Subtarget->isThumb2()) {
10992           // A constant that can be used as an immediate value in a
10993           // data-processing instruction.
10994           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10995             break;
10996         } else {
10997           // A constant that can be used as an immediate value in a
10998           // data-processing instruction.
10999           if (ARM_AM::getSOImmVal(CVal) != -1)
11000             break;
11001         }
11002         return;
11003
11004       case 'J':
11005         if (Subtarget->isThumb()) {  // FIXME thumb2
11006           // This must be a constant between -255 and -1, for negated ADD
11007           // immediates. This can be used in GCC with an "n" modifier that
11008           // prints the negated value, for use with SUB instructions. It is
11009           // not useful otherwise but is implemented for compatibility.
11010           if (CVal >= -255 && CVal <= -1)
11011             break;
11012         } else {
11013           // This must be a constant between -4095 and 4095. It is not clear
11014           // what this constraint is intended for. Implemented for
11015           // compatibility with GCC.
11016           if (CVal >= -4095 && CVal <= 4095)
11017             break;
11018         }
11019         return;
11020
11021       case 'K':
11022         if (Subtarget->isThumb1Only()) {
11023           // A 32-bit value where only one byte has a nonzero value. Exclude
11024           // zero to match GCC. This constraint is used by GCC internally for
11025           // constants that can be loaded with a move/shift combination.
11026           // It is not useful otherwise but is implemented for compatibility.
11027           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11028             break;
11029         } else if (Subtarget->isThumb2()) {
11030           // A constant whose bitwise inverse can be used as an immediate
11031           // value in a data-processing instruction. This can be used in GCC
11032           // with a "B" modifier that prints the inverted value, for use with
11033           // BIC and MVN instructions. It is not useful otherwise but is
11034           // implemented for compatibility.
11035           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11036             break;
11037         } else {
11038           // A constant whose bitwise inverse can be used as an immediate
11039           // value in a data-processing instruction. This can be used in GCC
11040           // with a "B" modifier that prints the inverted value, for use with
11041           // BIC and MVN instructions. It is not useful otherwise but is
11042           // implemented for compatibility.
11043           if (ARM_AM::getSOImmVal(~CVal) != -1)
11044             break;
11045         }
11046         return;
11047
11048       case 'L':
11049         if (Subtarget->isThumb1Only()) {
11050           // This must be a constant between -7 and 7,
11051           // for 3-operand ADD/SUB immediate instructions.
11052           if (CVal >= -7 && CVal < 7)
11053             break;
11054         } else if (Subtarget->isThumb2()) {
11055           // A constant whose negation can be used as an immediate value in a
11056           // data-processing instruction. This can be used in GCC with an "n"
11057           // modifier that prints the negated value, for use with SUB
11058           // instructions. It is not useful otherwise but is implemented for
11059           // compatibility.
11060           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11061             break;
11062         } else {
11063           // A constant whose negation can be used as an immediate value in a
11064           // data-processing instruction. This can be used in GCC with an "n"
11065           // modifier that prints the negated value, for use with SUB
11066           // instructions. It is not useful otherwise but is implemented for
11067           // compatibility.
11068           if (ARM_AM::getSOImmVal(-CVal) != -1)
11069             break;
11070         }
11071         return;
11072
11073       case 'M':
11074         if (Subtarget->isThumb()) { // FIXME thumb2
11075           // This must be a multiple of 4 between 0 and 1020, for
11076           // ADD sp + immediate.
11077           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11078             break;
11079         } else {
11080           // A power of two or a constant between 0 and 32.  This is used in
11081           // GCC for the shift amount on shifted register operands, but it is
11082           // useful in general for any shift amounts.
11083           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11084             break;
11085         }
11086         return;
11087
11088       case 'N':
11089         if (Subtarget->isThumb()) {  // FIXME thumb2
11090           // This must be a constant between 0 and 31, for shift amounts.
11091           if (CVal >= 0 && CVal <= 31)
11092             break;
11093         }
11094         return;
11095
11096       case 'O':
11097         if (Subtarget->isThumb()) {  // FIXME thumb2
11098           // This must be a multiple of 4 between -508 and 508, for
11099           // ADD/SUB sp = sp + immediate.
11100           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11101             break;
11102         }
11103         return;
11104     }
11105     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11106     break;
11107   }
11108
11109   if (Result.getNode()) {
11110     Ops.push_back(Result);
11111     return;
11112   }
11113   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11114 }
11115
11116 static RTLIB::Libcall getDivRemLibcall(
11117     const SDNode *N, MVT::SimpleValueType SVT) {
11118   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11119           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11120          "Unhandled Opcode in getDivRemLibcall");
11121   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11122                   N->getOpcode() == ISD::SREM;
11123   RTLIB::Libcall LC;
11124   switch (SVT) {
11125   default: llvm_unreachable("Unexpected request for libcall!");
11126   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11127   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11128   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11129   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11130   }
11131   return LC;
11132 }
11133
11134 static TargetLowering::ArgListTy getDivRemArgList(
11135     const SDNode *N, LLVMContext *Context) {
11136   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11137           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11138          "Unhandled Opcode in getDivRemArgList");
11139   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11140                   N->getOpcode() == ISD::SREM;
11141   TargetLowering::ArgListTy Args;
11142   TargetLowering::ArgListEntry Entry;
11143   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11144     EVT ArgVT = N->getOperand(i).getValueType();
11145     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11146     Entry.Node = N->getOperand(i);
11147     Entry.Ty = ArgTy;
11148     Entry.isSExt = isSigned;
11149     Entry.isZExt = !isSigned;
11150     Args.push_back(Entry);
11151   }
11152   return Args;
11153 }
11154
11155 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11156   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11157          "Register-based DivRem lowering only");
11158   unsigned Opcode = Op->getOpcode();
11159   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11160          "Invalid opcode for Div/Rem lowering");
11161   bool isSigned = (Opcode == ISD::SDIVREM);
11162   EVT VT = Op->getValueType(0);
11163   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11164
11165   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11166                                        VT.getSimpleVT().SimpleTy);
11167   SDValue InChain = DAG.getEntryNode();
11168
11169   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11170                                                     DAG.getContext());
11171
11172   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11173                                          getPointerTy(DAG.getDataLayout()));
11174
11175   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11176
11177   SDLoc dl(Op);
11178   TargetLowering::CallLoweringInfo CLI(DAG);
11179   CLI.setDebugLoc(dl).setChain(InChain)
11180     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11181     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11182
11183   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11184   return CallInfo.first;
11185 }
11186
11187 // Lowers REM using divmod helpers
11188 // see RTABI section 4.2/4.3
11189 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11190   // Build return types (div and rem)
11191   std::vector<Type*> RetTyParams;
11192   Type *RetTyElement;
11193
11194   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11195   default: llvm_unreachable("Unexpected request for libcall!");
11196   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11197   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11198   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11199   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11200   }
11201
11202   RetTyParams.push_back(RetTyElement);
11203   RetTyParams.push_back(RetTyElement);
11204   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11205   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11206
11207   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11208                                                              SimpleTy);
11209   SDValue InChain = DAG.getEntryNode();
11210   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11211   bool isSigned = N->getOpcode() == ISD::SREM;
11212   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11213                                          getPointerTy(DAG.getDataLayout()));
11214
11215   // Lower call
11216   CallLoweringInfo CLI(DAG);
11217   CLI.setChain(InChain)
11218      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11219      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11220   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11221
11222   // Return second (rem) result operand (first contains div)
11223   SDNode *ResNode = CallResult.first.getNode();
11224   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11225   return ResNode->getOperand(1);
11226 }
11227
11228 SDValue
11229 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11230   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11231   SDLoc DL(Op);
11232
11233   // Get the inputs.
11234   SDValue Chain = Op.getOperand(0);
11235   SDValue Size  = Op.getOperand(1);
11236
11237   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11238                               DAG.getConstant(2, DL, MVT::i32));
11239
11240   SDValue Flag;
11241   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11242   Flag = Chain.getValue(1);
11243
11244   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11245   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11246
11247   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11248   Chain = NewSP.getValue(1);
11249
11250   SDValue Ops[2] = { NewSP, Chain };
11251   return DAG.getMergeValues(Ops, DL);
11252 }
11253
11254 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11255   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11256          "Unexpected type for custom-lowering FP_EXTEND");
11257
11258   RTLIB::Libcall LC;
11259   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11260
11261   SDValue SrcVal = Op.getOperand(0);
11262   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11263                      /*isSigned*/ false, SDLoc(Op)).first;
11264 }
11265
11266 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11267   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11268          Subtarget->isFPOnlySP() &&
11269          "Unexpected type for custom-lowering FP_ROUND");
11270
11271   RTLIB::Libcall LC;
11272   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11273
11274   SDValue SrcVal = Op.getOperand(0);
11275   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11276                      /*isSigned*/ false, SDLoc(Op)).first;
11277 }
11278
11279 bool
11280 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11281   // The ARM target isn't yet aware of offsets.
11282   return false;
11283 }
11284
11285 bool ARM::isBitFieldInvertedMask(unsigned v) {
11286   if (v == 0xffffffff)
11287     return false;
11288
11289   // there can be 1's on either or both "outsides", all the "inside"
11290   // bits must be 0's
11291   return isShiftedMask_32(~v);
11292 }
11293
11294 /// isFPImmLegal - Returns true if the target can instruction select the
11295 /// specified FP immediate natively. If false, the legalizer will
11296 /// materialize the FP immediate as a load from a constant pool.
11297 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11298   if (!Subtarget->hasVFP3())
11299     return false;
11300   if (VT == MVT::f32)
11301     return ARM_AM::getFP32Imm(Imm) != -1;
11302   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11303     return ARM_AM::getFP64Imm(Imm) != -1;
11304   return false;
11305 }
11306
11307 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11308 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11309 /// specified in the intrinsic calls.
11310 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11311                                            const CallInst &I,
11312                                            unsigned Intrinsic) const {
11313   switch (Intrinsic) {
11314   case Intrinsic::arm_neon_vld1:
11315   case Intrinsic::arm_neon_vld2:
11316   case Intrinsic::arm_neon_vld3:
11317   case Intrinsic::arm_neon_vld4:
11318   case Intrinsic::arm_neon_vld2lane:
11319   case Intrinsic::arm_neon_vld3lane:
11320   case Intrinsic::arm_neon_vld4lane: {
11321     Info.opc = ISD::INTRINSIC_W_CHAIN;
11322     // Conservatively set memVT to the entire set of vectors loaded.
11323     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11324     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11325     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11326     Info.ptrVal = I.getArgOperand(0);
11327     Info.offset = 0;
11328     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11329     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11330     Info.vol = false; // volatile loads with NEON intrinsics not supported
11331     Info.readMem = true;
11332     Info.writeMem = false;
11333     return true;
11334   }
11335   case Intrinsic::arm_neon_vst1:
11336   case Intrinsic::arm_neon_vst2:
11337   case Intrinsic::arm_neon_vst3:
11338   case Intrinsic::arm_neon_vst4:
11339   case Intrinsic::arm_neon_vst2lane:
11340   case Intrinsic::arm_neon_vst3lane:
11341   case Intrinsic::arm_neon_vst4lane: {
11342     Info.opc = ISD::INTRINSIC_VOID;
11343     // Conservatively set memVT to the entire set of vectors stored.
11344     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11345     unsigned NumElts = 0;
11346     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11347       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11348       if (!ArgTy->isVectorTy())
11349         break;
11350       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11351     }
11352     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11353     Info.ptrVal = I.getArgOperand(0);
11354     Info.offset = 0;
11355     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11356     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11357     Info.vol = false; // volatile stores with NEON intrinsics not supported
11358     Info.readMem = false;
11359     Info.writeMem = true;
11360     return true;
11361   }
11362   case Intrinsic::arm_ldaex:
11363   case Intrinsic::arm_ldrex: {
11364     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11365     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11366     Info.opc = ISD::INTRINSIC_W_CHAIN;
11367     Info.memVT = MVT::getVT(PtrTy->getElementType());
11368     Info.ptrVal = I.getArgOperand(0);
11369     Info.offset = 0;
11370     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11371     Info.vol = true;
11372     Info.readMem = true;
11373     Info.writeMem = false;
11374     return true;
11375   }
11376   case Intrinsic::arm_stlex:
11377   case Intrinsic::arm_strex: {
11378     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11379     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11380     Info.opc = ISD::INTRINSIC_W_CHAIN;
11381     Info.memVT = MVT::getVT(PtrTy->getElementType());
11382     Info.ptrVal = I.getArgOperand(1);
11383     Info.offset = 0;
11384     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11385     Info.vol = true;
11386     Info.readMem = false;
11387     Info.writeMem = true;
11388     return true;
11389   }
11390   case Intrinsic::arm_stlexd:
11391   case Intrinsic::arm_strexd: {
11392     Info.opc = ISD::INTRINSIC_W_CHAIN;
11393     Info.memVT = MVT::i64;
11394     Info.ptrVal = I.getArgOperand(2);
11395     Info.offset = 0;
11396     Info.align = 8;
11397     Info.vol = true;
11398     Info.readMem = false;
11399     Info.writeMem = true;
11400     return true;
11401   }
11402   case Intrinsic::arm_ldaexd:
11403   case Intrinsic::arm_ldrexd: {
11404     Info.opc = ISD::INTRINSIC_W_CHAIN;
11405     Info.memVT = MVT::i64;
11406     Info.ptrVal = I.getArgOperand(0);
11407     Info.offset = 0;
11408     Info.align = 8;
11409     Info.vol = true;
11410     Info.readMem = true;
11411     Info.writeMem = false;
11412     return true;
11413   }
11414   default:
11415     break;
11416   }
11417
11418   return false;
11419 }
11420
11421 /// \brief Returns true if it is beneficial to convert a load of a constant
11422 /// to just the constant itself.
11423 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11424                                                           Type *Ty) const {
11425   assert(Ty->isIntegerTy());
11426
11427   unsigned Bits = Ty->getPrimitiveSizeInBits();
11428   if (Bits == 0 || Bits > 32)
11429     return false;
11430   return true;
11431 }
11432
11433 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11434
11435 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11436                                         ARM_MB::MemBOpt Domain) const {
11437   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11438
11439   // First, if the target has no DMB, see what fallback we can use.
11440   if (!Subtarget->hasDataBarrier()) {
11441     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11442     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11443     // here.
11444     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11445       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11446       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11447                         Builder.getInt32(0), Builder.getInt32(7),
11448                         Builder.getInt32(10), Builder.getInt32(5)};
11449       return Builder.CreateCall(MCR, args);
11450     } else {
11451       // Instead of using barriers, atomic accesses on these subtargets use
11452       // libcalls.
11453       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11454     }
11455   } else {
11456     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11457     // Only a full system barrier exists in the M-class architectures.
11458     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11459     Constant *CDomain = Builder.getInt32(Domain);
11460     return Builder.CreateCall(DMB, CDomain);
11461   }
11462 }
11463
11464 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11465 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11466                                          AtomicOrdering Ord, bool IsStore,
11467                                          bool IsLoad) const {
11468   if (!getInsertFencesForAtomic())
11469     return nullptr;
11470
11471   switch (Ord) {
11472   case NotAtomic:
11473   case Unordered:
11474     llvm_unreachable("Invalid fence: unordered/non-atomic");
11475   case Monotonic:
11476   case Acquire:
11477     return nullptr; // Nothing to do
11478   case SequentiallyConsistent:
11479     if (!IsStore)
11480       return nullptr; // Nothing to do
11481     /*FALLTHROUGH*/
11482   case Release:
11483   case AcquireRelease:
11484     if (Subtarget->isSwift())
11485       return makeDMB(Builder, ARM_MB::ISHST);
11486     // FIXME: add a comment with a link to documentation justifying this.
11487     else
11488       return makeDMB(Builder, ARM_MB::ISH);
11489   }
11490   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11491 }
11492
11493 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11494                                           AtomicOrdering Ord, bool IsStore,
11495                                           bool IsLoad) const {
11496   if (!getInsertFencesForAtomic())
11497     return nullptr;
11498
11499   switch (Ord) {
11500   case NotAtomic:
11501   case Unordered:
11502     llvm_unreachable("Invalid fence: unordered/not-atomic");
11503   case Monotonic:
11504   case Release:
11505     return nullptr; // Nothing to do
11506   case Acquire:
11507   case AcquireRelease:
11508   case SequentiallyConsistent:
11509     return makeDMB(Builder, ARM_MB::ISH);
11510   }
11511   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11512 }
11513
11514 // Loads and stores less than 64-bits are already atomic; ones above that
11515 // are doomed anyway, so defer to the default libcall and blame the OS when
11516 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11517 // anything for those.
11518 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11519   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11520   return (Size == 64) && !Subtarget->isMClass();
11521 }
11522
11523 // Loads and stores less than 64-bits are already atomic; ones above that
11524 // are doomed anyway, so defer to the default libcall and blame the OS when
11525 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11526 // anything for those.
11527 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11528 // guarantee, see DDI0406C ARM architecture reference manual,
11529 // sections A8.8.72-74 LDRD)
11530 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11531   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11532   return (Size == 64) && !Subtarget->isMClass();
11533 }
11534
11535 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11536 // and up to 64 bits on the non-M profiles
11537 TargetLoweringBase::AtomicRMWExpansionKind
11538 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11539   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11540   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11541              ? AtomicRMWExpansionKind::LLSC
11542              : AtomicRMWExpansionKind::None;
11543 }
11544
11545 // This has so far only been implemented for MachO.
11546 bool ARMTargetLowering::useLoadStackGuardNode() const {
11547   return Subtarget->isTargetMachO();
11548 }
11549
11550 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11551                                                   unsigned &Cost) const {
11552   // If we do not have NEON, vector types are not natively supported.
11553   if (!Subtarget->hasNEON())
11554     return false;
11555
11556   // Floating point values and vector values map to the same register file.
11557   // Therefore, although we could do a store extract of a vector type, this is
11558   // better to leave at float as we have more freedom in the addressing mode for
11559   // those.
11560   if (VectorTy->isFPOrFPVectorTy())
11561     return false;
11562
11563   // If the index is unknown at compile time, this is very expensive to lower
11564   // and it is not possible to combine the store with the extract.
11565   if (!isa<ConstantInt>(Idx))
11566     return false;
11567
11568   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11569   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11570   // We can do a store + vector extract on any vector that fits perfectly in a D
11571   // or Q register.
11572   if (BitWidth == 64 || BitWidth == 128) {
11573     Cost = 0;
11574     return true;
11575   }
11576   return false;
11577 }
11578
11579 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11580                                          AtomicOrdering Ord) const {
11581   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11582   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11583   bool IsAcquire = isAtLeastAcquire(Ord);
11584
11585   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11586   // intrinsic must return {i32, i32} and we have to recombine them into a
11587   // single i64 here.
11588   if (ValTy->getPrimitiveSizeInBits() == 64) {
11589     Intrinsic::ID Int =
11590         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11591     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11592
11593     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11594     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11595
11596     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11597     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11598     if (!Subtarget->isLittle())
11599       std::swap (Lo, Hi);
11600     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11601     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11602     return Builder.CreateOr(
11603         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11604   }
11605
11606   Type *Tys[] = { Addr->getType() };
11607   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11608   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11609
11610   return Builder.CreateTruncOrBitCast(
11611       Builder.CreateCall(Ldrex, Addr),
11612       cast<PointerType>(Addr->getType())->getElementType());
11613 }
11614
11615 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11616                                                Value *Addr,
11617                                                AtomicOrdering Ord) const {
11618   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11619   bool IsRelease = isAtLeastRelease(Ord);
11620
11621   // Since the intrinsics must have legal type, the i64 intrinsics take two
11622   // parameters: "i32, i32". We must marshal Val into the appropriate form
11623   // before the call.
11624   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11625     Intrinsic::ID Int =
11626         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11627     Function *Strex = Intrinsic::getDeclaration(M, Int);
11628     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11629
11630     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11631     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11632     if (!Subtarget->isLittle())
11633       std::swap (Lo, Hi);
11634     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11635     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11636   }
11637
11638   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11639   Type *Tys[] = { Addr->getType() };
11640   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11641
11642   return Builder.CreateCall(
11643       Strex, {Builder.CreateZExtOrBitCast(
11644                   Val, Strex->getFunctionType()->getParamType(0)),
11645               Addr});
11646 }
11647
11648 /// \brief Lower an interleaved load into a vldN intrinsic.
11649 ///
11650 /// E.g. Lower an interleaved load (Factor = 2):
11651 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11652 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11653 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11654 ///
11655 ///      Into:
11656 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11657 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11658 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11659 bool ARMTargetLowering::lowerInterleavedLoad(
11660     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11661     ArrayRef<unsigned> Indices, unsigned Factor) const {
11662   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11663          "Invalid interleave factor");
11664   assert(!Shuffles.empty() && "Empty shufflevector input");
11665   assert(Shuffles.size() == Indices.size() &&
11666          "Unmatched number of shufflevectors and indices");
11667
11668   VectorType *VecTy = Shuffles[0]->getType();
11669   Type *EltTy = VecTy->getVectorElementType();
11670
11671   const DataLayout &DL = LI->getModule()->getDataLayout();
11672   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11673   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11674
11675   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11676   // support i64/f64 element).
11677   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11678     return false;
11679
11680   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11681   // load integer vectors first and then convert to pointer vectors.
11682   if (EltTy->isPointerTy())
11683     VecTy =
11684         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11685
11686   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11687                                             Intrinsic::arm_neon_vld3,
11688                                             Intrinsic::arm_neon_vld4};
11689
11690   Function *VldnFunc =
11691       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11692
11693   IRBuilder<> Builder(LI);
11694   SmallVector<Value *, 2> Ops;
11695
11696   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11697   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11698   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11699
11700   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11701
11702   // Replace uses of each shufflevector with the corresponding vector loaded
11703   // by ldN.
11704   for (unsigned i = 0; i < Shuffles.size(); i++) {
11705     ShuffleVectorInst *SV = Shuffles[i];
11706     unsigned Index = Indices[i];
11707
11708     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11709
11710     // Convert the integer vector to pointer vector if the element is pointer.
11711     if (EltTy->isPointerTy())
11712       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11713
11714     SV->replaceAllUsesWith(SubVec);
11715   }
11716
11717   return true;
11718 }
11719
11720 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11721 ///
11722 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11723 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11724                                    unsigned NumElts) {
11725   SmallVector<Constant *, 16> Mask;
11726   for (unsigned i = 0; i < NumElts; i++)
11727     Mask.push_back(Builder.getInt32(Start + i));
11728
11729   return ConstantVector::get(Mask);
11730 }
11731
11732 /// \brief Lower an interleaved store into a vstN intrinsic.
11733 ///
11734 /// E.g. Lower an interleaved store (Factor = 3):
11735 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11736 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11737 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11738 ///
11739 ///      Into:
11740 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11741 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11742 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11743 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11744 ///
11745 /// Note that the new shufflevectors will be removed and we'll only generate one
11746 /// vst3 instruction in CodeGen.
11747 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11748                                               ShuffleVectorInst *SVI,
11749                                               unsigned Factor) const {
11750   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11751          "Invalid interleave factor");
11752
11753   VectorType *VecTy = SVI->getType();
11754   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11755          "Invalid interleaved store");
11756
11757   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11758   Type *EltTy = VecTy->getVectorElementType();
11759   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11760
11761   const DataLayout &DL = SI->getModule()->getDataLayout();
11762   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11763   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11764
11765   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11766   // doesn't support i64/f64 element).
11767   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11768     return false;
11769
11770   Value *Op0 = SVI->getOperand(0);
11771   Value *Op1 = SVI->getOperand(1);
11772   IRBuilder<> Builder(SI);
11773
11774   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11775   // vectors to integer vectors.
11776   if (EltTy->isPointerTy()) {
11777     Type *IntTy = DL.getIntPtrType(EltTy);
11778
11779     // Convert to the corresponding integer vector.
11780     Type *IntVecTy =
11781         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11782     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11783     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11784
11785     SubVecTy = VectorType::get(IntTy, NumSubElts);
11786   }
11787
11788   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11789                                        Intrinsic::arm_neon_vst3,
11790                                        Intrinsic::arm_neon_vst4};
11791   Function *VstNFunc = Intrinsic::getDeclaration(
11792       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11793
11794   SmallVector<Value *, 6> Ops;
11795
11796   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11797   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11798
11799   // Split the shufflevector operands into sub vectors for the new vstN call.
11800   for (unsigned i = 0; i < Factor; i++)
11801     Ops.push_back(Builder.CreateShuffleVector(
11802         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11803
11804   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11805   Builder.CreateCall(VstNFunc, Ops);
11806   return true;
11807 }
11808
11809 enum HABaseType {
11810   HA_UNKNOWN = 0,
11811   HA_FLOAT,
11812   HA_DOUBLE,
11813   HA_VECT64,
11814   HA_VECT128
11815 };
11816
11817 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11818                                    uint64_t &Members) {
11819   if (auto *ST = dyn_cast<StructType>(Ty)) {
11820     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11821       uint64_t SubMembers = 0;
11822       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11823         return false;
11824       Members += SubMembers;
11825     }
11826   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11827     uint64_t SubMembers = 0;
11828     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11829       return false;
11830     Members += SubMembers * AT->getNumElements();
11831   } else if (Ty->isFloatTy()) {
11832     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11833       return false;
11834     Members = 1;
11835     Base = HA_FLOAT;
11836   } else if (Ty->isDoubleTy()) {
11837     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11838       return false;
11839     Members = 1;
11840     Base = HA_DOUBLE;
11841   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11842     Members = 1;
11843     switch (Base) {
11844     case HA_FLOAT:
11845     case HA_DOUBLE:
11846       return false;
11847     case HA_VECT64:
11848       return VT->getBitWidth() == 64;
11849     case HA_VECT128:
11850       return VT->getBitWidth() == 128;
11851     case HA_UNKNOWN:
11852       switch (VT->getBitWidth()) {
11853       case 64:
11854         Base = HA_VECT64;
11855         return true;
11856       case 128:
11857         Base = HA_VECT128;
11858         return true;
11859       default:
11860         return false;
11861       }
11862     }
11863   }
11864
11865   return (Members > 0 && Members <= 4);
11866 }
11867
11868 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11869 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11870 /// passing according to AAPCS rules.
11871 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11872     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11873   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11874       CallingConv::ARM_AAPCS_VFP)
11875     return false;
11876
11877   HABaseType Base = HA_UNKNOWN;
11878   uint64_t Members = 0;
11879   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11880   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11881
11882   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11883   return IsHA || IsIntArray;
11884 }