da8ecfa1102b4b4d9cfc2823b93b72e9a46c1f6e
[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     // Set the correct calling convention for ARMv7k WatchOS. It's just
247     // AAPCS_VFP for functions as simple as libcalls.
248     if (Subtarget->isTargetWatchOS()) {
249       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
250         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, nullptr);
256   setLibcallName(RTLIB::SRL_I128, nullptr);
257   setLibcallName(RTLIB::SRA_I128, nullptr);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
260       !Subtarget->isTargetWindows()) {
261     static const struct {
262       const RTLIB::Libcall Op;
263       const char * const Name;
264       const CallingConv::ID CC;
265       const ISD::CondCode Cond;
266     } LibraryCalls[] = {
267       // Double-precision floating-point arithmetic helper functions
268       // RTABI chapter 4.1.2, Table 2
269       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273
274       // Double-precision floating-point comparison helper functions
275       // RTABI chapter 4.1.2, Table 3
276       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
278       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
284
285       // Single-precision floating-point arithmetic helper functions
286       // RTABI chapter 4.1.2, Table 4
287       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291
292       // Single-precision floating-point comparison helper functions
293       // RTABI chapter 4.1.2, Table 5
294       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
296       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
301       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
302
303       // Floating-point to integer conversions.
304       // RTABI chapter 4.1.2, Table 6
305       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313
314       // Conversions between floating types.
315       // RTABI chapter 4.1.2, Table 7
316       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319
320       // Integer to floating-point conversions.
321       // RTABI chapter 4.1.2, Table 8
322       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330
331       // Long long helper functions
332       // RTABI chapter 4.2, Table 9
333       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337
338       // Integer division functions
339       // RTABI chapter 4.3.1
340       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348
349       // Memory operations
350       // RTABI chapter 4.3.4
351       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354     };
355
356     for (const auto &LC : LibraryCalls) {
357       setLibcallName(LC.Op, LC.Name);
358       setLibcallCallingConv(LC.Op, LC.CC);
359       if (LC.Cond != ISD::SETCC_INVALID)
360         setCmpLibcallCC(LC.Op, LC.Cond);
361     }
362   }
363
364   if (Subtarget->isTargetWindows()) {
365     static const struct {
366       const RTLIB::Libcall Op;
367       const char * const Name;
368       const CallingConv::ID CC;
369     } LibraryCalls[] = {
370       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
376       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
377       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
378     };
379
380     for (const auto &LC : LibraryCalls) {
381       setLibcallName(LC.Op, LC.Name);
382       setLibcallCallingConv(LC.Op, LC.CC);
383     }
384   }
385
386   // Use divmod compiler-rt calls for iOS 5.0 and later.
387   if (Subtarget->isTargetWatchOS() ||
388       (Subtarget->isTargetIOS() &&
389        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
390     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
391     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
392   }
393
394   // The half <-> float conversion functions are always soft-float, but are
395   // needed for some targets which use a hard-float calling convention by
396   // default.
397   if (Subtarget->isAAPCS_ABI()) {
398     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
399     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
400     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
401   } else {
402     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
403     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
404     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
405   }
406
407   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
408   // a __gnu_ prefix (which is the default).
409   if (Subtarget->isTargetAEABI()) {
410     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
411     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
412     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
413   }
414
415   if (Subtarget->isThumb1Only())
416     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
417   else
418     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
419   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
420       !Subtarget->isThumb1Only()) {
421     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
422     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
423   }
424
425   for (MVT VT : MVT::vector_valuetypes()) {
426     for (MVT InnerVT : MVT::vector_valuetypes()) {
427       setTruncStoreAction(VT, InnerVT, Expand);
428       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
429       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
430       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
431     }
432
433     setOperationAction(ISD::MULHS, VT, Expand);
434     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
435     setOperationAction(ISD::MULHU, VT, Expand);
436     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
437
438     setOperationAction(ISD::BSWAP, VT, Expand);
439   }
440
441   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
442   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
443
444   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
445   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
446
447   if (Subtarget->hasNEON()) {
448     addDRTypeForNEON(MVT::v2f32);
449     addDRTypeForNEON(MVT::v8i8);
450     addDRTypeForNEON(MVT::v4i16);
451     addDRTypeForNEON(MVT::v2i32);
452     addDRTypeForNEON(MVT::v1i64);
453
454     addQRTypeForNEON(MVT::v4f32);
455     addQRTypeForNEON(MVT::v2f64);
456     addQRTypeForNEON(MVT::v16i8);
457     addQRTypeForNEON(MVT::v8i16);
458     addQRTypeForNEON(MVT::v4i32);
459     addQRTypeForNEON(MVT::v2i64);
460
461     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
462     // neither Neon nor VFP support any arithmetic operations on it.
463     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
464     // supported for v4f32.
465     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
467     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
468     // FIXME: Code duplication: FDIV and FREM are expanded always, see
469     // ARMTargetLowering::addTypeForNEON method for details.
470     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
471     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
472     // FIXME: Create unittest.
473     // In another words, find a way when "copysign" appears in DAG with vector
474     // operands.
475     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
476     // FIXME: Code duplication: SETCC has custom operation action, see
477     // ARMTargetLowering::addTypeForNEON method for details.
478     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
479     // FIXME: Create unittest for FNEG and for FABS.
480     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
481     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
482     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
483     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
484     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
485     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
486     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
487     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
488     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
489     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
490     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
491     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
492     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
493     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
494     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
495     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
496     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
497     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
498     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
499
500     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
501     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
502     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
503     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
504     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
505     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
506     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
507     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
508     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
509     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
510     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
511     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
512     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
514     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
515
516     // Mark v2f32 intrinsics.
517     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
518     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
519     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
520     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
521     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
522     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
523     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
524     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
525     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
526     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
527     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
528     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
529     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
531     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
532
533     // Neon does not support some operations on v1i64 and v2i64 types.
534     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
535     // Custom handling for some quad-vector types to detect VMULL.
536     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
537     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
538     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
539     // Custom handling for some vector types to avoid expensive expansions
540     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
541     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
542     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
543     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
544     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
545     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
546     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
547     // a destination type that is wider than the source, and nor does
548     // it have a FP_TO_[SU]INT instruction with a narrower destination than
549     // source.
550     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
551     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
552     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
553     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
554
555     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
556     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
557
558     // NEON does not have single instruction CTPOP for vectors with element
559     // types wider than 8-bits.  However, custom lowering can leverage the
560     // v8i8/v16i8 vcnt instruction.
561     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
562     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
563     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
564     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
565
566     // NEON does not have single instruction CTTZ for vectors.
567     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
568     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
569     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
570     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
571
572     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
573     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
574     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
575     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
576
577     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
578     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
579     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
580     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
581
582     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
583     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
584     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
585     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
586
587     // NEON only has FMA instructions as of VFP4.
588     if (!Subtarget->hasVFP4()) {
589       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
590       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
591     }
592
593     setTargetDAGCombine(ISD::INTRINSIC_VOID);
594     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
595     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
596     setTargetDAGCombine(ISD::SHL);
597     setTargetDAGCombine(ISD::SRL);
598     setTargetDAGCombine(ISD::SRA);
599     setTargetDAGCombine(ISD::SIGN_EXTEND);
600     setTargetDAGCombine(ISD::ZERO_EXTEND);
601     setTargetDAGCombine(ISD::ANY_EXTEND);
602     setTargetDAGCombine(ISD::BUILD_VECTOR);
603     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
604     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
605     setTargetDAGCombine(ISD::STORE);
606     setTargetDAGCombine(ISD::FP_TO_SINT);
607     setTargetDAGCombine(ISD::FP_TO_UINT);
608     setTargetDAGCombine(ISD::FDIV);
609     setTargetDAGCombine(ISD::LOAD);
610
611     // It is legal to extload from v4i8 to v4i16 or v4i32.
612     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
613                    MVT::v2i32}) {
614       for (MVT VT : MVT::integer_vector_valuetypes()) {
615         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
616         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
617         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
618       }
619     }
620   }
621
622   // ARM and Thumb2 support UMLAL/SMLAL.
623   if (!Subtarget->isThumb1Only())
624     setTargetDAGCombine(ISD::ADDC);
625
626   if (Subtarget->isFPOnlySP()) {
627     // When targeting a floating-point unit with only single-precision
628     // operations, f64 is legal for the few double-precision instructions which
629     // are present However, no double-precision operations other than moves,
630     // loads and stores are provided by the hardware.
631     setOperationAction(ISD::FADD,       MVT::f64, Expand);
632     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
633     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
634     setOperationAction(ISD::FMA,        MVT::f64, Expand);
635     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
636     setOperationAction(ISD::FREM,       MVT::f64, Expand);
637     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
638     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
639     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
640     setOperationAction(ISD::FABS,       MVT::f64, Expand);
641     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
642     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
643     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
644     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
645     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
646     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
647     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
648     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
649     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
650     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
651     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
652     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
653     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
654     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
655     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
656     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
657     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
658     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
659     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
661     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
662     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
663     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
664   }
665
666   computeRegisterProperties(Subtarget->getRegisterInfo());
667
668   // ARM does not have floating-point extending loads.
669   for (MVT VT : MVT::fp_valuetypes()) {
670     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
671     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
672   }
673
674   // ... or truncating stores
675   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
676   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
677   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
678
679   // ARM does not have i1 sign extending load.
680   for (MVT VT : MVT::integer_valuetypes())
681     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
682
683   // ARM supports all 4 flavors of integer indexed load / store.
684   if (!Subtarget->isThumb1Only()) {
685     for (unsigned im = (unsigned)ISD::PRE_INC;
686          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
687       setIndexedLoadAction(im,  MVT::i1,  Legal);
688       setIndexedLoadAction(im,  MVT::i8,  Legal);
689       setIndexedLoadAction(im,  MVT::i16, Legal);
690       setIndexedLoadAction(im,  MVT::i32, Legal);
691       setIndexedStoreAction(im, MVT::i1,  Legal);
692       setIndexedStoreAction(im, MVT::i8,  Legal);
693       setIndexedStoreAction(im, MVT::i16, Legal);
694       setIndexedStoreAction(im, MVT::i32, Legal);
695     }
696   }
697
698   setOperationAction(ISD::SADDO, MVT::i32, Custom);
699   setOperationAction(ISD::UADDO, MVT::i32, Custom);
700   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
701   setOperationAction(ISD::USUBO, MVT::i32, Custom);
702
703   // i64 operation support.
704   setOperationAction(ISD::MUL,     MVT::i64, Expand);
705   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
706   if (Subtarget->isThumb1Only()) {
707     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
708     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
709   }
710   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
711       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
712     setOperationAction(ISD::MULHS, MVT::i32, Expand);
713
714   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
715   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
716   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
717   setOperationAction(ISD::SRL,       MVT::i64, Custom);
718   setOperationAction(ISD::SRA,       MVT::i64, Custom);
719
720   if (!Subtarget->isThumb1Only()) {
721     // FIXME: We should do this for Thumb1 as well.
722     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
723     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
724     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
725     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
726   }
727
728   // ARM does not have ROTL.
729   setOperationAction(ISD::ROTL, MVT::i32, Expand);
730   for (MVT VT : MVT::vector_valuetypes()) {
731     setOperationAction(ISD::ROTL, VT, Expand);
732     setOperationAction(ISD::ROTR, VT, Expand);
733   }
734   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
735   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
736   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
737     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
738
739   // These just redirect to CTTZ and CTLZ on ARM.
740   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
741   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
742
743   // @llvm.readcyclecounter requires the Performance Monitors extension.
744   // Default to the 0 expansion on unsupported platforms.
745   // FIXME: Technically there are older ARM CPUs that have
746   // implementation-specific ways of obtaining this information.
747   if (Subtarget->hasPerfMon())
748     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
749
750   // Only ARMv6 has BSWAP.
751   if (!Subtarget->hasV6Ops())
752     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
753
754   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
755       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
756     // These are expanded into libcalls if the cpu doesn't have HW divider.
757     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
758     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
759   }
760
761   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
762     setOperationAction(ISD::SDIV, MVT::i32, Custom);
763     setOperationAction(ISD::UDIV, MVT::i32, Custom);
764
765     setOperationAction(ISD::SDIV, MVT::i64, Custom);
766     setOperationAction(ISD::UDIV, MVT::i64, Custom);
767   }
768
769   setOperationAction(ISD::SREM,  MVT::i32, Expand);
770   setOperationAction(ISD::UREM,  MVT::i32, Expand);
771   // Register based DivRem for AEABI (RTABI 4.2)
772   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
773     setOperationAction(ISD::SREM, MVT::i64, Custom);
774     setOperationAction(ISD::UREM, MVT::i64, Custom);
775
776     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
777     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
778     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
779     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
780     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
781     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
782     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
783     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
784
785     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
786     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
787     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
788     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
789     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
790     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
791     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
792     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
793
794     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
795     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
796   } else {
797     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
798     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
799   }
800
801   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
802   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
803   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
804   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
805
806   setOperationAction(ISD::TRAP, MVT::Other, Legal);
807
808   // Use the default implementation.
809   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
810   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
811   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
812   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
813   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
814   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
815
816   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
817     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
818   else
819     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
820
821   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
822   // the default expansion. If we are targeting a single threaded system,
823   // then set them all for expand so we can lower them later into their
824   // non-atomic form.
825   if (TM.Options.ThreadModel == ThreadModel::Single)
826     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
827   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
828     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
829     // to ldrex/strex loops already.
830     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
831
832     // On v8, we have particularly efficient implementations of atomic fences
833     // if they can be combined with nearby atomic loads and stores.
834     if (!Subtarget->hasV8Ops()) {
835       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
836       setInsertFencesForAtomic(true);
837     }
838   } else {
839     // If there's anything we can use as a barrier, go through custom lowering
840     // for ATOMIC_FENCE.
841     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
842                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
843
844     // Set them all for expansion, which will force libcalls.
845     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
846     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
847     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
848     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
849     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
850     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
851     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
852     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
853     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
854     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
855     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
856     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
857     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
858     // Unordered/Monotonic case.
859     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
860     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
861   }
862
863   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
864
865   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
866   if (!Subtarget->hasV6Ops()) {
867     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
869   }
870   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
871
872   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
873       !Subtarget->isThumb1Only()) {
874     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
875     // iff target supports vfp2.
876     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
877     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
878   }
879
880   // We want to custom lower some of our intrinsics.
881   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
882   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
883   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
884   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
885   if (Subtarget->useSjLjEH())
886     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
887
888   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
889   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
890   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
891   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
892   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
893   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
894   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
895   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
896   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
897
898   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
899   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
900   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
901   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
902   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
903
904   // We don't support sin/cos/fmod/copysign/pow
905   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
906   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
907   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
908   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
909   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
910   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
911   setOperationAction(ISD::FREM,      MVT::f64, Expand);
912   setOperationAction(ISD::FREM,      MVT::f32, Expand);
913   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
914       !Subtarget->isThumb1Only()) {
915     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
916     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
917   }
918   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
919   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
920
921   if (!Subtarget->hasVFP4()) {
922     setOperationAction(ISD::FMA, MVT::f64, Expand);
923     setOperationAction(ISD::FMA, MVT::f32, Expand);
924   }
925
926   // Various VFP goodness
927   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
928     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
929     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
930       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
931       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
932     }
933
934     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
935     if (!Subtarget->hasFP16()) {
936       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
937       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
938     }
939   }
940
941   // Combine sin / cos into one node or libcall if possible.
942   if (Subtarget->hasSinCos()) {
943     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
944     setLibcallName(RTLIB::SINCOS_F64, "sincos");
945     if (Subtarget->isTargetWatchOS()) {
946       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
947       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
948     }
949     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
950       // For iOS, we don't want to the normal expansion of a libcall to
951       // sincos. We want to issue a libcall to __sincos_stret.
952       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
953       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
954     }
955   }
956
957   // FP-ARMv8 implements a lot of rounding-like FP operations.
958   if (Subtarget->hasFPARMv8()) {
959     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
960     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
961     setOperationAction(ISD::FROUND, MVT::f32, Legal);
962     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
963     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
964     setOperationAction(ISD::FRINT, MVT::f32, Legal);
965     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
966     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
967     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
968     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
969     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
970     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
971
972     if (!Subtarget->isFPOnlySP()) {
973       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
974       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
975       setOperationAction(ISD::FROUND, MVT::f64, Legal);
976       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
977       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
978       setOperationAction(ISD::FRINT, MVT::f64, Legal);
979       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
980       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
981     }
982   }
983
984   if (Subtarget->hasNEON()) {
985     // vmin and vmax aren't available in a scalar form, so we use
986     // a NEON instruction with an undef lane instead.
987     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
988     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
989     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
990     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
991     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
992     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
993   }
994
995   // We have target-specific dag combine patterns for the following nodes:
996   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
997   setTargetDAGCombine(ISD::ADD);
998   setTargetDAGCombine(ISD::SUB);
999   setTargetDAGCombine(ISD::MUL);
1000   setTargetDAGCombine(ISD::AND);
1001   setTargetDAGCombine(ISD::OR);
1002   setTargetDAGCombine(ISD::XOR);
1003
1004   if (Subtarget->hasV6Ops())
1005     setTargetDAGCombine(ISD::SRL);
1006
1007   setStackPointerRegisterToSaveRestore(ARM::SP);
1008
1009   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1010       !Subtarget->hasVFP2())
1011     setSchedulingPreference(Sched::RegPressure);
1012   else
1013     setSchedulingPreference(Sched::Hybrid);
1014
1015   //// temporary - rewrite interface to use type
1016   MaxStoresPerMemset = 8;
1017   MaxStoresPerMemsetOptSize = 4;
1018   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1019   MaxStoresPerMemcpyOptSize = 2;
1020   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1021   MaxStoresPerMemmoveOptSize = 2;
1022
1023   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1024   // are at least 4 bytes aligned.
1025   setMinStackArgumentAlignment(4);
1026
1027   // Prefer likely predicted branches to selects on out-of-order cores.
1028   PredictableSelectIsExpensive = Subtarget->isLikeA9();
1029
1030   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1031 }
1032
1033 bool ARMTargetLowering::useSoftFloat() const {
1034   return Subtarget->useSoftFloat();
1035 }
1036
1037 // FIXME: It might make sense to define the representative register class as the
1038 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1039 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1040 // SPR's representative would be DPR_VFP2. This should work well if register
1041 // pressure tracking were modified such that a register use would increment the
1042 // pressure of the register class's representative and all of it's super
1043 // classes' representatives transitively. We have not implemented this because
1044 // of the difficulty prior to coalescing of modeling operand register classes
1045 // due to the common occurrence of cross class copies and subregister insertions
1046 // and extractions.
1047 std::pair<const TargetRegisterClass *, uint8_t>
1048 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1049                                            MVT VT) const {
1050   const TargetRegisterClass *RRC = nullptr;
1051   uint8_t Cost = 1;
1052   switch (VT.SimpleTy) {
1053   default:
1054     return TargetLowering::findRepresentativeClass(TRI, VT);
1055   // Use DPR as representative register class for all floating point
1056   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1057   // the cost is 1 for both f32 and f64.
1058   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1059   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1060     RRC = &ARM::DPRRegClass;
1061     // When NEON is used for SP, only half of the register file is available
1062     // because operations that define both SP and DP results will be constrained
1063     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1064     // coalescing by double-counting the SP regs. See the FIXME above.
1065     if (Subtarget->useNEONForSinglePrecisionFP())
1066       Cost = 2;
1067     break;
1068   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1069   case MVT::v4f32: case MVT::v2f64:
1070     RRC = &ARM::DPRRegClass;
1071     Cost = 2;
1072     break;
1073   case MVT::v4i64:
1074     RRC = &ARM::DPRRegClass;
1075     Cost = 4;
1076     break;
1077   case MVT::v8i64:
1078     RRC = &ARM::DPRRegClass;
1079     Cost = 8;
1080     break;
1081   }
1082   return std::make_pair(RRC, Cost);
1083 }
1084
1085 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1086   switch ((ARMISD::NodeType)Opcode) {
1087   case ARMISD::FIRST_NUMBER:  break;
1088   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1089   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1090   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1091   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1092   case ARMISD::CALL:          return "ARMISD::CALL";
1093   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1094   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1095   case ARMISD::tCALL:         return "ARMISD::tCALL";
1096   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1097   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1098   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1099   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1100   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1101   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1102   case ARMISD::CMP:           return "ARMISD::CMP";
1103   case ARMISD::CMN:           return "ARMISD::CMN";
1104   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1105   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1106   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1107   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1108   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1109
1110   case ARMISD::CMOV:          return "ARMISD::CMOV";
1111
1112   case ARMISD::RBIT:          return "ARMISD::RBIT";
1113
1114   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1115   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1116   case ARMISD::RRX:           return "ARMISD::RRX";
1117
1118   case ARMISD::ADDC:          return "ARMISD::ADDC";
1119   case ARMISD::ADDE:          return "ARMISD::ADDE";
1120   case ARMISD::SUBC:          return "ARMISD::SUBC";
1121   case ARMISD::SUBE:          return "ARMISD::SUBE";
1122
1123   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1124   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1125
1126   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1127   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1128   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1129
1130   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1131
1132   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1133
1134   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1135
1136   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1137
1138   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1139
1140   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1141   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1142
1143   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1144   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1145   case ARMISD::VCGE:          return "ARMISD::VCGE";
1146   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1147   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1148   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1149   case ARMISD::VCGT:          return "ARMISD::VCGT";
1150   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1151   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1152   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1153   case ARMISD::VTST:          return "ARMISD::VTST";
1154
1155   case ARMISD::VSHL:          return "ARMISD::VSHL";
1156   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1157   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1158   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1159   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1160   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1161   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1162   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1163   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1164   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1165   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1166   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1167   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1168   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1169   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1170   case ARMISD::VSLI:          return "ARMISD::VSLI";
1171   case ARMISD::VSRI:          return "ARMISD::VSRI";
1172   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1173   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1174   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1175   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1176   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1177   case ARMISD::VDUP:          return "ARMISD::VDUP";
1178   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1179   case ARMISD::VEXT:          return "ARMISD::VEXT";
1180   case ARMISD::VREV64:        return "ARMISD::VREV64";
1181   case ARMISD::VREV32:        return "ARMISD::VREV32";
1182   case ARMISD::VREV16:        return "ARMISD::VREV16";
1183   case ARMISD::VZIP:          return "ARMISD::VZIP";
1184   case ARMISD::VUZP:          return "ARMISD::VUZP";
1185   case ARMISD::VTRN:          return "ARMISD::VTRN";
1186   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1187   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1188   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1189   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1190   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1191   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1192   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1193   case ARMISD::BFI:           return "ARMISD::BFI";
1194   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1195   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1196   case ARMISD::VBSL:          return "ARMISD::VBSL";
1197   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1198   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1199   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1200   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1201   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1202   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1203   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1204   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1205   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1206   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1207   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1208   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1209   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1210   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1211   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1212   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1213   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1214   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1215   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1216   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1217   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1218   }
1219   return nullptr;
1220 }
1221
1222 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1223                                           EVT VT) const {
1224   if (!VT.isVector())
1225     return getPointerTy(DL);
1226   return VT.changeVectorElementTypeToInteger();
1227 }
1228
1229 /// getRegClassFor - Return the register class that should be used for the
1230 /// specified value type.
1231 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1232   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1233   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1234   // load / store 4 to 8 consecutive D registers.
1235   if (Subtarget->hasNEON()) {
1236     if (VT == MVT::v4i64)
1237       return &ARM::QQPRRegClass;
1238     if (VT == MVT::v8i64)
1239       return &ARM::QQQQPRRegClass;
1240   }
1241   return TargetLowering::getRegClassFor(VT);
1242 }
1243
1244 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1245 // source/dest is aligned and the copy size is large enough. We therefore want
1246 // to align such objects passed to memory intrinsics.
1247 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1248                                                unsigned &PrefAlign) const {
1249   if (!isa<MemIntrinsic>(CI))
1250     return false;
1251   MinSize = 8;
1252   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1253   // cycle faster than 4-byte aligned LDM.
1254   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1255   return true;
1256 }
1257
1258 // Create a fast isel object.
1259 FastISel *
1260 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1261                                   const TargetLibraryInfo *libInfo) const {
1262   return ARM::createFastISel(funcInfo, libInfo);
1263 }
1264
1265 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1266   unsigned NumVals = N->getNumValues();
1267   if (!NumVals)
1268     return Sched::RegPressure;
1269
1270   for (unsigned i = 0; i != NumVals; ++i) {
1271     EVT VT = N->getValueType(i);
1272     if (VT == MVT::Glue || VT == MVT::Other)
1273       continue;
1274     if (VT.isFloatingPoint() || VT.isVector())
1275       return Sched::ILP;
1276   }
1277
1278   if (!N->isMachineOpcode())
1279     return Sched::RegPressure;
1280
1281   // Load are scheduled for latency even if there instruction itinerary
1282   // is not available.
1283   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1284   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1285
1286   if (MCID.getNumDefs() == 0)
1287     return Sched::RegPressure;
1288   if (!Itins->isEmpty() &&
1289       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1290     return Sched::ILP;
1291
1292   return Sched::RegPressure;
1293 }
1294
1295 //===----------------------------------------------------------------------===//
1296 // Lowering Code
1297 //===----------------------------------------------------------------------===//
1298
1299 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1300 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1301   switch (CC) {
1302   default: llvm_unreachable("Unknown condition code!");
1303   case ISD::SETNE:  return ARMCC::NE;
1304   case ISD::SETEQ:  return ARMCC::EQ;
1305   case ISD::SETGT:  return ARMCC::GT;
1306   case ISD::SETGE:  return ARMCC::GE;
1307   case ISD::SETLT:  return ARMCC::LT;
1308   case ISD::SETLE:  return ARMCC::LE;
1309   case ISD::SETUGT: return ARMCC::HI;
1310   case ISD::SETUGE: return ARMCC::HS;
1311   case ISD::SETULT: return ARMCC::LO;
1312   case ISD::SETULE: return ARMCC::LS;
1313   }
1314 }
1315
1316 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1317 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1318                         ARMCC::CondCodes &CondCode2) {
1319   CondCode2 = ARMCC::AL;
1320   switch (CC) {
1321   default: llvm_unreachable("Unknown FP condition!");
1322   case ISD::SETEQ:
1323   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1324   case ISD::SETGT:
1325   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1326   case ISD::SETGE:
1327   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1328   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1329   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1330   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1331   case ISD::SETO:   CondCode = ARMCC::VC; break;
1332   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1333   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1334   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1335   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1336   case ISD::SETLT:
1337   case ISD::SETULT: CondCode = ARMCC::LT; break;
1338   case ISD::SETLE:
1339   case ISD::SETULE: CondCode = ARMCC::LE; break;
1340   case ISD::SETNE:
1341   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1342   }
1343 }
1344
1345 //===----------------------------------------------------------------------===//
1346 //                      Calling Convention Implementation
1347 //===----------------------------------------------------------------------===//
1348
1349 #include "ARMGenCallingConv.inc"
1350
1351 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1352 /// account presence of floating point hardware and calling convention
1353 /// limitations, such as support for variadic functions.
1354 CallingConv::ID
1355 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1356                                            bool isVarArg) const {
1357   switch (CC) {
1358   default:
1359     llvm_unreachable("Unsupported calling convention");
1360   case CallingConv::ARM_AAPCS:
1361   case CallingConv::ARM_APCS:
1362   case CallingConv::GHC:
1363     return CC;
1364   case CallingConv::ARM_AAPCS_VFP:
1365     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1366   case CallingConv::C:
1367     if (!Subtarget->isAAPCS_ABI())
1368       return CallingConv::ARM_APCS;
1369     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1370              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1371              !isVarArg)
1372       return CallingConv::ARM_AAPCS_VFP;
1373     else
1374       return CallingConv::ARM_AAPCS;
1375   case CallingConv::Fast:
1376     if (!Subtarget->isAAPCS_ABI()) {
1377       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1378         return CallingConv::Fast;
1379       return CallingConv::ARM_APCS;
1380     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1381       return CallingConv::ARM_AAPCS_VFP;
1382     else
1383       return CallingConv::ARM_AAPCS;
1384   }
1385 }
1386
1387 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1388 /// CallingConvention.
1389 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1390                                                  bool Return,
1391                                                  bool isVarArg) const {
1392   switch (getEffectiveCallingConv(CC, isVarArg)) {
1393   default:
1394     llvm_unreachable("Unsupported calling convention");
1395   case CallingConv::ARM_APCS:
1396     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1397   case CallingConv::ARM_AAPCS:
1398     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1399   case CallingConv::ARM_AAPCS_VFP:
1400     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1401   case CallingConv::Fast:
1402     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1403   case CallingConv::GHC:
1404     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1405   }
1406 }
1407
1408 /// LowerCallResult - Lower the result values of a call into the
1409 /// appropriate copies out of appropriate physical registers.
1410 SDValue
1411 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1412                                    CallingConv::ID CallConv, bool isVarArg,
1413                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1414                                    SDLoc dl, SelectionDAG &DAG,
1415                                    SmallVectorImpl<SDValue> &InVals,
1416                                    bool isThisReturn, SDValue ThisVal) const {
1417
1418   // Assign locations to each value returned by this call.
1419   SmallVector<CCValAssign, 16> RVLocs;
1420   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1421                     *DAG.getContext(), Call);
1422   CCInfo.AnalyzeCallResult(Ins,
1423                            CCAssignFnForNode(CallConv, /* Return*/ true,
1424                                              isVarArg));
1425
1426   // Copy all of the result registers out of their specified physreg.
1427   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1428     CCValAssign VA = RVLocs[i];
1429
1430     // Pass 'this' value directly from the argument to return value, to avoid
1431     // reg unit interference
1432     if (i == 0 && isThisReturn) {
1433       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1434              "unexpected return calling convention register assignment");
1435       InVals.push_back(ThisVal);
1436       continue;
1437     }
1438
1439     SDValue Val;
1440     if (VA.needsCustom()) {
1441       // Handle f64 or half of a v2f64.
1442       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1443                                       InFlag);
1444       Chain = Lo.getValue(1);
1445       InFlag = Lo.getValue(2);
1446       VA = RVLocs[++i]; // skip ahead to next loc
1447       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1448                                       InFlag);
1449       Chain = Hi.getValue(1);
1450       InFlag = Hi.getValue(2);
1451       if (!Subtarget->isLittle())
1452         std::swap (Lo, Hi);
1453       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1454
1455       if (VA.getLocVT() == MVT::v2f64) {
1456         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1457         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1458                           DAG.getConstant(0, dl, MVT::i32));
1459
1460         VA = RVLocs[++i]; // skip ahead to next loc
1461         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1462         Chain = Lo.getValue(1);
1463         InFlag = Lo.getValue(2);
1464         VA = RVLocs[++i]; // skip ahead to next loc
1465         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1466         Chain = Hi.getValue(1);
1467         InFlag = Hi.getValue(2);
1468         if (!Subtarget->isLittle())
1469           std::swap (Lo, Hi);
1470         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1471         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1472                           DAG.getConstant(1, dl, MVT::i32));
1473       }
1474     } else {
1475       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1476                                InFlag);
1477       Chain = Val.getValue(1);
1478       InFlag = Val.getValue(2);
1479     }
1480
1481     switch (VA.getLocInfo()) {
1482     default: llvm_unreachable("Unknown loc info!");
1483     case CCValAssign::Full: break;
1484     case CCValAssign::BCvt:
1485       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1486       break;
1487     }
1488
1489     InVals.push_back(Val);
1490   }
1491
1492   return Chain;
1493 }
1494
1495 /// LowerMemOpCallTo - Store the argument to the stack.
1496 SDValue
1497 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1498                                     SDValue StackPtr, SDValue Arg,
1499                                     SDLoc dl, SelectionDAG &DAG,
1500                                     const CCValAssign &VA,
1501                                     ISD::ArgFlagsTy Flags) const {
1502   unsigned LocMemOffset = VA.getLocMemOffset();
1503   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1504   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1505                        StackPtr, PtrOff);
1506   return DAG.getStore(
1507       Chain, dl, Arg, PtrOff,
1508       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
1509       false, false, 0);
1510 }
1511
1512 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1513                                          SDValue Chain, SDValue &Arg,
1514                                          RegsToPassVector &RegsToPass,
1515                                          CCValAssign &VA, CCValAssign &NextVA,
1516                                          SDValue &StackPtr,
1517                                          SmallVectorImpl<SDValue> &MemOpChains,
1518                                          ISD::ArgFlagsTy Flags) const {
1519
1520   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1521                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1522   unsigned id = Subtarget->isLittle() ? 0 : 1;
1523   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1524
1525   if (NextVA.isRegLoc())
1526     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1527   else {
1528     assert(NextVA.isMemLoc());
1529     if (!StackPtr.getNode())
1530       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1531                                     getPointerTy(DAG.getDataLayout()));
1532
1533     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1534                                            dl, DAG, NextVA,
1535                                            Flags));
1536   }
1537 }
1538
1539 /// LowerCall - Lowering a call into a callseq_start <-
1540 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1541 /// nodes.
1542 SDValue
1543 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1544                              SmallVectorImpl<SDValue> &InVals) const {
1545   SelectionDAG &DAG                     = CLI.DAG;
1546   SDLoc &dl                             = CLI.DL;
1547   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1548   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1549   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1550   SDValue Chain                         = CLI.Chain;
1551   SDValue Callee                        = CLI.Callee;
1552   bool &isTailCall                      = CLI.IsTailCall;
1553   CallingConv::ID CallConv              = CLI.CallConv;
1554   bool doesNotRet                       = CLI.DoesNotReturn;
1555   bool isVarArg                         = CLI.IsVarArg;
1556
1557   MachineFunction &MF = DAG.getMachineFunction();
1558   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1559   bool isThisReturn   = false;
1560   bool isSibCall      = false;
1561   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1562
1563   // Disable tail calls if they're not supported.
1564   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1565     isTailCall = false;
1566
1567   if (isTailCall) {
1568     // Check if it's really possible to do a tail call.
1569     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1570                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1571                                                    Outs, OutVals, Ins, DAG);
1572     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1573       report_fatal_error("failed to perform tail call elimination on a call "
1574                          "site marked musttail");
1575     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1576     // detected sibcalls.
1577     if (isTailCall) {
1578       ++NumTailCalls;
1579       isSibCall = true;
1580     }
1581   }
1582
1583   // Analyze operands of the call, assigning locations to each operand.
1584   SmallVector<CCValAssign, 16> ArgLocs;
1585   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1586                     *DAG.getContext(), Call);
1587   CCInfo.AnalyzeCallOperands(Outs,
1588                              CCAssignFnForNode(CallConv, /* Return*/ false,
1589                                                isVarArg));
1590
1591   // Get a count of how many bytes are to be pushed on the stack.
1592   unsigned NumBytes = CCInfo.getNextStackOffset();
1593
1594   // For tail calls, memory operands are available in our caller's stack.
1595   if (isSibCall)
1596     NumBytes = 0;
1597
1598   // Adjust the stack pointer for the new arguments...
1599   // These operations are automatically eliminated by the prolog/epilog pass
1600   if (!isSibCall)
1601     Chain = DAG.getCALLSEQ_START(Chain,
1602                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1603
1604   SDValue StackPtr =
1605       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1606
1607   RegsToPassVector RegsToPass;
1608   SmallVector<SDValue, 8> MemOpChains;
1609
1610   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1611   // of tail call optimization, arguments are handled later.
1612   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1613        i != e;
1614        ++i, ++realArgIdx) {
1615     CCValAssign &VA = ArgLocs[i];
1616     SDValue Arg = OutVals[realArgIdx];
1617     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1618     bool isByVal = Flags.isByVal();
1619
1620     // Promote the value if needed.
1621     switch (VA.getLocInfo()) {
1622     default: llvm_unreachable("Unknown loc info!");
1623     case CCValAssign::Full: break;
1624     case CCValAssign::SExt:
1625       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1626       break;
1627     case CCValAssign::ZExt:
1628       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1629       break;
1630     case CCValAssign::AExt:
1631       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1632       break;
1633     case CCValAssign::BCvt:
1634       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1635       break;
1636     }
1637
1638     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1639     if (VA.needsCustom()) {
1640       if (VA.getLocVT() == MVT::v2f64) {
1641         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1642                                   DAG.getConstant(0, dl, MVT::i32));
1643         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1644                                   DAG.getConstant(1, dl, MVT::i32));
1645
1646         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1647                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1648
1649         VA = ArgLocs[++i]; // skip ahead to next loc
1650         if (VA.isRegLoc()) {
1651           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1652                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1653         } else {
1654           assert(VA.isMemLoc());
1655
1656           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1657                                                  dl, DAG, VA, Flags));
1658         }
1659       } else {
1660         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1661                          StackPtr, MemOpChains, Flags);
1662       }
1663     } else if (VA.isRegLoc()) {
1664       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1665         assert(VA.getLocVT() == MVT::i32 &&
1666                "unexpected calling convention register assignment");
1667         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1668                "unexpected use of 'returned'");
1669         isThisReturn = true;
1670       }
1671       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1672     } else if (isByVal) {
1673       assert(VA.isMemLoc());
1674       unsigned offset = 0;
1675
1676       // True if this byval aggregate will be split between registers
1677       // and memory.
1678       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1679       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1680
1681       if (CurByValIdx < ByValArgsCount) {
1682
1683         unsigned RegBegin, RegEnd;
1684         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1685
1686         EVT PtrVT =
1687             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1688         unsigned int i, j;
1689         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1690           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1691           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1692           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1693                                      MachinePointerInfo(),
1694                                      false, false, false,
1695                                      DAG.InferPtrAlignment(AddArg));
1696           MemOpChains.push_back(Load.getValue(1));
1697           RegsToPass.push_back(std::make_pair(j, Load));
1698         }
1699
1700         // If parameter size outsides register area, "offset" value
1701         // helps us to calculate stack slot for remained part properly.
1702         offset = RegEnd - RegBegin;
1703
1704         CCInfo.nextInRegsParam();
1705       }
1706
1707       if (Flags.getByValSize() > 4*offset) {
1708         auto PtrVT = getPointerTy(DAG.getDataLayout());
1709         unsigned LocMemOffset = VA.getLocMemOffset();
1710         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1711         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1712         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1713         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1714         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1715                                            MVT::i32);
1716         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1717                                             MVT::i32);
1718
1719         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1720         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1721         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1722                                           Ops));
1723       }
1724     } else if (!isSibCall) {
1725       assert(VA.isMemLoc());
1726
1727       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1728                                              dl, DAG, VA, Flags));
1729     }
1730   }
1731
1732   if (!MemOpChains.empty())
1733     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1734
1735   // Build a sequence of copy-to-reg nodes chained together with token chain
1736   // and flag operands which copy the outgoing args into the appropriate regs.
1737   SDValue InFlag;
1738   // Tail call byval lowering might overwrite argument registers so in case of
1739   // tail call optimization the copies to registers are lowered later.
1740   if (!isTailCall)
1741     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1742       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1743                                RegsToPass[i].second, InFlag);
1744       InFlag = Chain.getValue(1);
1745     }
1746
1747   // For tail calls lower the arguments to the 'real' stack slot.
1748   if (isTailCall) {
1749     // Force all the incoming stack arguments to be loaded from the stack
1750     // before any new outgoing arguments are stored to the stack, because the
1751     // outgoing stack slots may alias the incoming argument stack slots, and
1752     // the alias isn't otherwise explicit. This is slightly more conservative
1753     // than necessary, because it means that each store effectively depends
1754     // on every argument instead of just those arguments it would clobber.
1755
1756     // Do not flag preceding copytoreg stuff together with the following stuff.
1757     InFlag = SDValue();
1758     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1759       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1760                                RegsToPass[i].second, InFlag);
1761       InFlag = Chain.getValue(1);
1762     }
1763     InFlag = SDValue();
1764   }
1765
1766   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1767   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1768   // node so that legalize doesn't hack it.
1769   bool isDirect = false;
1770   bool isARMFunc = false;
1771   bool isLocalARMFunc = false;
1772   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1773   auto PtrVt = getPointerTy(DAG.getDataLayout());
1774
1775   if (Subtarget->genLongCalls()) {
1776     assert((Subtarget->isTargetWindows() ||
1777             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1778            "long-calls with non-static relocation model!");
1779     // Handle a global address or an external symbol. If it's not one of
1780     // those, the target's already in a register, so we don't need to do
1781     // anything extra.
1782     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1783       const GlobalValue *GV = G->getGlobal();
1784       // Create a constant pool entry for the callee address
1785       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1786       ARMConstantPoolValue *CPV =
1787         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1788
1789       // Get the address of the callee into a register
1790       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1791       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1792       Callee = DAG.getLoad(
1793           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1794           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1795           false, false, 0);
1796     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1797       const char *Sym = S->getSymbol();
1798
1799       // Create a constant pool entry for the callee address
1800       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1801       ARMConstantPoolValue *CPV =
1802         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1803                                       ARMPCLabelIndex, 0);
1804       // Get the address of the callee into a register
1805       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1806       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1807       Callee = DAG.getLoad(
1808           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1809           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1810           false, false, 0);
1811     }
1812   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1813     const GlobalValue *GV = G->getGlobal();
1814     isDirect = true;
1815     bool isDef = GV->isStrongDefinitionForLinker();
1816     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1817                    getTargetMachine().getRelocationModel() != Reloc::Static;
1818     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1819     // ARM call to a local ARM function is predicable.
1820     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1821     // tBX takes a register source operand.
1822     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1823       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1824       Callee = DAG.getNode(
1825           ARMISD::WrapperPIC, dl, PtrVt,
1826           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1827       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1828                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1829                            false, false, true, 0);
1830     } else if (Subtarget->isTargetCOFF()) {
1831       assert(Subtarget->isTargetWindows() &&
1832              "Windows is the only supported COFF target");
1833       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1834                                  ? ARMII::MO_DLLIMPORT
1835                                  : ARMII::MO_NO_FLAG;
1836       Callee =
1837           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1838       if (GV->hasDLLImportStorageClass())
1839         Callee =
1840             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1841                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1842                         MachinePointerInfo::getGOT(DAG.getMachineFunction()),
1843                         false, false, false, 0);
1844     } else {
1845       // On ELF targets for PIC code, direct calls should go through the PLT
1846       unsigned OpFlags = 0;
1847       if (Subtarget->isTargetELF() &&
1848           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1849         OpFlags = ARMII::MO_PLT;
1850       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1851     }
1852   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1853     isDirect = true;
1854     bool isStub = Subtarget->isTargetMachO() &&
1855                   getTargetMachine().getRelocationModel() != Reloc::Static;
1856     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1857     // tBX takes a register source operand.
1858     const char *Sym = S->getSymbol();
1859     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1860       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1861       ARMConstantPoolValue *CPV =
1862         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1863                                       ARMPCLabelIndex, 4);
1864       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1865       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1866       Callee = DAG.getLoad(
1867           PtrVt, dl, DAG.getEntryNode(), CPAddr,
1868           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
1869           false, false, 0);
1870       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1871       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1872     } else {
1873       unsigned OpFlags = 0;
1874       // On ELF targets for PIC code, direct calls should go through the PLT
1875       if (Subtarget->isTargetELF() &&
1876                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1877         OpFlags = ARMII::MO_PLT;
1878       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1879     }
1880   }
1881
1882   // FIXME: handle tail calls differently.
1883   unsigned CallOpc;
1884   if (Subtarget->isThumb()) {
1885     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1886       CallOpc = ARMISD::CALL_NOLINK;
1887     else
1888       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1889   } else {
1890     if (!isDirect && !Subtarget->hasV5TOps())
1891       CallOpc = ARMISD::CALL_NOLINK;
1892     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1893              // Emit regular call when code size is the priority
1894              !MF.getFunction()->optForMinSize())
1895       // "mov lr, pc; b _foo" to avoid confusing the RSP
1896       CallOpc = ARMISD::CALL_NOLINK;
1897     else
1898       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1899   }
1900
1901   std::vector<SDValue> Ops;
1902   Ops.push_back(Chain);
1903   Ops.push_back(Callee);
1904
1905   // Add argument registers to the end of the list so that they are known live
1906   // into the call.
1907   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1908     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1909                                   RegsToPass[i].second.getValueType()));
1910
1911   // Add a register mask operand representing the call-preserved registers.
1912   if (!isTailCall) {
1913     const uint32_t *Mask;
1914     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1915     if (isThisReturn) {
1916       // For 'this' returns, use the R0-preserving mask if applicable
1917       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1918       if (!Mask) {
1919         // Set isThisReturn to false if the calling convention is not one that
1920         // allows 'returned' to be modeled in this way, so LowerCallResult does
1921         // not try to pass 'this' straight through
1922         isThisReturn = false;
1923         Mask = ARI->getCallPreservedMask(MF, CallConv);
1924       }
1925     } else
1926       Mask = ARI->getCallPreservedMask(MF, CallConv);
1927
1928     assert(Mask && "Missing call preserved mask for calling convention");
1929     Ops.push_back(DAG.getRegisterMask(Mask));
1930   }
1931
1932   if (InFlag.getNode())
1933     Ops.push_back(InFlag);
1934
1935   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1936   if (isTailCall) {
1937     MF.getFrameInfo()->setHasTailCall();
1938     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1939   }
1940
1941   // Returns a chain and a flag for retval copy to use.
1942   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1943   InFlag = Chain.getValue(1);
1944
1945   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1946                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1947   if (!Ins.empty())
1948     InFlag = Chain.getValue(1);
1949
1950   // Handle result values, copying them out of physregs into vregs that we
1951   // return.
1952   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1953                          InVals, isThisReturn,
1954                          isThisReturn ? OutVals[0] : SDValue());
1955 }
1956
1957 /// HandleByVal - Every parameter *after* a byval parameter is passed
1958 /// on the stack.  Remember the next parameter register to allocate,
1959 /// and then confiscate the rest of the parameter registers to insure
1960 /// this.
1961 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1962                                     unsigned Align) const {
1963   assert((State->getCallOrPrologue() == Prologue ||
1964           State->getCallOrPrologue() == Call) &&
1965          "unhandled ParmContext");
1966
1967   // Byval (as with any stack) slots are always at least 4 byte aligned.
1968   Align = std::max(Align, 4U);
1969
1970   unsigned Reg = State->AllocateReg(GPRArgRegs);
1971   if (!Reg)
1972     return;
1973
1974   unsigned AlignInRegs = Align / 4;
1975   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1976   for (unsigned i = 0; i < Waste; ++i)
1977     Reg = State->AllocateReg(GPRArgRegs);
1978
1979   if (!Reg)
1980     return;
1981
1982   unsigned Excess = 4 * (ARM::R4 - Reg);
1983
1984   // Special case when NSAA != SP and parameter size greater than size of
1985   // all remained GPR regs. In that case we can't split parameter, we must
1986   // send it to stack. We also must set NCRN to R4, so waste all
1987   // remained registers.
1988   const unsigned NSAAOffset = State->getNextStackOffset();
1989   if (NSAAOffset != 0 && Size > Excess) {
1990     while (State->AllocateReg(GPRArgRegs))
1991       ;
1992     return;
1993   }
1994
1995   // First register for byval parameter is the first register that wasn't
1996   // allocated before this method call, so it would be "reg".
1997   // If parameter is small enough to be saved in range [reg, r4), then
1998   // the end (first after last) register would be reg + param-size-in-regs,
1999   // else parameter would be splitted between registers and stack,
2000   // end register would be r4 in this case.
2001   unsigned ByValRegBegin = Reg;
2002   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2003   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2004   // Note, first register is allocated in the beginning of function already,
2005   // allocate remained amount of registers we need.
2006   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2007     State->AllocateReg(GPRArgRegs);
2008   // A byval parameter that is split between registers and memory needs its
2009   // size truncated here.
2010   // In the case where the entire structure fits in registers, we set the
2011   // size in memory to zero.
2012   Size = std::max<int>(Size - Excess, 0);
2013 }
2014
2015 /// MatchingStackOffset - Return true if the given stack call argument is
2016 /// already available in the same position (relatively) of the caller's
2017 /// incoming argument stack.
2018 static
2019 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2020                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2021                          const TargetInstrInfo *TII) {
2022   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2023   int FI = INT_MAX;
2024   if (Arg.getOpcode() == ISD::CopyFromReg) {
2025     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2026     if (!TargetRegisterInfo::isVirtualRegister(VR))
2027       return false;
2028     MachineInstr *Def = MRI->getVRegDef(VR);
2029     if (!Def)
2030       return false;
2031     if (!Flags.isByVal()) {
2032       if (!TII->isLoadFromStackSlot(Def, FI))
2033         return false;
2034     } else {
2035       return false;
2036     }
2037   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2038     if (Flags.isByVal())
2039       // ByVal argument is passed in as a pointer but it's now being
2040       // dereferenced. e.g.
2041       // define @foo(%struct.X* %A) {
2042       //   tail call @bar(%struct.X* byval %A)
2043       // }
2044       return false;
2045     SDValue Ptr = Ld->getBasePtr();
2046     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2047     if (!FINode)
2048       return false;
2049     FI = FINode->getIndex();
2050   } else
2051     return false;
2052
2053   assert(FI != INT_MAX);
2054   if (!MFI->isFixedObjectIndex(FI))
2055     return false;
2056   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2057 }
2058
2059 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2060 /// for tail call optimization. Targets which want to do tail call
2061 /// optimization should implement this function.
2062 bool
2063 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2064                                                      CallingConv::ID CalleeCC,
2065                                                      bool isVarArg,
2066                                                      bool isCalleeStructRet,
2067                                                      bool isCallerStructRet,
2068                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2069                                     const SmallVectorImpl<SDValue> &OutVals,
2070                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2071                                                      SelectionDAG& DAG) const {
2072   const Function *CallerF = DAG.getMachineFunction().getFunction();
2073   CallingConv::ID CallerCC = CallerF->getCallingConv();
2074   bool CCMatch = CallerCC == CalleeCC;
2075
2076   assert(Subtarget->supportsTailCall());
2077
2078   // Look for obvious safe cases to perform tail call optimization that do not
2079   // require ABI changes. This is what gcc calls sibcall.
2080
2081   // Do not sibcall optimize vararg calls unless the call site is not passing
2082   // any arguments.
2083   if (isVarArg && !Outs.empty())
2084     return false;
2085
2086   // Exception-handling functions need a special set of instructions to indicate
2087   // a return to the hardware. Tail-calling another function would probably
2088   // break this.
2089   if (CallerF->hasFnAttribute("interrupt"))
2090     return false;
2091
2092   // Also avoid sibcall optimization if either caller or callee uses struct
2093   // return semantics.
2094   if (isCalleeStructRet || isCallerStructRet)
2095     return false;
2096
2097   // Externally-defined functions with weak linkage should not be
2098   // tail-called on ARM when the OS does not support dynamic
2099   // pre-emption of symbols, as the AAELF spec requires normal calls
2100   // to undefined weak functions to be replaced with a NOP or jump to the
2101   // next instruction. The behaviour of branch instructions in this
2102   // situation (as used for tail calls) is implementation-defined, so we
2103   // cannot rely on the linker replacing the tail call with a return.
2104   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2105     const GlobalValue *GV = G->getGlobal();
2106     const Triple &TT = getTargetMachine().getTargetTriple();
2107     if (GV->hasExternalWeakLinkage() &&
2108         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2109       return false;
2110   }
2111
2112   // If the calling conventions do not match, then we'd better make sure the
2113   // results are returned in the same way as what the caller expects.
2114   if (!CCMatch) {
2115     SmallVector<CCValAssign, 16> RVLocs1;
2116     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2117                        *DAG.getContext(), Call);
2118     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2119
2120     SmallVector<CCValAssign, 16> RVLocs2;
2121     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2122                        *DAG.getContext(), Call);
2123     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2124
2125     if (RVLocs1.size() != RVLocs2.size())
2126       return false;
2127     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2128       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2129         return false;
2130       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2131         return false;
2132       if (RVLocs1[i].isRegLoc()) {
2133         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2134           return false;
2135       } else {
2136         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2137           return false;
2138       }
2139     }
2140   }
2141
2142   // If Caller's vararg or byval argument has been split between registers and
2143   // stack, do not perform tail call, since part of the argument is in caller's
2144   // local frame.
2145   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2146                                       getInfo<ARMFunctionInfo>();
2147   if (AFI_Caller->getArgRegsSaveSize())
2148     return false;
2149
2150   // If the callee takes no arguments then go on to check the results of the
2151   // call.
2152   if (!Outs.empty()) {
2153     // Check if stack adjustment is needed. For now, do not do this if any
2154     // argument is passed on the stack.
2155     SmallVector<CCValAssign, 16> ArgLocs;
2156     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2157                       *DAG.getContext(), Call);
2158     CCInfo.AnalyzeCallOperands(Outs,
2159                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2160     if (CCInfo.getNextStackOffset()) {
2161       MachineFunction &MF = DAG.getMachineFunction();
2162
2163       // Check if the arguments are already laid out in the right way as
2164       // the caller's fixed stack objects.
2165       MachineFrameInfo *MFI = MF.getFrameInfo();
2166       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2167       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2168       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2169            i != e;
2170            ++i, ++realArgIdx) {
2171         CCValAssign &VA = ArgLocs[i];
2172         EVT RegVT = VA.getLocVT();
2173         SDValue Arg = OutVals[realArgIdx];
2174         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2175         if (VA.getLocInfo() == CCValAssign::Indirect)
2176           return false;
2177         if (VA.needsCustom()) {
2178           // f64 and vector types are split into multiple registers or
2179           // register/stack-slot combinations.  The types will not match
2180           // the registers; give up on memory f64 refs until we figure
2181           // out what to do about this.
2182           if (!VA.isRegLoc())
2183             return false;
2184           if (!ArgLocs[++i].isRegLoc())
2185             return false;
2186           if (RegVT == MVT::v2f64) {
2187             if (!ArgLocs[++i].isRegLoc())
2188               return false;
2189             if (!ArgLocs[++i].isRegLoc())
2190               return false;
2191           }
2192         } else if (!VA.isRegLoc()) {
2193           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2194                                    MFI, MRI, TII))
2195             return false;
2196         }
2197       }
2198     }
2199   }
2200
2201   return true;
2202 }
2203
2204 bool
2205 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2206                                   MachineFunction &MF, bool isVarArg,
2207                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2208                                   LLVMContext &Context) const {
2209   SmallVector<CCValAssign, 16> RVLocs;
2210   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2211   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2212                                                     isVarArg));
2213 }
2214
2215 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2216                                     SDLoc DL, SelectionDAG &DAG) {
2217   const MachineFunction &MF = DAG.getMachineFunction();
2218   const Function *F = MF.getFunction();
2219
2220   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2221
2222   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2223   // version of the "preferred return address". These offsets affect the return
2224   // instruction if this is a return from PL1 without hypervisor extensions.
2225   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2226   //    SWI:     0      "subs pc, lr, #0"
2227   //    ABORT:   +4     "subs pc, lr, #4"
2228   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2229   // UNDEF varies depending on where the exception came from ARM or Thumb
2230   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2231
2232   int64_t LROffset;
2233   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2234       IntKind == "ABORT")
2235     LROffset = 4;
2236   else if (IntKind == "SWI" || IntKind == "UNDEF")
2237     LROffset = 0;
2238   else
2239     report_fatal_error("Unsupported interrupt attribute. If present, value "
2240                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2241
2242   RetOps.insert(RetOps.begin() + 1,
2243                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2244
2245   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2246 }
2247
2248 SDValue
2249 ARMTargetLowering::LowerReturn(SDValue Chain,
2250                                CallingConv::ID CallConv, bool isVarArg,
2251                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2252                                const SmallVectorImpl<SDValue> &OutVals,
2253                                SDLoc dl, SelectionDAG &DAG) const {
2254
2255   // CCValAssign - represent the assignment of the return value to a location.
2256   SmallVector<CCValAssign, 16> RVLocs;
2257
2258   // CCState - Info about the registers and stack slots.
2259   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2260                     *DAG.getContext(), Call);
2261
2262   // Analyze outgoing return values.
2263   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2264                                                isVarArg));
2265
2266   SDValue Flag;
2267   SmallVector<SDValue, 4> RetOps;
2268   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2269   bool isLittleEndian = Subtarget->isLittle();
2270
2271   MachineFunction &MF = DAG.getMachineFunction();
2272   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2273   AFI->setReturnRegsCount(RVLocs.size());
2274
2275   // Copy the result values into the output registers.
2276   for (unsigned i = 0, realRVLocIdx = 0;
2277        i != RVLocs.size();
2278        ++i, ++realRVLocIdx) {
2279     CCValAssign &VA = RVLocs[i];
2280     assert(VA.isRegLoc() && "Can only return in registers!");
2281
2282     SDValue Arg = OutVals[realRVLocIdx];
2283
2284     switch (VA.getLocInfo()) {
2285     default: llvm_unreachable("Unknown loc info!");
2286     case CCValAssign::Full: break;
2287     case CCValAssign::BCvt:
2288       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2289       break;
2290     }
2291
2292     if (VA.needsCustom()) {
2293       if (VA.getLocVT() == MVT::v2f64) {
2294         // Extract the first half and return it in two registers.
2295         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2296                                    DAG.getConstant(0, dl, MVT::i32));
2297         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2298                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2299
2300         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2301                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2302                                  Flag);
2303         Flag = Chain.getValue(1);
2304         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2305         VA = RVLocs[++i]; // skip ahead to next loc
2306         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2307                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2308                                  Flag);
2309         Flag = Chain.getValue(1);
2310         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2311         VA = RVLocs[++i]; // skip ahead to next loc
2312
2313         // Extract the 2nd half and fall through to handle it as an f64 value.
2314         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2315                           DAG.getConstant(1, dl, MVT::i32));
2316       }
2317       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2318       // available.
2319       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2320                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2321       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2322                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2323                                Flag);
2324       Flag = Chain.getValue(1);
2325       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2326       VA = RVLocs[++i]; // skip ahead to next loc
2327       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2328                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2329                                Flag);
2330     } else
2331       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2332
2333     // Guarantee that all emitted copies are
2334     // stuck together, avoiding something bad.
2335     Flag = Chain.getValue(1);
2336     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2337   }
2338
2339   // Update chain and glue.
2340   RetOps[0] = Chain;
2341   if (Flag.getNode())
2342     RetOps.push_back(Flag);
2343
2344   // CPUs which aren't M-class use a special sequence to return from
2345   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2346   // though we use "subs pc, lr, #N").
2347   //
2348   // M-class CPUs actually use a normal return sequence with a special
2349   // (hardware-provided) value in LR, so the normal code path works.
2350   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2351       !Subtarget->isMClass()) {
2352     if (Subtarget->isThumb1Only())
2353       report_fatal_error("interrupt attribute is not supported in Thumb1");
2354     return LowerInterruptReturn(RetOps, dl, DAG);
2355   }
2356
2357   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2358 }
2359
2360 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2361   if (N->getNumValues() != 1)
2362     return false;
2363   if (!N->hasNUsesOfValue(1, 0))
2364     return false;
2365
2366   SDValue TCChain = Chain;
2367   SDNode *Copy = *N->use_begin();
2368   if (Copy->getOpcode() == ISD::CopyToReg) {
2369     // If the copy has a glue operand, we conservatively assume it isn't safe to
2370     // perform a tail call.
2371     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2372       return false;
2373     TCChain = Copy->getOperand(0);
2374   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2375     SDNode *VMov = Copy;
2376     // f64 returned in a pair of GPRs.
2377     SmallPtrSet<SDNode*, 2> Copies;
2378     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2379          UI != UE; ++UI) {
2380       if (UI->getOpcode() != ISD::CopyToReg)
2381         return false;
2382       Copies.insert(*UI);
2383     }
2384     if (Copies.size() > 2)
2385       return false;
2386
2387     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2388          UI != UE; ++UI) {
2389       SDValue UseChain = UI->getOperand(0);
2390       if (Copies.count(UseChain.getNode()))
2391         // Second CopyToReg
2392         Copy = *UI;
2393       else {
2394         // We are at the top of this chain.
2395         // If the copy has a glue operand, we conservatively assume it
2396         // isn't safe to perform a tail call.
2397         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2398           return false;
2399         // First CopyToReg
2400         TCChain = UseChain;
2401       }
2402     }
2403   } else if (Copy->getOpcode() == ISD::BITCAST) {
2404     // f32 returned in a single GPR.
2405     if (!Copy->hasOneUse())
2406       return false;
2407     Copy = *Copy->use_begin();
2408     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2409       return false;
2410     // If the copy has a glue operand, we conservatively assume it isn't safe to
2411     // perform a tail call.
2412     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2413       return false;
2414     TCChain = Copy->getOperand(0);
2415   } else {
2416     return false;
2417   }
2418
2419   bool HasRet = false;
2420   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2421        UI != UE; ++UI) {
2422     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2423         UI->getOpcode() != ARMISD::INTRET_FLAG)
2424       return false;
2425     HasRet = true;
2426   }
2427
2428   if (!HasRet)
2429     return false;
2430
2431   Chain = TCChain;
2432   return true;
2433 }
2434
2435 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2436   if (!Subtarget->supportsTailCall())
2437     return false;
2438
2439   auto Attr =
2440       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2441   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2442     return false;
2443
2444   return true;
2445 }
2446
2447 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2448 // and pass the lower and high parts through.
2449 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2450   SDLoc DL(Op);
2451   SDValue WriteValue = Op->getOperand(2);
2452
2453   // This function is only supposed to be called for i64 type argument.
2454   assert(WriteValue.getValueType() == MVT::i64
2455           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2456
2457   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2458                            DAG.getConstant(0, DL, MVT::i32));
2459   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2460                            DAG.getConstant(1, DL, MVT::i32));
2461   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2462   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2463 }
2464
2465 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2466 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2467 // one of the above mentioned nodes. It has to be wrapped because otherwise
2468 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2469 // be used to form addressing mode. These wrapped nodes will be selected
2470 // into MOVi.
2471 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2472   EVT PtrVT = Op.getValueType();
2473   // FIXME there is no actual debug info here
2474   SDLoc dl(Op);
2475   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2476   SDValue Res;
2477   if (CP->isMachineConstantPoolEntry())
2478     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2479                                     CP->getAlignment());
2480   else
2481     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2482                                     CP->getAlignment());
2483   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2484 }
2485
2486 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2487   return MachineJumpTableInfo::EK_Inline;
2488 }
2489
2490 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2491                                              SelectionDAG &DAG) const {
2492   MachineFunction &MF = DAG.getMachineFunction();
2493   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2494   unsigned ARMPCLabelIndex = 0;
2495   SDLoc DL(Op);
2496   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2497   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2498   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2499   SDValue CPAddr;
2500   if (RelocM == Reloc::Static) {
2501     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2502   } else {
2503     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2504     ARMPCLabelIndex = AFI->createPICLabelUId();
2505     ARMConstantPoolValue *CPV =
2506       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2507                                       ARMCP::CPBlockAddress, PCAdj);
2508     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2509   }
2510   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2511   SDValue Result =
2512       DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2513                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2514                   false, false, false, 0);
2515   if (RelocM == Reloc::Static)
2516     return Result;
2517   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2518   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2519 }
2520
2521 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2522 SDValue
2523 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2524                                                  SelectionDAG &DAG) const {
2525   SDLoc dl(GA);
2526   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2527   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2528   MachineFunction &MF = DAG.getMachineFunction();
2529   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2530   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2531   ARMConstantPoolValue *CPV =
2532     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2533                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2534   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2535   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2536   Argument =
2537       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2538                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2539                   false, false, false, 0);
2540   SDValue Chain = Argument.getValue(1);
2541
2542   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2543   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2544
2545   // call __tls_get_addr.
2546   ArgListTy Args;
2547   ArgListEntry Entry;
2548   Entry.Node = Argument;
2549   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2550   Args.push_back(Entry);
2551
2552   // FIXME: is there useful debug info available here?
2553   TargetLowering::CallLoweringInfo CLI(DAG);
2554   CLI.setDebugLoc(dl).setChain(Chain)
2555     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2556                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2557                0);
2558
2559   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2560   return CallResult.first;
2561 }
2562
2563 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2564 // "local exec" model.
2565 SDValue
2566 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2567                                         SelectionDAG &DAG,
2568                                         TLSModel::Model model) const {
2569   const GlobalValue *GV = GA->getGlobal();
2570   SDLoc dl(GA);
2571   SDValue Offset;
2572   SDValue Chain = DAG.getEntryNode();
2573   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2574   // Get the Thread Pointer
2575   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2576
2577   if (model == TLSModel::InitialExec) {
2578     MachineFunction &MF = DAG.getMachineFunction();
2579     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2580     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2581     // Initial exec model.
2582     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2583     ARMConstantPoolValue *CPV =
2584       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2585                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2586                                       true);
2587     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2588     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2589     Offset = DAG.getLoad(
2590         PtrVT, dl, Chain, Offset,
2591         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2592         false, false, 0);
2593     Chain = Offset.getValue(1);
2594
2595     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2596     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2597
2598     Offset = DAG.getLoad(
2599         PtrVT, dl, Chain, Offset,
2600         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2601         false, false, 0);
2602   } else {
2603     // local exec model
2604     assert(model == TLSModel::LocalExec);
2605     ARMConstantPoolValue *CPV =
2606       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2607     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2608     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2609     Offset = DAG.getLoad(
2610         PtrVT, dl, Chain, Offset,
2611         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2612         false, false, 0);
2613   }
2614
2615   // The address of the thread local variable is the add of the thread
2616   // pointer with the offset of the variable.
2617   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2618 }
2619
2620 SDValue
2621 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2622   // TODO: implement the "local dynamic" model
2623   assert(Subtarget->isTargetELF() &&
2624          "TLS not implemented for non-ELF targets");
2625   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2626   if (DAG.getTarget().Options.EmulatedTLS)
2627     return LowerToTLSEmulatedModel(GA, DAG);
2628
2629   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2630
2631   switch (model) {
2632     case TLSModel::GeneralDynamic:
2633     case TLSModel::LocalDynamic:
2634       return LowerToTLSGeneralDynamicModel(GA, DAG);
2635     case TLSModel::InitialExec:
2636     case TLSModel::LocalExec:
2637       return LowerToTLSExecModels(GA, DAG, model);
2638   }
2639   llvm_unreachable("bogus TLS model");
2640 }
2641
2642 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2643                                                  SelectionDAG &DAG) const {
2644   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2645   SDLoc dl(Op);
2646   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2647   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2648     bool UseGOT_PREL =
2649         !(GV->hasHiddenVisibility() || GV->hasLocalLinkage());
2650
2651     MachineFunction &MF = DAG.getMachineFunction();
2652     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2653     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2654     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2655     SDLoc dl(Op);
2656     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2657     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2658         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2659         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2660         /*AddCurrentAddress=*/UseGOT_PREL);
2661     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2662     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2663     SDValue Result = DAG.getLoad(
2664         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2665         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2666         false, false, 0);
2667     SDValue Chain = Result.getValue(1);
2668     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2669     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2670     if (UseGOT_PREL)
2671       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2672                            MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2673                            false, false, false, 0);
2674     return Result;
2675   }
2676
2677   // If we have T2 ops, we can materialize the address directly via movt/movw
2678   // pair. This is always cheaper.
2679   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2680     ++NumMovwMovt;
2681     // FIXME: Once remat is capable of dealing with instructions with register
2682     // operands, expand this into two nodes.
2683     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2684                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2685   } else {
2686     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2687     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2688     return DAG.getLoad(
2689         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2690         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2691         false, false, 0);
2692   }
2693 }
2694
2695 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2696                                                     SelectionDAG &DAG) const {
2697   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2698   SDLoc dl(Op);
2699   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2700   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2701
2702   if (Subtarget->useMovt(DAG.getMachineFunction()))
2703     ++NumMovwMovt;
2704
2705   // FIXME: Once remat is capable of dealing with instructions with register
2706   // operands, expand this into multiple nodes
2707   unsigned Wrapper =
2708       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2709
2710   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2711   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2712
2713   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2714     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2715                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2716                          false, false, false, 0);
2717   return Result;
2718 }
2719
2720 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2721                                                      SelectionDAG &DAG) const {
2722   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2723   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2724          "Windows on ARM expects to use movw/movt");
2725
2726   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2727   const ARMII::TOF TargetFlags =
2728     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2729   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2730   SDValue Result;
2731   SDLoc DL(Op);
2732
2733   ++NumMovwMovt;
2734
2735   // FIXME: Once remat is capable of dealing with instructions with register
2736   // operands, expand this into two nodes.
2737   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2738                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2739                                                   TargetFlags));
2740   if (GV->hasDLLImportStorageClass())
2741     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2742                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2743                          false, false, false, 0);
2744   return Result;
2745 }
2746
2747 SDValue
2748 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2749   SDLoc dl(Op);
2750   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2751   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2752                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2753                      Op.getOperand(1), Val);
2754 }
2755
2756 SDValue
2757 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2758   SDLoc dl(Op);
2759   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2760                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2761 }
2762
2763 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2764                                                       SelectionDAG &DAG) const {
2765   SDLoc dl(Op);
2766   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2767                      Op.getOperand(0));
2768 }
2769
2770 SDValue
2771 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2772                                           const ARMSubtarget *Subtarget) const {
2773   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2774   SDLoc dl(Op);
2775   switch (IntNo) {
2776   default: return SDValue();    // Don't custom lower most intrinsics.
2777   case Intrinsic::arm_rbit: {
2778     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2779            "RBIT intrinsic must have i32 type!");
2780     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2781   }
2782   case Intrinsic::arm_thread_pointer: {
2783     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2784     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2785   }
2786   case Intrinsic::eh_sjlj_lsda: {
2787     MachineFunction &MF = DAG.getMachineFunction();
2788     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2789     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2790     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2791     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2792     SDValue CPAddr;
2793     unsigned PCAdj = (RelocM != Reloc::PIC_)
2794       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2795     ARMConstantPoolValue *CPV =
2796       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2797                                       ARMCP::CPLSDA, PCAdj);
2798     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2799     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2800     SDValue Result = DAG.getLoad(
2801         PtrVT, dl, DAG.getEntryNode(), CPAddr,
2802         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2803         false, false, 0);
2804
2805     if (RelocM == Reloc::PIC_) {
2806       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2807       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2808     }
2809     return Result;
2810   }
2811   case Intrinsic::arm_neon_vmulls:
2812   case Intrinsic::arm_neon_vmullu: {
2813     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2814       ? ARMISD::VMULLs : ARMISD::VMULLu;
2815     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2816                        Op.getOperand(1), Op.getOperand(2));
2817   }
2818   case Intrinsic::arm_neon_vminnm:
2819   case Intrinsic::arm_neon_vmaxnm: {
2820     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2821       ? ISD::FMINNUM : ISD::FMAXNUM;
2822     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2823                        Op.getOperand(1), Op.getOperand(2));
2824   }
2825   case Intrinsic::arm_neon_vminu:
2826   case Intrinsic::arm_neon_vmaxu: {
2827     if (Op.getValueType().isFloatingPoint())
2828       return SDValue();
2829     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
2830       ? ISD::UMIN : ISD::UMAX;
2831     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2832                          Op.getOperand(1), Op.getOperand(2));
2833   }
2834   case Intrinsic::arm_neon_vmins:
2835   case Intrinsic::arm_neon_vmaxs: {
2836     // v{min,max}s is overloaded between signed integers and floats.
2837     if (!Op.getValueType().isFloatingPoint()) {
2838       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2839         ? ISD::SMIN : ISD::SMAX;
2840       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2841                          Op.getOperand(1), Op.getOperand(2));
2842     }
2843     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
2844       ? ISD::FMINNAN : ISD::FMAXNAN;
2845     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2846                        Op.getOperand(1), Op.getOperand(2));
2847   }
2848   }
2849 }
2850
2851 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2852                                  const ARMSubtarget *Subtarget) {
2853   // FIXME: handle "fence singlethread" more efficiently.
2854   SDLoc dl(Op);
2855   if (!Subtarget->hasDataBarrier()) {
2856     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2857     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2858     // here.
2859     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2860            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2861     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2862                        DAG.getConstant(0, dl, MVT::i32));
2863   }
2864
2865   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2866   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2867   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2868   if (Subtarget->isMClass()) {
2869     // Only a full system barrier exists in the M-class architectures.
2870     Domain = ARM_MB::SY;
2871   } else if (Subtarget->isSwift() && Ord == Release) {
2872     // Swift happens to implement ISHST barriers in a way that's compatible with
2873     // Release semantics but weaker than ISH so we'd be fools not to use
2874     // it. Beware: other processors probably don't!
2875     Domain = ARM_MB::ISHST;
2876   }
2877
2878   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2879                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2880                      DAG.getConstant(Domain, dl, MVT::i32));
2881 }
2882
2883 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2884                              const ARMSubtarget *Subtarget) {
2885   // ARM pre v5TE and Thumb1 does not have preload instructions.
2886   if (!(Subtarget->isThumb2() ||
2887         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2888     // Just preserve the chain.
2889     return Op.getOperand(0);
2890
2891   SDLoc dl(Op);
2892   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2893   if (!isRead &&
2894       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2895     // ARMv7 with MP extension has PLDW.
2896     return Op.getOperand(0);
2897
2898   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2899   if (Subtarget->isThumb()) {
2900     // Invert the bits.
2901     isRead = ~isRead & 1;
2902     isData = ~isData & 1;
2903   }
2904
2905   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2906                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2907                      DAG.getConstant(isData, dl, MVT::i32));
2908 }
2909
2910 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2911   MachineFunction &MF = DAG.getMachineFunction();
2912   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2913
2914   // vastart just stores the address of the VarArgsFrameIndex slot into the
2915   // memory location argument.
2916   SDLoc dl(Op);
2917   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2918   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2919   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2920   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2921                       MachinePointerInfo(SV), false, false, 0);
2922 }
2923
2924 SDValue
2925 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2926                                         SDValue &Root, SelectionDAG &DAG,
2927                                         SDLoc dl) const {
2928   MachineFunction &MF = DAG.getMachineFunction();
2929   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2930
2931   const TargetRegisterClass *RC;
2932   if (AFI->isThumb1OnlyFunction())
2933     RC = &ARM::tGPRRegClass;
2934   else
2935     RC = &ARM::GPRRegClass;
2936
2937   // Transform the arguments stored in physical registers into virtual ones.
2938   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2939   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2940
2941   SDValue ArgValue2;
2942   if (NextVA.isMemLoc()) {
2943     MachineFrameInfo *MFI = MF.getFrameInfo();
2944     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2945
2946     // Create load node to retrieve arguments from the stack.
2947     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2948     ArgValue2 = DAG.getLoad(
2949         MVT::i32, dl, Root, FIN,
2950         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2951         false, false, 0);
2952   } else {
2953     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2954     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2955   }
2956   if (!Subtarget->isLittle())
2957     std::swap (ArgValue, ArgValue2);
2958   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2959 }
2960
2961 // The remaining GPRs hold either the beginning of variable-argument
2962 // data, or the beginning of an aggregate passed by value (usually
2963 // byval).  Either way, we allocate stack slots adjacent to the data
2964 // provided by our caller, and store the unallocated registers there.
2965 // If this is a variadic function, the va_list pointer will begin with
2966 // these values; otherwise, this reassembles a (byval) structure that
2967 // was split between registers and memory.
2968 // Return: The frame index registers were stored into.
2969 int
2970 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2971                                   SDLoc dl, SDValue &Chain,
2972                                   const Value *OrigArg,
2973                                   unsigned InRegsParamRecordIdx,
2974                                   int ArgOffset,
2975                                   unsigned ArgSize) const {
2976   // Currently, two use-cases possible:
2977   // Case #1. Non-var-args function, and we meet first byval parameter.
2978   //          Setup first unallocated register as first byval register;
2979   //          eat all remained registers
2980   //          (these two actions are performed by HandleByVal method).
2981   //          Then, here, we initialize stack frame with
2982   //          "store-reg" instructions.
2983   // Case #2. Var-args function, that doesn't contain byval parameters.
2984   //          The same: eat all remained unallocated registers,
2985   //          initialize stack frame.
2986
2987   MachineFunction &MF = DAG.getMachineFunction();
2988   MachineFrameInfo *MFI = MF.getFrameInfo();
2989   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2990   unsigned RBegin, REnd;
2991   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2992     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2993   } else {
2994     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2995     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2996     REnd = ARM::R4;
2997   }
2998
2999   if (REnd != RBegin)
3000     ArgOffset = -4 * (ARM::R4 - RBegin);
3001
3002   auto PtrVT = getPointerTy(DAG.getDataLayout());
3003   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
3004   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3005
3006   SmallVector<SDValue, 4> MemOps;
3007   const TargetRegisterClass *RC =
3008       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3009
3010   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3011     unsigned VReg = MF.addLiveIn(Reg, RC);
3012     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3013     SDValue Store =
3014         DAG.getStore(Val.getValue(1), dl, Val, FIN,
3015                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
3016     MemOps.push_back(Store);
3017     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3018   }
3019
3020   if (!MemOps.empty())
3021     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3022   return FrameIndex;
3023 }
3024
3025 // Setup stack frame, the va_list pointer will start from.
3026 void
3027 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3028                                         SDLoc dl, SDValue &Chain,
3029                                         unsigned ArgOffset,
3030                                         unsigned TotalArgRegsSaveSize,
3031                                         bool ForceMutable) const {
3032   MachineFunction &MF = DAG.getMachineFunction();
3033   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3034
3035   // Try to store any remaining integer argument regs
3036   // to their spots on the stack so that they may be loaded by deferencing
3037   // the result of va_next.
3038   // If there is no regs to be stored, just point address after last
3039   // argument passed via stack.
3040   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3041                                   CCInfo.getInRegsParamsCount(),
3042                                   CCInfo.getNextStackOffset(), 4);
3043   AFI->setVarArgsFrameIndex(FrameIndex);
3044 }
3045
3046 SDValue
3047 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3048                                         CallingConv::ID CallConv, bool isVarArg,
3049                                         const SmallVectorImpl<ISD::InputArg>
3050                                           &Ins,
3051                                         SDLoc dl, SelectionDAG &DAG,
3052                                         SmallVectorImpl<SDValue> &InVals)
3053                                           const {
3054   MachineFunction &MF = DAG.getMachineFunction();
3055   MachineFrameInfo *MFI = MF.getFrameInfo();
3056
3057   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3058
3059   // Assign locations to all of the incoming arguments.
3060   SmallVector<CCValAssign, 16> ArgLocs;
3061   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3062                     *DAG.getContext(), Prologue);
3063   CCInfo.AnalyzeFormalArguments(Ins,
3064                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3065                                                   isVarArg));
3066
3067   SmallVector<SDValue, 16> ArgValues;
3068   SDValue ArgValue;
3069   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3070   unsigned CurArgIdx = 0;
3071
3072   // Initially ArgRegsSaveSize is zero.
3073   // Then we increase this value each time we meet byval parameter.
3074   // We also increase this value in case of varargs function.
3075   AFI->setArgRegsSaveSize(0);
3076
3077   // Calculate the amount of stack space that we need to allocate to store
3078   // byval and variadic arguments that are passed in registers.
3079   // We need to know this before we allocate the first byval or variadic
3080   // argument, as they will be allocated a stack slot below the CFA (Canonical
3081   // Frame Address, the stack pointer at entry to the function).
3082   unsigned ArgRegBegin = ARM::R4;
3083   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3084     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3085       break;
3086
3087     CCValAssign &VA = ArgLocs[i];
3088     unsigned Index = VA.getValNo();
3089     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3090     if (!Flags.isByVal())
3091       continue;
3092
3093     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3094     unsigned RBegin, REnd;
3095     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3096     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3097
3098     CCInfo.nextInRegsParam();
3099   }
3100   CCInfo.rewindByValRegsInfo();
3101
3102   int lastInsIndex = -1;
3103   if (isVarArg && MFI->hasVAStart()) {
3104     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3105     if (RegIdx != array_lengthof(GPRArgRegs))
3106       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3107   }
3108
3109   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3110   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3111   auto PtrVT = getPointerTy(DAG.getDataLayout());
3112
3113   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3114     CCValAssign &VA = ArgLocs[i];
3115     if (Ins[VA.getValNo()].isOrigArg()) {
3116       std::advance(CurOrigArg,
3117                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3118       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3119     }
3120     // Arguments stored in registers.
3121     if (VA.isRegLoc()) {
3122       EVT RegVT = VA.getLocVT();
3123
3124       if (VA.needsCustom()) {
3125         // f64 and vector types are split up into multiple registers or
3126         // combinations of registers and stack slots.
3127         if (VA.getLocVT() == MVT::v2f64) {
3128           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3129                                                    Chain, DAG, dl);
3130           VA = ArgLocs[++i]; // skip ahead to next loc
3131           SDValue ArgValue2;
3132           if (VA.isMemLoc()) {
3133             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3134             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3135             ArgValue2 = DAG.getLoad(
3136                 MVT::f64, dl, Chain, FIN,
3137                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3138                 false, false, false, 0);
3139           } else {
3140             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3141                                              Chain, DAG, dl);
3142           }
3143           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3144           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3145                                  ArgValue, ArgValue1,
3146                                  DAG.getIntPtrConstant(0, dl));
3147           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3148                                  ArgValue, ArgValue2,
3149                                  DAG.getIntPtrConstant(1, dl));
3150         } else
3151           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3152
3153       } else {
3154         const TargetRegisterClass *RC;
3155
3156         if (RegVT == MVT::f32)
3157           RC = &ARM::SPRRegClass;
3158         else if (RegVT == MVT::f64)
3159           RC = &ARM::DPRRegClass;
3160         else if (RegVT == MVT::v2f64)
3161           RC = &ARM::QPRRegClass;
3162         else if (RegVT == MVT::i32)
3163           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3164                                            : &ARM::GPRRegClass;
3165         else
3166           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3167
3168         // Transform the arguments in physical registers into virtual ones.
3169         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3170         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3171       }
3172
3173       // If this is an 8 or 16-bit value, it is really passed promoted
3174       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3175       // truncate to the right size.
3176       switch (VA.getLocInfo()) {
3177       default: llvm_unreachable("Unknown loc info!");
3178       case CCValAssign::Full: break;
3179       case CCValAssign::BCvt:
3180         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3181         break;
3182       case CCValAssign::SExt:
3183         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3184                                DAG.getValueType(VA.getValVT()));
3185         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3186         break;
3187       case CCValAssign::ZExt:
3188         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3189                                DAG.getValueType(VA.getValVT()));
3190         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3191         break;
3192       }
3193
3194       InVals.push_back(ArgValue);
3195
3196     } else { // VA.isRegLoc()
3197
3198       // sanity check
3199       assert(VA.isMemLoc());
3200       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3201
3202       int index = VA.getValNo();
3203
3204       // Some Ins[] entries become multiple ArgLoc[] entries.
3205       // Process them only once.
3206       if (index != lastInsIndex)
3207         {
3208           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3209           // FIXME: For now, all byval parameter objects are marked mutable.
3210           // This can be changed with more analysis.
3211           // In case of tail call optimization mark all arguments mutable.
3212           // Since they could be overwritten by lowering of arguments in case of
3213           // a tail call.
3214           if (Flags.isByVal()) {
3215             assert(Ins[index].isOrigArg() &&
3216                    "Byval arguments cannot be implicit");
3217             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3218
3219             int FrameIndex = StoreByValRegs(
3220                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3221                 VA.getLocMemOffset(), Flags.getByValSize());
3222             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3223             CCInfo.nextInRegsParam();
3224           } else {
3225             unsigned FIOffset = VA.getLocMemOffset();
3226             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3227                                             FIOffset, true);
3228
3229             // Create load nodes to retrieve arguments from the stack.
3230             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3231             InVals.push_back(DAG.getLoad(
3232                 VA.getValVT(), dl, Chain, FIN,
3233                 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3234                 false, false, false, 0));
3235           }
3236           lastInsIndex = index;
3237         }
3238     }
3239   }
3240
3241   // varargs
3242   if (isVarArg && MFI->hasVAStart())
3243     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3244                          CCInfo.getNextStackOffset(),
3245                          TotalArgRegsSaveSize);
3246
3247   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3248
3249   return Chain;
3250 }
3251
3252 /// isFloatingPointZero - Return true if this is +0.0.
3253 static bool isFloatingPointZero(SDValue Op) {
3254   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3255     return CFP->getValueAPF().isPosZero();
3256   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3257     // Maybe this has already been legalized into the constant pool?
3258     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3259       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3260       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3261         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3262           return CFP->getValueAPF().isPosZero();
3263     }
3264   } else if (Op->getOpcode() == ISD::BITCAST &&
3265              Op->getValueType(0) == MVT::f64) {
3266     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3267     // created by LowerConstantFP().
3268     SDValue BitcastOp = Op->getOperand(0);
3269     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3270       SDValue MoveOp = BitcastOp->getOperand(0);
3271       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3272           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3273         return true;
3274       }
3275     }
3276   }
3277   return false;
3278 }
3279
3280 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3281 /// the given operands.
3282 SDValue
3283 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3284                              SDValue &ARMcc, SelectionDAG &DAG,
3285                              SDLoc dl) const {
3286   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3287     unsigned C = RHSC->getZExtValue();
3288     if (!isLegalICmpImmediate(C)) {
3289       // Constant does not fit, try adjusting it by one?
3290       switch (CC) {
3291       default: break;
3292       case ISD::SETLT:
3293       case ISD::SETGE:
3294         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3295           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3296           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3297         }
3298         break;
3299       case ISD::SETULT:
3300       case ISD::SETUGE:
3301         if (C != 0 && isLegalICmpImmediate(C-1)) {
3302           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3303           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3304         }
3305         break;
3306       case ISD::SETLE:
3307       case ISD::SETGT:
3308         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3309           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3310           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3311         }
3312         break;
3313       case ISD::SETULE:
3314       case ISD::SETUGT:
3315         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3316           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3317           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3318         }
3319         break;
3320       }
3321     }
3322   }
3323
3324   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3325   ARMISD::NodeType CompareType;
3326   switch (CondCode) {
3327   default:
3328     CompareType = ARMISD::CMP;
3329     break;
3330   case ARMCC::EQ:
3331   case ARMCC::NE:
3332     // Uses only Z Flag
3333     CompareType = ARMISD::CMPZ;
3334     break;
3335   }
3336   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3337   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3338 }
3339
3340 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3341 SDValue
3342 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3343                              SDLoc dl) const {
3344   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3345   SDValue Cmp;
3346   if (!isFloatingPointZero(RHS))
3347     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3348   else
3349     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3350   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3351 }
3352
3353 /// duplicateCmp - Glue values can have only one use, so this function
3354 /// duplicates a comparison node.
3355 SDValue
3356 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3357   unsigned Opc = Cmp.getOpcode();
3358   SDLoc DL(Cmp);
3359   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3360     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3361
3362   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3363   Cmp = Cmp.getOperand(0);
3364   Opc = Cmp.getOpcode();
3365   if (Opc == ARMISD::CMPFP)
3366     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3367   else {
3368     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3369     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3370   }
3371   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3372 }
3373
3374 std::pair<SDValue, SDValue>
3375 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3376                                  SDValue &ARMcc) const {
3377   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3378
3379   SDValue Value, OverflowCmp;
3380   SDValue LHS = Op.getOperand(0);
3381   SDValue RHS = Op.getOperand(1);
3382   SDLoc dl(Op);
3383
3384   // FIXME: We are currently always generating CMPs because we don't support
3385   // generating CMN through the backend. This is not as good as the natural
3386   // CMP case because it causes a register dependency and cannot be folded
3387   // later.
3388
3389   switch (Op.getOpcode()) {
3390   default:
3391     llvm_unreachable("Unknown overflow instruction!");
3392   case ISD::SADDO:
3393     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3394     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3395     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3396     break;
3397   case ISD::UADDO:
3398     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3399     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3400     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3401     break;
3402   case ISD::SSUBO:
3403     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3404     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3405     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3406     break;
3407   case ISD::USUBO:
3408     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3409     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3410     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3411     break;
3412   } // switch (...)
3413
3414   return std::make_pair(Value, OverflowCmp);
3415 }
3416
3417
3418 SDValue
3419 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3420   // Let legalize expand this if it isn't a legal type yet.
3421   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3422     return SDValue();
3423
3424   SDValue Value, OverflowCmp;
3425   SDValue ARMcc;
3426   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3427   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3428   SDLoc dl(Op);
3429   // We use 0 and 1 as false and true values.
3430   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3431   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3432   EVT VT = Op.getValueType();
3433
3434   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3435                                  ARMcc, CCR, OverflowCmp);
3436
3437   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3438   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3439 }
3440
3441
3442 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3443   SDValue Cond = Op.getOperand(0);
3444   SDValue SelectTrue = Op.getOperand(1);
3445   SDValue SelectFalse = Op.getOperand(2);
3446   SDLoc dl(Op);
3447   unsigned Opc = Cond.getOpcode();
3448
3449   if (Cond.getResNo() == 1 &&
3450       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3451        Opc == ISD::USUBO)) {
3452     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3453       return SDValue();
3454
3455     SDValue Value, OverflowCmp;
3456     SDValue ARMcc;
3457     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3458     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3459     EVT VT = Op.getValueType();
3460
3461     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3462                    OverflowCmp, DAG);
3463   }
3464
3465   // Convert:
3466   //
3467   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3468   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3469   //
3470   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3471     const ConstantSDNode *CMOVTrue =
3472       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3473     const ConstantSDNode *CMOVFalse =
3474       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3475
3476     if (CMOVTrue && CMOVFalse) {
3477       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3478       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3479
3480       SDValue True;
3481       SDValue False;
3482       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3483         True = SelectTrue;
3484         False = SelectFalse;
3485       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3486         True = SelectFalse;
3487         False = SelectTrue;
3488       }
3489
3490       if (True.getNode() && False.getNode()) {
3491         EVT VT = Op.getValueType();
3492         SDValue ARMcc = Cond.getOperand(2);
3493         SDValue CCR = Cond.getOperand(3);
3494         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3495         assert(True.getValueType() == VT);
3496         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3497       }
3498     }
3499   }
3500
3501   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3502   // undefined bits before doing a full-word comparison with zero.
3503   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3504                      DAG.getConstant(1, dl, Cond.getValueType()));
3505
3506   return DAG.getSelectCC(dl, Cond,
3507                          DAG.getConstant(0, dl, Cond.getValueType()),
3508                          SelectTrue, SelectFalse, ISD::SETNE);
3509 }
3510
3511 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3512                                  bool &swpCmpOps, bool &swpVselOps) {
3513   // Start by selecting the GE condition code for opcodes that return true for
3514   // 'equality'
3515   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3516       CC == ISD::SETULE)
3517     CondCode = ARMCC::GE;
3518
3519   // and GT for opcodes that return false for 'equality'.
3520   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3521            CC == ISD::SETULT)
3522     CondCode = ARMCC::GT;
3523
3524   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3525   // to swap the compare operands.
3526   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3527       CC == ISD::SETULT)
3528     swpCmpOps = true;
3529
3530   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3531   // If we have an unordered opcode, we need to swap the operands to the VSEL
3532   // instruction (effectively negating the condition).
3533   //
3534   // This also has the effect of swapping which one of 'less' or 'greater'
3535   // returns true, so we also swap the compare operands. It also switches
3536   // whether we return true for 'equality', so we compensate by picking the
3537   // opposite condition code to our original choice.
3538   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3539       CC == ISD::SETUGT) {
3540     swpCmpOps = !swpCmpOps;
3541     swpVselOps = !swpVselOps;
3542     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3543   }
3544
3545   // 'ordered' is 'anything but unordered', so use the VS condition code and
3546   // swap the VSEL operands.
3547   if (CC == ISD::SETO) {
3548     CondCode = ARMCC::VS;
3549     swpVselOps = true;
3550   }
3551
3552   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3553   // code and swap the VSEL operands.
3554   if (CC == ISD::SETUNE) {
3555     CondCode = ARMCC::EQ;
3556     swpVselOps = true;
3557   }
3558 }
3559
3560 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3561                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3562                                    SDValue Cmp, SelectionDAG &DAG) const {
3563   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3564     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3565                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3566     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3567                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3568
3569     SDValue TrueLow = TrueVal.getValue(0);
3570     SDValue TrueHigh = TrueVal.getValue(1);
3571     SDValue FalseLow = FalseVal.getValue(0);
3572     SDValue FalseHigh = FalseVal.getValue(1);
3573
3574     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3575                               ARMcc, CCR, Cmp);
3576     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3577                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3578
3579     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3580   } else {
3581     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3582                        Cmp);
3583   }
3584 }
3585
3586 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3587   EVT VT = Op.getValueType();
3588   SDValue LHS = Op.getOperand(0);
3589   SDValue RHS = Op.getOperand(1);
3590   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3591   SDValue TrueVal = Op.getOperand(2);
3592   SDValue FalseVal = Op.getOperand(3);
3593   SDLoc dl(Op);
3594
3595   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3596     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3597                                                     dl);
3598
3599     // If softenSetCCOperands only returned one value, we should compare it to
3600     // zero.
3601     if (!RHS.getNode()) {
3602       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3603       CC = ISD::SETNE;
3604     }
3605   }
3606
3607   if (LHS.getValueType() == MVT::i32) {
3608     // Try to generate VSEL on ARMv8.
3609     // The VSEL instruction can't use all the usual ARM condition
3610     // codes: it only has two bits to select the condition code, so it's
3611     // constrained to use only GE, GT, VS and EQ.
3612     //
3613     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3614     // swap the operands of the previous compare instruction (effectively
3615     // inverting the compare condition, swapping 'less' and 'greater') and
3616     // sometimes need to swap the operands to the VSEL (which inverts the
3617     // condition in the sense of firing whenever the previous condition didn't)
3618     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3619                                     TrueVal.getValueType() == MVT::f64)) {
3620       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3621       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3622           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3623         CC = ISD::getSetCCInverse(CC, true);
3624         std::swap(TrueVal, FalseVal);
3625       }
3626     }
3627
3628     SDValue ARMcc;
3629     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3630     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3631     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3632   }
3633
3634   ARMCC::CondCodes CondCode, CondCode2;
3635   FPCCToARMCC(CC, CondCode, CondCode2);
3636
3637   // Try to generate VMAXNM/VMINNM on ARMv8.
3638   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3639                                   TrueVal.getValueType() == MVT::f64)) {
3640     bool swpCmpOps = false;
3641     bool swpVselOps = false;
3642     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3643
3644     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3645         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3646       if (swpCmpOps)
3647         std::swap(LHS, RHS);
3648       if (swpVselOps)
3649         std::swap(TrueVal, FalseVal);
3650     }
3651   }
3652
3653   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3654   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3655   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3656   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3657   if (CondCode2 != ARMCC::AL) {
3658     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3659     // FIXME: Needs another CMP because flag can have but one use.
3660     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3661     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3662   }
3663   return Result;
3664 }
3665
3666 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3667 /// to morph to an integer compare sequence.
3668 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3669                            const ARMSubtarget *Subtarget) {
3670   SDNode *N = Op.getNode();
3671   if (!N->hasOneUse())
3672     // Otherwise it requires moving the value from fp to integer registers.
3673     return false;
3674   if (!N->getNumValues())
3675     return false;
3676   EVT VT = Op.getValueType();
3677   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3678     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3679     // vmrs are very slow, e.g. cortex-a8.
3680     return false;
3681
3682   if (isFloatingPointZero(Op)) {
3683     SeenZero = true;
3684     return true;
3685   }
3686   return ISD::isNormalLoad(N);
3687 }
3688
3689 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3690   if (isFloatingPointZero(Op))
3691     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3692
3693   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3694     return DAG.getLoad(MVT::i32, SDLoc(Op),
3695                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3696                        Ld->isVolatile(), Ld->isNonTemporal(),
3697                        Ld->isInvariant(), Ld->getAlignment());
3698
3699   llvm_unreachable("Unknown VFP cmp argument!");
3700 }
3701
3702 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3703                            SDValue &RetVal1, SDValue &RetVal2) {
3704   SDLoc dl(Op);
3705
3706   if (isFloatingPointZero(Op)) {
3707     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3708     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3709     return;
3710   }
3711
3712   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3713     SDValue Ptr = Ld->getBasePtr();
3714     RetVal1 = DAG.getLoad(MVT::i32, dl,
3715                           Ld->getChain(), Ptr,
3716                           Ld->getPointerInfo(),
3717                           Ld->isVolatile(), Ld->isNonTemporal(),
3718                           Ld->isInvariant(), Ld->getAlignment());
3719
3720     EVT PtrType = Ptr.getValueType();
3721     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3722     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3723                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3724     RetVal2 = DAG.getLoad(MVT::i32, dl,
3725                           Ld->getChain(), NewPtr,
3726                           Ld->getPointerInfo().getWithOffset(4),
3727                           Ld->isVolatile(), Ld->isNonTemporal(),
3728                           Ld->isInvariant(), NewAlign);
3729     return;
3730   }
3731
3732   llvm_unreachable("Unknown VFP cmp argument!");
3733 }
3734
3735 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3736 /// f32 and even f64 comparisons to integer ones.
3737 SDValue
3738 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3739   SDValue Chain = Op.getOperand(0);
3740   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3741   SDValue LHS = Op.getOperand(2);
3742   SDValue RHS = Op.getOperand(3);
3743   SDValue Dest = Op.getOperand(4);
3744   SDLoc dl(Op);
3745
3746   bool LHSSeenZero = false;
3747   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3748   bool RHSSeenZero = false;
3749   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3750   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3751     // If unsafe fp math optimization is enabled and there are no other uses of
3752     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3753     // to an integer comparison.
3754     if (CC == ISD::SETOEQ)
3755       CC = ISD::SETEQ;
3756     else if (CC == ISD::SETUNE)
3757       CC = ISD::SETNE;
3758
3759     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3760     SDValue ARMcc;
3761     if (LHS.getValueType() == MVT::f32) {
3762       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3763                         bitcastf32Toi32(LHS, DAG), Mask);
3764       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3765                         bitcastf32Toi32(RHS, DAG), Mask);
3766       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3767       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3768       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3769                          Chain, Dest, ARMcc, CCR, Cmp);
3770     }
3771
3772     SDValue LHS1, LHS2;
3773     SDValue RHS1, RHS2;
3774     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3775     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3776     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3777     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3778     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3779     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3780     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3781     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3782     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3783   }
3784
3785   return SDValue();
3786 }
3787
3788 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3789   SDValue Chain = Op.getOperand(0);
3790   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3791   SDValue LHS = Op.getOperand(2);
3792   SDValue RHS = Op.getOperand(3);
3793   SDValue Dest = Op.getOperand(4);
3794   SDLoc dl(Op);
3795
3796   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3797     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3798                                                     dl);
3799
3800     // If softenSetCCOperands only returned one value, we should compare it to
3801     // zero.
3802     if (!RHS.getNode()) {
3803       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3804       CC = ISD::SETNE;
3805     }
3806   }
3807
3808   if (LHS.getValueType() == MVT::i32) {
3809     SDValue ARMcc;
3810     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3811     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3812     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3813                        Chain, Dest, ARMcc, CCR, Cmp);
3814   }
3815
3816   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3817
3818   if (getTargetMachine().Options.UnsafeFPMath &&
3819       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3820        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3821     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3822     if (Result.getNode())
3823       return Result;
3824   }
3825
3826   ARMCC::CondCodes CondCode, CondCode2;
3827   FPCCToARMCC(CC, CondCode, CondCode2);
3828
3829   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3830   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3831   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3832   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3833   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3834   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3835   if (CondCode2 != ARMCC::AL) {
3836     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3837     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3838     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3839   }
3840   return Res;
3841 }
3842
3843 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3844   SDValue Chain = Op.getOperand(0);
3845   SDValue Table = Op.getOperand(1);
3846   SDValue Index = Op.getOperand(2);
3847   SDLoc dl(Op);
3848
3849   EVT PTy = getPointerTy(DAG.getDataLayout());
3850   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3851   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3852   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3853   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3854   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3855   if (Subtarget->isThumb2()) {
3856     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3857     // which does another jump to the destination. This also makes it easier
3858     // to translate it to TBB / TBH later.
3859     // FIXME: This might not work if the function is extremely large.
3860     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3861                        Addr, Op.getOperand(2), JTI);
3862   }
3863   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3864     Addr =
3865         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3866                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3867                     false, false, false, 0);
3868     Chain = Addr.getValue(1);
3869     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3870     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3871   } else {
3872     Addr =
3873         DAG.getLoad(PTy, dl, Chain, Addr,
3874                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
3875                     false, false, false, 0);
3876     Chain = Addr.getValue(1);
3877     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3878   }
3879 }
3880
3881 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3882   EVT VT = Op.getValueType();
3883   SDLoc dl(Op);
3884
3885   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3886     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3887       return Op;
3888     return DAG.UnrollVectorOp(Op.getNode());
3889   }
3890
3891   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3892          "Invalid type for custom lowering!");
3893   if (VT != MVT::v4i16)
3894     return DAG.UnrollVectorOp(Op.getNode());
3895
3896   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3897   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3898 }
3899
3900 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3901   EVT VT = Op.getValueType();
3902   if (VT.isVector())
3903     return LowerVectorFP_TO_INT(Op, DAG);
3904   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3905     RTLIB::Libcall LC;
3906     if (Op.getOpcode() == ISD::FP_TO_SINT)
3907       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3908                               Op.getValueType());
3909     else
3910       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3911                               Op.getValueType());
3912     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3913                        /*isSigned*/ false, SDLoc(Op)).first;
3914   }
3915
3916   return Op;
3917 }
3918
3919 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3920   EVT VT = Op.getValueType();
3921   SDLoc dl(Op);
3922
3923   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3924     if (VT.getVectorElementType() == MVT::f32)
3925       return Op;
3926     return DAG.UnrollVectorOp(Op.getNode());
3927   }
3928
3929   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3930          "Invalid type for custom lowering!");
3931   if (VT != MVT::v4f32)
3932     return DAG.UnrollVectorOp(Op.getNode());
3933
3934   unsigned CastOpc;
3935   unsigned Opc;
3936   switch (Op.getOpcode()) {
3937   default: llvm_unreachable("Invalid opcode!");
3938   case ISD::SINT_TO_FP:
3939     CastOpc = ISD::SIGN_EXTEND;
3940     Opc = ISD::SINT_TO_FP;
3941     break;
3942   case ISD::UINT_TO_FP:
3943     CastOpc = ISD::ZERO_EXTEND;
3944     Opc = ISD::UINT_TO_FP;
3945     break;
3946   }
3947
3948   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3949   return DAG.getNode(Opc, dl, VT, Op);
3950 }
3951
3952 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3953   EVT VT = Op.getValueType();
3954   if (VT.isVector())
3955     return LowerVectorINT_TO_FP(Op, DAG);
3956   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3957     RTLIB::Libcall LC;
3958     if (Op.getOpcode() == ISD::SINT_TO_FP)
3959       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3960                               Op.getValueType());
3961     else
3962       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3963                               Op.getValueType());
3964     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
3965                        /*isSigned*/ false, SDLoc(Op)).first;
3966   }
3967
3968   return Op;
3969 }
3970
3971 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3972   // Implement fcopysign with a fabs and a conditional fneg.
3973   SDValue Tmp0 = Op.getOperand(0);
3974   SDValue Tmp1 = Op.getOperand(1);
3975   SDLoc dl(Op);
3976   EVT VT = Op.getValueType();
3977   EVT SrcVT = Tmp1.getValueType();
3978   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3979     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3980   bool UseNEON = !InGPR && Subtarget->hasNEON();
3981
3982   if (UseNEON) {
3983     // Use VBSL to copy the sign bit.
3984     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3985     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3986                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3987     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3988     if (VT == MVT::f64)
3989       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3990                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3991                          DAG.getConstant(32, dl, MVT::i32));
3992     else /*if (VT == MVT::f32)*/
3993       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3994     if (SrcVT == MVT::f32) {
3995       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3996       if (VT == MVT::f64)
3997         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3998                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3999                            DAG.getConstant(32, dl, MVT::i32));
4000     } else if (VT == MVT::f32)
4001       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4002                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4003                          DAG.getConstant(32, dl, MVT::i32));
4004     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4005     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4006
4007     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4008                                             dl, MVT::i32);
4009     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4010     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4011                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4012
4013     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4014                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4015                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4016     if (VT == MVT::f32) {
4017       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4018       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4019                         DAG.getConstant(0, dl, MVT::i32));
4020     } else {
4021       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4022     }
4023
4024     return Res;
4025   }
4026
4027   // Bitcast operand 1 to i32.
4028   if (SrcVT == MVT::f64)
4029     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4030                        Tmp1).getValue(1);
4031   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4032
4033   // Or in the signbit with integer operations.
4034   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4035   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4036   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4037   if (VT == MVT::f32) {
4038     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4039                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4040     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4041                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4042   }
4043
4044   // f64: Or the high part with signbit and then combine two parts.
4045   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4046                      Tmp0);
4047   SDValue Lo = Tmp0.getValue(0);
4048   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4049   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4050   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4051 }
4052
4053 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4054   MachineFunction &MF = DAG.getMachineFunction();
4055   MachineFrameInfo *MFI = MF.getFrameInfo();
4056   MFI->setReturnAddressIsTaken(true);
4057
4058   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4059     return SDValue();
4060
4061   EVT VT = Op.getValueType();
4062   SDLoc dl(Op);
4063   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4064   if (Depth) {
4065     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4066     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4067     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4068                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4069                        MachinePointerInfo(), false, false, false, 0);
4070   }
4071
4072   // Return LR, which contains the return address. Mark it an implicit live-in.
4073   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4074   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4075 }
4076
4077 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4078   const ARMBaseRegisterInfo &ARI =
4079     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4080   MachineFunction &MF = DAG.getMachineFunction();
4081   MachineFrameInfo *MFI = MF.getFrameInfo();
4082   MFI->setFrameAddressIsTaken(true);
4083
4084   EVT VT = Op.getValueType();
4085   SDLoc dl(Op);  // FIXME probably not meaningful
4086   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4087   unsigned FrameReg = ARI.getFrameRegister(MF);
4088   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4089   while (Depth--)
4090     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4091                             MachinePointerInfo(),
4092                             false, false, false, 0);
4093   return FrameAddr;
4094 }
4095
4096 // FIXME? Maybe this could be a TableGen attribute on some registers and
4097 // this table could be generated automatically from RegInfo.
4098 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4099                                               SelectionDAG &DAG) const {
4100   unsigned Reg = StringSwitch<unsigned>(RegName)
4101                        .Case("sp", ARM::SP)
4102                        .Default(0);
4103   if (Reg)
4104     return Reg;
4105   report_fatal_error(Twine("Invalid register name \""
4106                               + StringRef(RegName)  + "\"."));
4107 }
4108
4109 // Result is 64 bit value so split into two 32 bit values and return as a
4110 // pair of values.
4111 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4112                                 SelectionDAG &DAG) {
4113   SDLoc DL(N);
4114
4115   // This function is only supposed to be called for i64 type destination.
4116   assert(N->getValueType(0) == MVT::i64
4117           && "ExpandREAD_REGISTER called for non-i64 type result.");
4118
4119   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4120                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4121                              N->getOperand(0),
4122                              N->getOperand(1));
4123
4124   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4125                     Read.getValue(1)));
4126   Results.push_back(Read.getOperand(0));
4127 }
4128
4129 /// ExpandBITCAST - If the target supports VFP, this function is called to
4130 /// expand a bit convert where either the source or destination type is i64 to
4131 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4132 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4133 /// vectors), since the legalizer won't know what to do with that.
4134 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4136   SDLoc dl(N);
4137   SDValue Op = N->getOperand(0);
4138
4139   // This function is only supposed to be called for i64 types, either as the
4140   // source or destination of the bit convert.
4141   EVT SrcVT = Op.getValueType();
4142   EVT DstVT = N->getValueType(0);
4143   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4144          "ExpandBITCAST called for non-i64 type");
4145
4146   // Turn i64->f64 into VMOVDRR.
4147   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4148     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4149                              DAG.getConstant(0, dl, MVT::i32));
4150     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4151                              DAG.getConstant(1, dl, MVT::i32));
4152     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4153                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4154   }
4155
4156   // Turn f64->i64 into VMOVRRD.
4157   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4158     SDValue Cvt;
4159     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4160         SrcVT.getVectorNumElements() > 1)
4161       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4162                         DAG.getVTList(MVT::i32, MVT::i32),
4163                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4164     else
4165       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4166                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4167     // Merge the pieces into a single i64 value.
4168     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4169   }
4170
4171   return SDValue();
4172 }
4173
4174 /// getZeroVector - Returns a vector of specified type with all zero elements.
4175 /// Zero vectors are used to represent vector negation and in those cases
4176 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4177 /// not support i64 elements, so sometimes the zero vectors will need to be
4178 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4179 /// zero vector.
4180 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4181   assert(VT.isVector() && "Expected a vector type");
4182   // The canonical modified immediate encoding of a zero vector is....0!
4183   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4184   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4185   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4186   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4187 }
4188
4189 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4190 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4191 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4192                                                 SelectionDAG &DAG) const {
4193   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4194   EVT VT = Op.getValueType();
4195   unsigned VTBits = VT.getSizeInBits();
4196   SDLoc dl(Op);
4197   SDValue ShOpLo = Op.getOperand(0);
4198   SDValue ShOpHi = Op.getOperand(1);
4199   SDValue ShAmt  = Op.getOperand(2);
4200   SDValue ARMcc;
4201   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4202
4203   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4204
4205   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4206                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4207   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4208   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4209                                    DAG.getConstant(VTBits, dl, MVT::i32));
4210   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4211   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4212   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4213
4214   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4215   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4216                           ISD::SETGE, ARMcc, DAG, dl);
4217   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4218   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4219                            CCR, Cmp);
4220
4221   SDValue Ops[2] = { Lo, Hi };
4222   return DAG.getMergeValues(Ops, dl);
4223 }
4224
4225 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4226 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4227 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4228                                                SelectionDAG &DAG) const {
4229   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4230   EVT VT = Op.getValueType();
4231   unsigned VTBits = VT.getSizeInBits();
4232   SDLoc dl(Op);
4233   SDValue ShOpLo = Op.getOperand(0);
4234   SDValue ShOpHi = Op.getOperand(1);
4235   SDValue ShAmt  = Op.getOperand(2);
4236   SDValue ARMcc;
4237
4238   assert(Op.getOpcode() == ISD::SHL_PARTS);
4239   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4240                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4241   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4242   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4243                                    DAG.getConstant(VTBits, dl, MVT::i32));
4244   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4245   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4246
4247   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4248   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4249   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4250                           ISD::SETGE, ARMcc, DAG, dl);
4251   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4252   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4253                            CCR, Cmp);
4254
4255   SDValue Ops[2] = { Lo, Hi };
4256   return DAG.getMergeValues(Ops, dl);
4257 }
4258
4259 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4260                                             SelectionDAG &DAG) const {
4261   // The rounding mode is in bits 23:22 of the FPSCR.
4262   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4263   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4264   // so that the shift + and get folded into a bitfield extract.
4265   SDLoc dl(Op);
4266   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4267                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4268                                               MVT::i32));
4269   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4270                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4271   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4272                               DAG.getConstant(22, dl, MVT::i32));
4273   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4274                      DAG.getConstant(3, dl, MVT::i32));
4275 }
4276
4277 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4278                          const ARMSubtarget *ST) {
4279   SDLoc dl(N);
4280   EVT VT = N->getValueType(0);
4281   if (VT.isVector()) {
4282     assert(ST->hasNEON());
4283
4284     // Compute the least significant set bit: LSB = X & -X
4285     SDValue X = N->getOperand(0);
4286     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4287     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4288
4289     EVT ElemTy = VT.getVectorElementType();
4290
4291     if (ElemTy == MVT::i8) {
4292       // Compute with: cttz(x) = ctpop(lsb - 1)
4293       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4294                                 DAG.getTargetConstant(1, dl, ElemTy));
4295       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4296       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4297     }
4298
4299     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4300         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4301       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4302       unsigned NumBits = ElemTy.getSizeInBits();
4303       SDValue WidthMinus1 =
4304           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4305                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4306       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4307       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4308     }
4309
4310     // Compute with: cttz(x) = ctpop(lsb - 1)
4311
4312     // Since we can only compute the number of bits in a byte with vcnt.8, we
4313     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4314     // and i64.
4315
4316     // Compute LSB - 1.
4317     SDValue Bits;
4318     if (ElemTy == MVT::i64) {
4319       // Load constant 0xffff'ffff'ffff'ffff to register.
4320       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4321                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4322       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4323     } else {
4324       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4325                                 DAG.getTargetConstant(1, dl, ElemTy));
4326       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4327     }
4328
4329     // Count #bits with vcnt.8.
4330     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4331     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4332     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4333
4334     // Gather the #bits with vpaddl (pairwise add.)
4335     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4336     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4337         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4338         Cnt8);
4339     if (ElemTy == MVT::i16)
4340       return Cnt16;
4341
4342     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4343     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4344         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4345         Cnt16);
4346     if (ElemTy == MVT::i32)
4347       return Cnt32;
4348
4349     assert(ElemTy == MVT::i64);
4350     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4351         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4352         Cnt32);
4353     return Cnt64;
4354   }
4355
4356   if (!ST->hasV6T2Ops())
4357     return SDValue();
4358
4359   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4360   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4361 }
4362
4363 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4364 /// for each 16-bit element from operand, repeated.  The basic idea is to
4365 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4366 ///
4367 /// Trace for v4i16:
4368 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4369 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4370 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4371 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4372 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4373 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4374 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4375 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4376 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4377   EVT VT = N->getValueType(0);
4378   SDLoc DL(N);
4379
4380   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4381   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4382   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4383   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4384   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4385   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4386 }
4387
4388 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4389 /// bit-count for each 16-bit element from the operand.  We need slightly
4390 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4391 /// 64/128-bit registers.
4392 ///
4393 /// Trace for v4i16:
4394 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4395 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4396 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4397 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4398 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4399   EVT VT = N->getValueType(0);
4400   SDLoc DL(N);
4401
4402   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4403   if (VT.is64BitVector()) {
4404     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4405     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4406                        DAG.getIntPtrConstant(0, DL));
4407   } else {
4408     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4409                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4410     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4411   }
4412 }
4413
4414 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4415 /// bit-count for each 32-bit element from the operand.  The idea here is
4416 /// to split the vector into 16-bit elements, leverage the 16-bit count
4417 /// routine, and then combine the results.
4418 ///
4419 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4420 /// input    = [v0    v1    ] (vi: 32-bit elements)
4421 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4422 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4423 /// vrev: N0 = [k1 k0 k3 k2 ]
4424 ///            [k0 k1 k2 k3 ]
4425 ///       N1 =+[k1 k0 k3 k2 ]
4426 ///            [k0 k2 k1 k3 ]
4427 ///       N2 =+[k1 k3 k0 k2 ]
4428 ///            [k0    k2    k1    k3    ]
4429 /// Extended =+[k1    k3    k0    k2    ]
4430 ///            [k0    k2    ]
4431 /// Extracted=+[k1    k3    ]
4432 ///
4433 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4434   EVT VT = N->getValueType(0);
4435   SDLoc DL(N);
4436
4437   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4438
4439   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4440   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4441   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4442   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4443   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4444
4445   if (VT.is64BitVector()) {
4446     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4447     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4448                        DAG.getIntPtrConstant(0, DL));
4449   } else {
4450     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4451                                     DAG.getIntPtrConstant(0, DL));
4452     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4453   }
4454 }
4455
4456 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4457                           const ARMSubtarget *ST) {
4458   EVT VT = N->getValueType(0);
4459
4460   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4461   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4462           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4463          "Unexpected type for custom ctpop lowering");
4464
4465   if (VT.getVectorElementType() == MVT::i32)
4466     return lowerCTPOP32BitElements(N, DAG);
4467   else
4468     return lowerCTPOP16BitElements(N, DAG);
4469 }
4470
4471 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4472                           const ARMSubtarget *ST) {
4473   EVT VT = N->getValueType(0);
4474   SDLoc dl(N);
4475
4476   if (!VT.isVector())
4477     return SDValue();
4478
4479   // Lower vector shifts on NEON to use VSHL.
4480   assert(ST->hasNEON() && "unexpected vector shift");
4481
4482   // Left shifts translate directly to the vshiftu intrinsic.
4483   if (N->getOpcode() == ISD::SHL)
4484     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4485                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4486                                        MVT::i32),
4487                        N->getOperand(0), N->getOperand(1));
4488
4489   assert((N->getOpcode() == ISD::SRA ||
4490           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4491
4492   // NEON uses the same intrinsics for both left and right shifts.  For
4493   // right shifts, the shift amounts are negative, so negate the vector of
4494   // shift amounts.
4495   EVT ShiftVT = N->getOperand(1).getValueType();
4496   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4497                                      getZeroVector(ShiftVT, DAG, dl),
4498                                      N->getOperand(1));
4499   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4500                              Intrinsic::arm_neon_vshifts :
4501                              Intrinsic::arm_neon_vshiftu);
4502   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4503                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4504                      N->getOperand(0), NegatedCount);
4505 }
4506
4507 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4508                                 const ARMSubtarget *ST) {
4509   EVT VT = N->getValueType(0);
4510   SDLoc dl(N);
4511
4512   // We can get here for a node like i32 = ISD::SHL i32, i64
4513   if (VT != MVT::i64)
4514     return SDValue();
4515
4516   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4517          "Unknown shift to lower!");
4518
4519   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4520   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4521       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4522     return SDValue();
4523
4524   // If we are in thumb mode, we don't have RRX.
4525   if (ST->isThumb1Only()) return SDValue();
4526
4527   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4528   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4529                            DAG.getConstant(0, dl, MVT::i32));
4530   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4531                            DAG.getConstant(1, dl, MVT::i32));
4532
4533   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4534   // captures the result into a carry flag.
4535   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4536   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4537
4538   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4539   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4540
4541   // Merge the pieces into a single i64 value.
4542  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4543 }
4544
4545 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4546   SDValue TmpOp0, TmpOp1;
4547   bool Invert = false;
4548   bool Swap = false;
4549   unsigned Opc = 0;
4550
4551   SDValue Op0 = Op.getOperand(0);
4552   SDValue Op1 = Op.getOperand(1);
4553   SDValue CC = Op.getOperand(2);
4554   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4555   EVT VT = Op.getValueType();
4556   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4557   SDLoc dl(Op);
4558
4559   if (CmpVT.getVectorElementType() == MVT::i64)
4560     // 64-bit comparisons are not legal. We've marked SETCC as non-Custom,
4561     // but it's possible that our operands are 64-bit but our result is 32-bit.
4562     // Bail in this case.
4563     return SDValue();
4564
4565   if (Op1.getValueType().isFloatingPoint()) {
4566     switch (SetCCOpcode) {
4567     default: llvm_unreachable("Illegal FP comparison");
4568     case ISD::SETUNE:
4569     case ISD::SETNE:  Invert = true; // Fallthrough
4570     case ISD::SETOEQ:
4571     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4572     case ISD::SETOLT:
4573     case ISD::SETLT: Swap = true; // Fallthrough
4574     case ISD::SETOGT:
4575     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4576     case ISD::SETOLE:
4577     case ISD::SETLE:  Swap = true; // Fallthrough
4578     case ISD::SETOGE:
4579     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4580     case ISD::SETUGE: Swap = true; // Fallthrough
4581     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4582     case ISD::SETUGT: Swap = true; // Fallthrough
4583     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4584     case ISD::SETUEQ: Invert = true; // Fallthrough
4585     case ISD::SETONE:
4586       // Expand this to (OLT | OGT).
4587       TmpOp0 = Op0;
4588       TmpOp1 = Op1;
4589       Opc = ISD::OR;
4590       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4591       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4592       break;
4593     case ISD::SETUO: Invert = true; // Fallthrough
4594     case ISD::SETO:
4595       // Expand this to (OLT | OGE).
4596       TmpOp0 = Op0;
4597       TmpOp1 = Op1;
4598       Opc = ISD::OR;
4599       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4600       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4601       break;
4602     }
4603   } else {
4604     // Integer comparisons.
4605     switch (SetCCOpcode) {
4606     default: llvm_unreachable("Illegal integer comparison");
4607     case ISD::SETNE:  Invert = true;
4608     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4609     case ISD::SETLT:  Swap = true;
4610     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4611     case ISD::SETLE:  Swap = true;
4612     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4613     case ISD::SETULT: Swap = true;
4614     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4615     case ISD::SETULE: Swap = true;
4616     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4617     }
4618
4619     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4620     if (Opc == ARMISD::VCEQ) {
4621
4622       SDValue AndOp;
4623       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4624         AndOp = Op0;
4625       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4626         AndOp = Op1;
4627
4628       // Ignore bitconvert.
4629       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4630         AndOp = AndOp.getOperand(0);
4631
4632       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4633         Opc = ARMISD::VTST;
4634         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4635         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4636         Invert = !Invert;
4637       }
4638     }
4639   }
4640
4641   if (Swap)
4642     std::swap(Op0, Op1);
4643
4644   // If one of the operands is a constant vector zero, attempt to fold the
4645   // comparison to a specialized compare-against-zero form.
4646   SDValue SingleOp;
4647   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4648     SingleOp = Op0;
4649   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4650     if (Opc == ARMISD::VCGE)
4651       Opc = ARMISD::VCLEZ;
4652     else if (Opc == ARMISD::VCGT)
4653       Opc = ARMISD::VCLTZ;
4654     SingleOp = Op1;
4655   }
4656
4657   SDValue Result;
4658   if (SingleOp.getNode()) {
4659     switch (Opc) {
4660     case ARMISD::VCEQ:
4661       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4662     case ARMISD::VCGE:
4663       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4664     case ARMISD::VCLEZ:
4665       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4666     case ARMISD::VCGT:
4667       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4668     case ARMISD::VCLTZ:
4669       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4670     default:
4671       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4672     }
4673   } else {
4674      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4675   }
4676
4677   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4678
4679   if (Invert)
4680     Result = DAG.getNOT(dl, Result, VT);
4681
4682   return Result;
4683 }
4684
4685 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4686 /// valid vector constant for a NEON instruction with a "modified immediate"
4687 /// operand (e.g., VMOV).  If so, return the encoded value.
4688 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4689                                  unsigned SplatBitSize, SelectionDAG &DAG,
4690                                  SDLoc dl, EVT &VT, bool is128Bits,
4691                                  NEONModImmType type) {
4692   unsigned OpCmode, Imm;
4693
4694   // SplatBitSize is set to the smallest size that splats the vector, so a
4695   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4696   // immediate instructions others than VMOV do not support the 8-bit encoding
4697   // of a zero vector, and the default encoding of zero is supposed to be the
4698   // 32-bit version.
4699   if (SplatBits == 0)
4700     SplatBitSize = 32;
4701
4702   switch (SplatBitSize) {
4703   case 8:
4704     if (type != VMOVModImm)
4705       return SDValue();
4706     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4707     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4708     OpCmode = 0xe;
4709     Imm = SplatBits;
4710     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4711     break;
4712
4713   case 16:
4714     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4715     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4716     if ((SplatBits & ~0xff) == 0) {
4717       // Value = 0x00nn: Op=x, Cmode=100x.
4718       OpCmode = 0x8;
4719       Imm = SplatBits;
4720       break;
4721     }
4722     if ((SplatBits & ~0xff00) == 0) {
4723       // Value = 0xnn00: Op=x, Cmode=101x.
4724       OpCmode = 0xa;
4725       Imm = SplatBits >> 8;
4726       break;
4727     }
4728     return SDValue();
4729
4730   case 32:
4731     // NEON's 32-bit VMOV supports splat values where:
4732     // * only one byte is nonzero, or
4733     // * the least significant byte is 0xff and the second byte is nonzero, or
4734     // * the least significant 2 bytes are 0xff and the third is nonzero.
4735     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4736     if ((SplatBits & ~0xff) == 0) {
4737       // Value = 0x000000nn: Op=x, Cmode=000x.
4738       OpCmode = 0;
4739       Imm = SplatBits;
4740       break;
4741     }
4742     if ((SplatBits & ~0xff00) == 0) {
4743       // Value = 0x0000nn00: Op=x, Cmode=001x.
4744       OpCmode = 0x2;
4745       Imm = SplatBits >> 8;
4746       break;
4747     }
4748     if ((SplatBits & ~0xff0000) == 0) {
4749       // Value = 0x00nn0000: Op=x, Cmode=010x.
4750       OpCmode = 0x4;
4751       Imm = SplatBits >> 16;
4752       break;
4753     }
4754     if ((SplatBits & ~0xff000000) == 0) {
4755       // Value = 0xnn000000: Op=x, Cmode=011x.
4756       OpCmode = 0x6;
4757       Imm = SplatBits >> 24;
4758       break;
4759     }
4760
4761     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4762     if (type == OtherModImm) return SDValue();
4763
4764     if ((SplatBits & ~0xffff) == 0 &&
4765         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4766       // Value = 0x0000nnff: Op=x, Cmode=1100.
4767       OpCmode = 0xc;
4768       Imm = SplatBits >> 8;
4769       break;
4770     }
4771
4772     if ((SplatBits & ~0xffffff) == 0 &&
4773         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4774       // Value = 0x00nnffff: Op=x, Cmode=1101.
4775       OpCmode = 0xd;
4776       Imm = SplatBits >> 16;
4777       break;
4778     }
4779
4780     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4781     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4782     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4783     // and fall through here to test for a valid 64-bit splat.  But, then the
4784     // caller would also need to check and handle the change in size.
4785     return SDValue();
4786
4787   case 64: {
4788     if (type != VMOVModImm)
4789       return SDValue();
4790     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4791     uint64_t BitMask = 0xff;
4792     uint64_t Val = 0;
4793     unsigned ImmMask = 1;
4794     Imm = 0;
4795     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4796       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4797         Val |= BitMask;
4798         Imm |= ImmMask;
4799       } else if ((SplatBits & BitMask) != 0) {
4800         return SDValue();
4801       }
4802       BitMask <<= 8;
4803       ImmMask <<= 1;
4804     }
4805
4806     if (DAG.getDataLayout().isBigEndian())
4807       // swap higher and lower 32 bit word
4808       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4809
4810     // Op=1, Cmode=1110.
4811     OpCmode = 0x1e;
4812     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4813     break;
4814   }
4815
4816   default:
4817     llvm_unreachable("unexpected size for isNEONModifiedImm");
4818   }
4819
4820   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4821   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4822 }
4823
4824 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4825                                            const ARMSubtarget *ST) const {
4826   if (!ST->hasVFP3())
4827     return SDValue();
4828
4829   bool IsDouble = Op.getValueType() == MVT::f64;
4830   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4831
4832   // Use the default (constant pool) lowering for double constants when we have
4833   // an SP-only FPU
4834   if (IsDouble && Subtarget->isFPOnlySP())
4835     return SDValue();
4836
4837   // Try splatting with a VMOV.f32...
4838   APFloat FPVal = CFP->getValueAPF();
4839   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4840
4841   if (ImmVal != -1) {
4842     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4843       // We have code in place to select a valid ConstantFP already, no need to
4844       // do any mangling.
4845       return Op;
4846     }
4847
4848     // It's a float and we are trying to use NEON operations where
4849     // possible. Lower it to a splat followed by an extract.
4850     SDLoc DL(Op);
4851     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4852     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4853                                       NewVal);
4854     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4855                        DAG.getConstant(0, DL, MVT::i32));
4856   }
4857
4858   // The rest of our options are NEON only, make sure that's allowed before
4859   // proceeding..
4860   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4861     return SDValue();
4862
4863   EVT VMovVT;
4864   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4865
4866   // It wouldn't really be worth bothering for doubles except for one very
4867   // important value, which does happen to match: 0.0. So make sure we don't do
4868   // anything stupid.
4869   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4870     return SDValue();
4871
4872   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4873   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4874                                      VMovVT, false, VMOVModImm);
4875   if (NewVal != SDValue()) {
4876     SDLoc DL(Op);
4877     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4878                                       NewVal);
4879     if (IsDouble)
4880       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4881
4882     // It's a float: cast and extract a vector element.
4883     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4884                                        VecConstant);
4885     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4886                        DAG.getConstant(0, DL, MVT::i32));
4887   }
4888
4889   // Finally, try a VMVN.i32
4890   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4891                              false, VMVNModImm);
4892   if (NewVal != SDValue()) {
4893     SDLoc DL(Op);
4894     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4895
4896     if (IsDouble)
4897       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4898
4899     // It's a float: cast and extract a vector element.
4900     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4901                                        VecConstant);
4902     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4903                        DAG.getConstant(0, DL, MVT::i32));
4904   }
4905
4906   return SDValue();
4907 }
4908
4909 // check if an VEXT instruction can handle the shuffle mask when the
4910 // vector sources of the shuffle are the same.
4911 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4912   unsigned NumElts = VT.getVectorNumElements();
4913
4914   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4915   if (M[0] < 0)
4916     return false;
4917
4918   Imm = M[0];
4919
4920   // If this is a VEXT shuffle, the immediate value is the index of the first
4921   // element.  The other shuffle indices must be the successive elements after
4922   // the first one.
4923   unsigned ExpectedElt = Imm;
4924   for (unsigned i = 1; i < NumElts; ++i) {
4925     // Increment the expected index.  If it wraps around, just follow it
4926     // back to index zero and keep going.
4927     ++ExpectedElt;
4928     if (ExpectedElt == NumElts)
4929       ExpectedElt = 0;
4930
4931     if (M[i] < 0) continue; // ignore UNDEF indices
4932     if (ExpectedElt != static_cast<unsigned>(M[i]))
4933       return false;
4934   }
4935
4936   return true;
4937 }
4938
4939
4940 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4941                        bool &ReverseVEXT, unsigned &Imm) {
4942   unsigned NumElts = VT.getVectorNumElements();
4943   ReverseVEXT = false;
4944
4945   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4946   if (M[0] < 0)
4947     return false;
4948
4949   Imm = M[0];
4950
4951   // If this is a VEXT shuffle, the immediate value is the index of the first
4952   // element.  The other shuffle indices must be the successive elements after
4953   // the first one.
4954   unsigned ExpectedElt = Imm;
4955   for (unsigned i = 1; i < NumElts; ++i) {
4956     // Increment the expected index.  If it wraps around, it may still be
4957     // a VEXT but the source vectors must be swapped.
4958     ExpectedElt += 1;
4959     if (ExpectedElt == NumElts * 2) {
4960       ExpectedElt = 0;
4961       ReverseVEXT = true;
4962     }
4963
4964     if (M[i] < 0) continue; // ignore UNDEF indices
4965     if (ExpectedElt != static_cast<unsigned>(M[i]))
4966       return false;
4967   }
4968
4969   // Adjust the index value if the source operands will be swapped.
4970   if (ReverseVEXT)
4971     Imm -= NumElts;
4972
4973   return true;
4974 }
4975
4976 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4977 /// instruction with the specified blocksize.  (The order of the elements
4978 /// within each block of the vector is reversed.)
4979 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4980   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4981          "Only possible block sizes for VREV are: 16, 32, 64");
4982
4983   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4984   if (EltSz == 64)
4985     return false;
4986
4987   unsigned NumElts = VT.getVectorNumElements();
4988   unsigned BlockElts = M[0] + 1;
4989   // If the first shuffle index is UNDEF, be optimistic.
4990   if (M[0] < 0)
4991     BlockElts = BlockSize / EltSz;
4992
4993   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4994     return false;
4995
4996   for (unsigned i = 0; i < NumElts; ++i) {
4997     if (M[i] < 0) continue; // ignore UNDEF indices
4998     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4999       return false;
5000   }
5001
5002   return true;
5003 }
5004
5005 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5006   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5007   // range, then 0 is placed into the resulting vector. So pretty much any mask
5008   // of 8 elements can work here.
5009   return VT == MVT::v8i8 && M.size() == 8;
5010 }
5011
5012 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5013 // checking that pairs of elements in the shuffle mask represent the same index
5014 // in each vector, incrementing the expected index by 2 at each step.
5015 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5016 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5017 //  v2={e,f,g,h}
5018 // WhichResult gives the offset for each element in the mask based on which
5019 // of the two results it belongs to.
5020 //
5021 // The transpose can be represented either as:
5022 // result1 = shufflevector v1, v2, result1_shuffle_mask
5023 // result2 = shufflevector v1, v2, result2_shuffle_mask
5024 // where v1/v2 and the shuffle masks have the same number of elements
5025 // (here WhichResult (see below) indicates which result is being checked)
5026 //
5027 // or as:
5028 // results = shufflevector v1, v2, shuffle_mask
5029 // where both results are returned in one vector and the shuffle mask has twice
5030 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5031 // want to check the low half and high half of the shuffle mask as if it were
5032 // the other case
5033 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5034   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5035   if (EltSz == 64)
5036     return false;
5037
5038   unsigned NumElts = VT.getVectorNumElements();
5039   if (M.size() != NumElts && M.size() != NumElts*2)
5040     return false;
5041
5042   // If the mask is twice as long as the input vector then we need to check the
5043   // upper and lower parts of the mask with a matching value for WhichResult
5044   // FIXME: A mask with only even values will be rejected in case the first
5045   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5046   // M[0] is used to determine WhichResult
5047   for (unsigned i = 0; i < M.size(); i += NumElts) {
5048     if (M.size() == NumElts * 2)
5049       WhichResult = i / NumElts;
5050     else
5051       WhichResult = M[i] == 0 ? 0 : 1;
5052     for (unsigned j = 0; j < NumElts; j += 2) {
5053       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5054           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5055         return false;
5056     }
5057   }
5058
5059   if (M.size() == NumElts*2)
5060     WhichResult = 0;
5061
5062   return true;
5063 }
5064
5065 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5066 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5067 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5068 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5069   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5070   if (EltSz == 64)
5071     return false;
5072
5073   unsigned NumElts = VT.getVectorNumElements();
5074   if (M.size() != NumElts && M.size() != NumElts*2)
5075     return false;
5076
5077   for (unsigned i = 0; i < M.size(); i += NumElts) {
5078     if (M.size() == NumElts * 2)
5079       WhichResult = i / NumElts;
5080     else
5081       WhichResult = M[i] == 0 ? 0 : 1;
5082     for (unsigned j = 0; j < NumElts; j += 2) {
5083       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5084           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5085         return false;
5086     }
5087   }
5088
5089   if (M.size() == NumElts*2)
5090     WhichResult = 0;
5091
5092   return true;
5093 }
5094
5095 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5096 // that the mask elements are either all even and in steps of size 2 or all odd
5097 // and in steps of size 2.
5098 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5099 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5100 //  v2={e,f,g,h}
5101 // Requires similar checks to that of isVTRNMask with
5102 // respect the how results are returned.
5103 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5104   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5105   if (EltSz == 64)
5106     return false;
5107
5108   unsigned NumElts = VT.getVectorNumElements();
5109   if (M.size() != NumElts && M.size() != NumElts*2)
5110     return false;
5111
5112   for (unsigned i = 0; i < M.size(); i += NumElts) {
5113     WhichResult = M[i] == 0 ? 0 : 1;
5114     for (unsigned j = 0; j < NumElts; ++j) {
5115       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5116         return false;
5117     }
5118   }
5119
5120   if (M.size() == NumElts*2)
5121     WhichResult = 0;
5122
5123   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5124   if (VT.is64BitVector() && EltSz == 32)
5125     return false;
5126
5127   return true;
5128 }
5129
5130 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5131 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5132 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5133 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5134   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5135   if (EltSz == 64)
5136     return false;
5137
5138   unsigned NumElts = VT.getVectorNumElements();
5139   if (M.size() != NumElts && M.size() != NumElts*2)
5140     return false;
5141
5142   unsigned Half = NumElts / 2;
5143   for (unsigned i = 0; i < M.size(); i += NumElts) {
5144     WhichResult = M[i] == 0 ? 0 : 1;
5145     for (unsigned j = 0; j < NumElts; j += Half) {
5146       unsigned Idx = WhichResult;
5147       for (unsigned k = 0; k < Half; ++k) {
5148         int MIdx = M[i + j + k];
5149         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5150           return false;
5151         Idx += 2;
5152       }
5153     }
5154   }
5155
5156   if (M.size() == NumElts*2)
5157     WhichResult = 0;
5158
5159   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5160   if (VT.is64BitVector() && EltSz == 32)
5161     return false;
5162
5163   return true;
5164 }
5165
5166 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5167 // that pairs of elements of the shufflemask represent the same index in each
5168 // vector incrementing sequentially through the vectors.
5169 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5170 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5171 //  v2={e,f,g,h}
5172 // Requires similar checks to that of isVTRNMask with respect the how results
5173 // are returned.
5174 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5175   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5176   if (EltSz == 64)
5177     return false;
5178
5179   unsigned NumElts = VT.getVectorNumElements();
5180   if (M.size() != NumElts && M.size() != NumElts*2)
5181     return false;
5182
5183   for (unsigned i = 0; i < M.size(); i += NumElts) {
5184     WhichResult = M[i] == 0 ? 0 : 1;
5185     unsigned Idx = WhichResult * NumElts / 2;
5186     for (unsigned j = 0; j < NumElts; j += 2) {
5187       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5188           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5189         return false;
5190       Idx += 1;
5191     }
5192   }
5193
5194   if (M.size() == NumElts*2)
5195     WhichResult = 0;
5196
5197   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5198   if (VT.is64BitVector() && EltSz == 32)
5199     return false;
5200
5201   return true;
5202 }
5203
5204 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5205 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5206 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5207 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5208   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5209   if (EltSz == 64)
5210     return false;
5211
5212   unsigned NumElts = VT.getVectorNumElements();
5213   if (M.size() != NumElts && M.size() != NumElts*2)
5214     return false;
5215
5216   for (unsigned i = 0; i < M.size(); i += NumElts) {
5217     WhichResult = M[i] == 0 ? 0 : 1;
5218     unsigned Idx = WhichResult * NumElts / 2;
5219     for (unsigned j = 0; j < NumElts; j += 2) {
5220       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5221           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5222         return false;
5223       Idx += 1;
5224     }
5225   }
5226
5227   if (M.size() == NumElts*2)
5228     WhichResult = 0;
5229
5230   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5231   if (VT.is64BitVector() && EltSz == 32)
5232     return false;
5233
5234   return true;
5235 }
5236
5237 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5238 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5239 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5240                                            unsigned &WhichResult,
5241                                            bool &isV_UNDEF) {
5242   isV_UNDEF = false;
5243   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5244     return ARMISD::VTRN;
5245   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5246     return ARMISD::VUZP;
5247   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5248     return ARMISD::VZIP;
5249
5250   isV_UNDEF = true;
5251   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5252     return ARMISD::VTRN;
5253   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5254     return ARMISD::VUZP;
5255   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5256     return ARMISD::VZIP;
5257
5258   return 0;
5259 }
5260
5261 /// \return true if this is a reverse operation on an vector.
5262 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5263   unsigned NumElts = VT.getVectorNumElements();
5264   // Make sure the mask has the right size.
5265   if (NumElts != M.size())
5266       return false;
5267
5268   // Look for <15, ..., 3, -1, 1, 0>.
5269   for (unsigned i = 0; i != NumElts; ++i)
5270     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5271       return false;
5272
5273   return true;
5274 }
5275
5276 // If N is an integer constant that can be moved into a register in one
5277 // instruction, return an SDValue of such a constant (will become a MOV
5278 // instruction).  Otherwise return null.
5279 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5280                                      const ARMSubtarget *ST, SDLoc dl) {
5281   uint64_t Val;
5282   if (!isa<ConstantSDNode>(N))
5283     return SDValue();
5284   Val = cast<ConstantSDNode>(N)->getZExtValue();
5285
5286   if (ST->isThumb1Only()) {
5287     if (Val <= 255 || ~Val <= 255)
5288       return DAG.getConstant(Val, dl, MVT::i32);
5289   } else {
5290     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5291       return DAG.getConstant(Val, dl, MVT::i32);
5292   }
5293   return SDValue();
5294 }
5295
5296 // If this is a case we can't handle, return null and let the default
5297 // expansion code take care of it.
5298 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5299                                              const ARMSubtarget *ST) const {
5300   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5301   SDLoc dl(Op);
5302   EVT VT = Op.getValueType();
5303
5304   APInt SplatBits, SplatUndef;
5305   unsigned SplatBitSize;
5306   bool HasAnyUndefs;
5307   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5308     if (SplatBitSize <= 64) {
5309       // Check if an immediate VMOV works.
5310       EVT VmovVT;
5311       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5312                                       SplatUndef.getZExtValue(), SplatBitSize,
5313                                       DAG, dl, VmovVT, VT.is128BitVector(),
5314                                       VMOVModImm);
5315       if (Val.getNode()) {
5316         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5317         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5318       }
5319
5320       // Try an immediate VMVN.
5321       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5322       Val = isNEONModifiedImm(NegatedImm,
5323                                       SplatUndef.getZExtValue(), SplatBitSize,
5324                                       DAG, dl, VmovVT, VT.is128BitVector(),
5325                                       VMVNModImm);
5326       if (Val.getNode()) {
5327         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5328         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5329       }
5330
5331       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5332       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5333         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5334         if (ImmVal != -1) {
5335           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5336           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5337         }
5338       }
5339     }
5340   }
5341
5342   // Scan through the operands to see if only one value is used.
5343   //
5344   // As an optimisation, even if more than one value is used it may be more
5345   // profitable to splat with one value then change some lanes.
5346   //
5347   // Heuristically we decide to do this if the vector has a "dominant" value,
5348   // defined as splatted to more than half of the lanes.
5349   unsigned NumElts = VT.getVectorNumElements();
5350   bool isOnlyLowElement = true;
5351   bool usesOnlyOneValue = true;
5352   bool hasDominantValue = false;
5353   bool isConstant = true;
5354
5355   // Map of the number of times a particular SDValue appears in the
5356   // element list.
5357   DenseMap<SDValue, unsigned> ValueCounts;
5358   SDValue Value;
5359   for (unsigned i = 0; i < NumElts; ++i) {
5360     SDValue V = Op.getOperand(i);
5361     if (V.getOpcode() == ISD::UNDEF)
5362       continue;
5363     if (i > 0)
5364       isOnlyLowElement = false;
5365     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5366       isConstant = false;
5367
5368     ValueCounts.insert(std::make_pair(V, 0));
5369     unsigned &Count = ValueCounts[V];
5370
5371     // Is this value dominant? (takes up more than half of the lanes)
5372     if (++Count > (NumElts / 2)) {
5373       hasDominantValue = true;
5374       Value = V;
5375     }
5376   }
5377   if (ValueCounts.size() != 1)
5378     usesOnlyOneValue = false;
5379   if (!Value.getNode() && ValueCounts.size() > 0)
5380     Value = ValueCounts.begin()->first;
5381
5382   if (ValueCounts.size() == 0)
5383     return DAG.getUNDEF(VT);
5384
5385   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5386   // Keep going if we are hitting this case.
5387   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5388     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5389
5390   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5391
5392   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5393   // i32 and try again.
5394   if (hasDominantValue && EltSize <= 32) {
5395     if (!isConstant) {
5396       SDValue N;
5397
5398       // If we are VDUPing a value that comes directly from a vector, that will
5399       // cause an unnecessary move to and from a GPR, where instead we could
5400       // just use VDUPLANE. We can only do this if the lane being extracted
5401       // is at a constant index, as the VDUP from lane instructions only have
5402       // constant-index forms.
5403       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5404           isa<ConstantSDNode>(Value->getOperand(1))) {
5405         // We need to create a new undef vector to use for the VDUPLANE if the
5406         // size of the vector from which we get the value is different than the
5407         // size of the vector that we need to create. We will insert the element
5408         // such that the register coalescer will remove unnecessary copies.
5409         if (VT != Value->getOperand(0).getValueType()) {
5410           ConstantSDNode *constIndex;
5411           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5412           assert(constIndex && "The index is not a constant!");
5413           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5414                              VT.getVectorNumElements();
5415           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5416                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5417                         Value, DAG.getConstant(index, dl, MVT::i32)),
5418                            DAG.getConstant(index, dl, MVT::i32));
5419         } else
5420           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5421                         Value->getOperand(0), Value->getOperand(1));
5422       } else
5423         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5424
5425       if (!usesOnlyOneValue) {
5426         // The dominant value was splatted as 'N', but we now have to insert
5427         // all differing elements.
5428         for (unsigned I = 0; I < NumElts; ++I) {
5429           if (Op.getOperand(I) == Value)
5430             continue;
5431           SmallVector<SDValue, 3> Ops;
5432           Ops.push_back(N);
5433           Ops.push_back(Op.getOperand(I));
5434           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5435           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5436         }
5437       }
5438       return N;
5439     }
5440     if (VT.getVectorElementType().isFloatingPoint()) {
5441       SmallVector<SDValue, 8> Ops;
5442       for (unsigned i = 0; i < NumElts; ++i)
5443         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5444                                   Op.getOperand(i)));
5445       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5446       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5447       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5448       if (Val.getNode())
5449         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5450     }
5451     if (usesOnlyOneValue) {
5452       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5453       if (isConstant && Val.getNode())
5454         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5455     }
5456   }
5457
5458   // If all elements are constants and the case above didn't get hit, fall back
5459   // to the default expansion, which will generate a load from the constant
5460   // pool.
5461   if (isConstant)
5462     return SDValue();
5463
5464   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5465   if (NumElts >= 4) {
5466     SDValue shuffle = ReconstructShuffle(Op, DAG);
5467     if (shuffle != SDValue())
5468       return shuffle;
5469   }
5470
5471   // Vectors with 32- or 64-bit elements can be built by directly assigning
5472   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5473   // will be legalized.
5474   if (EltSize >= 32) {
5475     // Do the expansion with floating-point types, since that is what the VFP
5476     // registers are defined to use, and since i64 is not legal.
5477     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5478     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5479     SmallVector<SDValue, 8> Ops;
5480     for (unsigned i = 0; i < NumElts; ++i)
5481       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5482     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5483     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5484   }
5485
5486   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5487   // know the default expansion would otherwise fall back on something even
5488   // worse. For a vector with one or two non-undef values, that's
5489   // scalar_to_vector for the elements followed by a shuffle (provided the
5490   // shuffle is valid for the target) and materialization element by element
5491   // on the stack followed by a load for everything else.
5492   if (!isConstant && !usesOnlyOneValue) {
5493     SDValue Vec = DAG.getUNDEF(VT);
5494     for (unsigned i = 0 ; i < NumElts; ++i) {
5495       SDValue V = Op.getOperand(i);
5496       if (V.getOpcode() == ISD::UNDEF)
5497         continue;
5498       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5499       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5500     }
5501     return Vec;
5502   }
5503
5504   return SDValue();
5505 }
5506
5507 // Gather data to see if the operation can be modelled as a
5508 // shuffle in combination with VEXTs.
5509 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5510                                               SelectionDAG &DAG) const {
5511   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5512   SDLoc dl(Op);
5513   EVT VT = Op.getValueType();
5514   unsigned NumElts = VT.getVectorNumElements();
5515
5516   struct ShuffleSourceInfo {
5517     SDValue Vec;
5518     unsigned MinElt;
5519     unsigned MaxElt;
5520
5521     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5522     // be compatible with the shuffle we intend to construct. As a result
5523     // ShuffleVec will be some sliding window into the original Vec.
5524     SDValue ShuffleVec;
5525
5526     // Code should guarantee that element i in Vec starts at element "WindowBase
5527     // + i * WindowScale in ShuffleVec".
5528     int WindowBase;
5529     int WindowScale;
5530
5531     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5532     ShuffleSourceInfo(SDValue Vec)
5533         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5534           WindowScale(1) {}
5535   };
5536
5537   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5538   // node.
5539   SmallVector<ShuffleSourceInfo, 2> Sources;
5540   for (unsigned i = 0; i < NumElts; ++i) {
5541     SDValue V = Op.getOperand(i);
5542     if (V.getOpcode() == ISD::UNDEF)
5543       continue;
5544     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5545       // A shuffle can only come from building a vector from various
5546       // elements of other vectors.
5547       return SDValue();
5548     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
5549       // Furthermore, shuffles require a constant mask, whereas extractelts
5550       // accept variable indices.
5551       return SDValue();
5552     }
5553
5554     // Add this element source to the list if it's not already there.
5555     SDValue SourceVec = V.getOperand(0);
5556     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5557     if (Source == Sources.end())
5558       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5559
5560     // Update the minimum and maximum lane number seen.
5561     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5562     Source->MinElt = std::min(Source->MinElt, EltNo);
5563     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5564   }
5565
5566   // Currently only do something sane when at most two source vectors
5567   // are involved.
5568   if (Sources.size() > 2)
5569     return SDValue();
5570
5571   // Find out the smallest element size among result and two sources, and use
5572   // it as element size to build the shuffle_vector.
5573   EVT SmallestEltTy = VT.getVectorElementType();
5574   for (auto &Source : Sources) {
5575     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5576     if (SrcEltTy.bitsLT(SmallestEltTy))
5577       SmallestEltTy = SrcEltTy;
5578   }
5579   unsigned ResMultiplier =
5580       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5581   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5582   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5583
5584   // If the source vector is too wide or too narrow, we may nevertheless be able
5585   // to construct a compatible shuffle either by concatenating it with UNDEF or
5586   // extracting a suitable range of elements.
5587   for (auto &Src : Sources) {
5588     EVT SrcVT = Src.ShuffleVec.getValueType();
5589
5590     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5591       continue;
5592
5593     // This stage of the search produces a source with the same element type as
5594     // the original, but with a total width matching the BUILD_VECTOR output.
5595     EVT EltVT = SrcVT.getVectorElementType();
5596     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5597     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5598
5599     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5600       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5601         return SDValue();
5602       // We can pad out the smaller vector for free, so if it's part of a
5603       // shuffle...
5604       Src.ShuffleVec =
5605           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5606                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5607       continue;
5608     }
5609
5610     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5611       return SDValue();
5612
5613     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5614       // Span too large for a VEXT to cope
5615       return SDValue();
5616     }
5617
5618     if (Src.MinElt >= NumSrcElts) {
5619       // The extraction can just take the second half
5620       Src.ShuffleVec =
5621           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5622                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5623       Src.WindowBase = -NumSrcElts;
5624     } else if (Src.MaxElt < NumSrcElts) {
5625       // The extraction can just take the first half
5626       Src.ShuffleVec =
5627           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5628                       DAG.getConstant(0, dl, MVT::i32));
5629     } else {
5630       // An actual VEXT is needed
5631       SDValue VEXTSrc1 =
5632           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5633                       DAG.getConstant(0, dl, MVT::i32));
5634       SDValue VEXTSrc2 =
5635           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5636                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5637
5638       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5639                                    VEXTSrc2,
5640                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
5641       Src.WindowBase = -Src.MinElt;
5642     }
5643   }
5644
5645   // Another possible incompatibility occurs from the vector element types. We
5646   // can fix this by bitcasting the source vectors to the same type we intend
5647   // for the shuffle.
5648   for (auto &Src : Sources) {
5649     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5650     if (SrcEltTy == SmallestEltTy)
5651       continue;
5652     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5653     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5654     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5655     Src.WindowBase *= Src.WindowScale;
5656   }
5657
5658   // Final sanity check before we try to actually produce a shuffle.
5659   DEBUG(
5660     for (auto Src : Sources)
5661       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5662   );
5663
5664   // The stars all align, our next step is to produce the mask for the shuffle.
5665   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5666   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5667   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5668     SDValue Entry = Op.getOperand(i);
5669     if (Entry.getOpcode() == ISD::UNDEF)
5670       continue;
5671
5672     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5673     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5674
5675     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5676     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5677     // segment.
5678     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5679     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5680                                VT.getVectorElementType().getSizeInBits());
5681     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5682
5683     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5684     // starting at the appropriate offset.
5685     int *LaneMask = &Mask[i * ResMultiplier];
5686
5687     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5688     ExtractBase += NumElts * (Src - Sources.begin());
5689     for (int j = 0; j < LanesDefined; ++j)
5690       LaneMask[j] = ExtractBase + j;
5691   }
5692
5693   // Final check before we try to produce nonsense...
5694   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5695     return SDValue();
5696
5697   // We can't handle more than two sources. This should have already
5698   // been checked before this point.
5699   assert(Sources.size() <= 2 && "Too many sources!");
5700
5701   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5702   for (unsigned i = 0; i < Sources.size(); ++i)
5703     ShuffleOps[i] = Sources[i].ShuffleVec;
5704
5705   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5706                                          ShuffleOps[1], &Mask[0]);
5707   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5708 }
5709
5710 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5711 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5712 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5713 /// are assumed to be legal.
5714 bool
5715 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5716                                       EVT VT) const {
5717   if (VT.getVectorNumElements() == 4 &&
5718       (VT.is128BitVector() || VT.is64BitVector())) {
5719     unsigned PFIndexes[4];
5720     for (unsigned i = 0; i != 4; ++i) {
5721       if (M[i] < 0)
5722         PFIndexes[i] = 8;
5723       else
5724         PFIndexes[i] = M[i];
5725     }
5726
5727     // Compute the index in the perfect shuffle table.
5728     unsigned PFTableIndex =
5729       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5730     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5731     unsigned Cost = (PFEntry >> 30);
5732
5733     if (Cost <= 4)
5734       return true;
5735   }
5736
5737   bool ReverseVEXT, isV_UNDEF;
5738   unsigned Imm, WhichResult;
5739
5740   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5741   return (EltSize >= 32 ||
5742           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5743           isVREVMask(M, VT, 64) ||
5744           isVREVMask(M, VT, 32) ||
5745           isVREVMask(M, VT, 16) ||
5746           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5747           isVTBLMask(M, VT) ||
5748           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5749           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5750 }
5751
5752 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5753 /// the specified operations to build the shuffle.
5754 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5755                                       SDValue RHS, SelectionDAG &DAG,
5756                                       SDLoc dl) {
5757   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5758   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5759   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5760
5761   enum {
5762     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5763     OP_VREV,
5764     OP_VDUP0,
5765     OP_VDUP1,
5766     OP_VDUP2,
5767     OP_VDUP3,
5768     OP_VEXT1,
5769     OP_VEXT2,
5770     OP_VEXT3,
5771     OP_VUZPL, // VUZP, left result
5772     OP_VUZPR, // VUZP, right result
5773     OP_VZIPL, // VZIP, left result
5774     OP_VZIPR, // VZIP, right result
5775     OP_VTRNL, // VTRN, left result
5776     OP_VTRNR  // VTRN, right result
5777   };
5778
5779   if (OpNum == OP_COPY) {
5780     if (LHSID == (1*9+2)*9+3) return LHS;
5781     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5782     return RHS;
5783   }
5784
5785   SDValue OpLHS, OpRHS;
5786   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5787   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5788   EVT VT = OpLHS.getValueType();
5789
5790   switch (OpNum) {
5791   default: llvm_unreachable("Unknown shuffle opcode!");
5792   case OP_VREV:
5793     // VREV divides the vector in half and swaps within the half.
5794     if (VT.getVectorElementType() == MVT::i32 ||
5795         VT.getVectorElementType() == MVT::f32)
5796       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5797     // vrev <4 x i16> -> VREV32
5798     if (VT.getVectorElementType() == MVT::i16)
5799       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5800     // vrev <4 x i8> -> VREV16
5801     assert(VT.getVectorElementType() == MVT::i8);
5802     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5803   case OP_VDUP0:
5804   case OP_VDUP1:
5805   case OP_VDUP2:
5806   case OP_VDUP3:
5807     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5808                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5809   case OP_VEXT1:
5810   case OP_VEXT2:
5811   case OP_VEXT3:
5812     return DAG.getNode(ARMISD::VEXT, dl, VT,
5813                        OpLHS, OpRHS,
5814                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5815   case OP_VUZPL:
5816   case OP_VUZPR:
5817     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5818                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5819   case OP_VZIPL:
5820   case OP_VZIPR:
5821     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5822                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5823   case OP_VTRNL:
5824   case OP_VTRNR:
5825     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5826                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5827   }
5828 }
5829
5830 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5831                                        ArrayRef<int> ShuffleMask,
5832                                        SelectionDAG &DAG) {
5833   // Check to see if we can use the VTBL instruction.
5834   SDValue V1 = Op.getOperand(0);
5835   SDValue V2 = Op.getOperand(1);
5836   SDLoc DL(Op);
5837
5838   SmallVector<SDValue, 8> VTBLMask;
5839   for (ArrayRef<int>::iterator
5840          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5841     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5842
5843   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5844     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5845                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5846
5847   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5848                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5849 }
5850
5851 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5852                                                       SelectionDAG &DAG) {
5853   SDLoc DL(Op);
5854   SDValue OpLHS = Op.getOperand(0);
5855   EVT VT = OpLHS.getValueType();
5856
5857   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5858          "Expect an v8i16/v16i8 type");
5859   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5860   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5861   // extract the first 8 bytes into the top double word and the last 8 bytes
5862   // into the bottom double word. The v8i16 case is similar.
5863   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5864   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5865                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5866 }
5867
5868 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5869   SDValue V1 = Op.getOperand(0);
5870   SDValue V2 = Op.getOperand(1);
5871   SDLoc dl(Op);
5872   EVT VT = Op.getValueType();
5873   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5874
5875   // Convert shuffles that are directly supported on NEON to target-specific
5876   // DAG nodes, instead of keeping them as shuffles and matching them again
5877   // during code selection.  This is more efficient and avoids the possibility
5878   // of inconsistencies between legalization and selection.
5879   // FIXME: floating-point vectors should be canonicalized to integer vectors
5880   // of the same time so that they get CSEd properly.
5881   ArrayRef<int> ShuffleMask = SVN->getMask();
5882
5883   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5884   if (EltSize <= 32) {
5885     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5886       int Lane = SVN->getSplatIndex();
5887       // If this is undef splat, generate it via "just" vdup, if possible.
5888       if (Lane == -1) Lane = 0;
5889
5890       // Test if V1 is a SCALAR_TO_VECTOR.
5891       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5892         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5893       }
5894       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5895       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5896       // reaches it).
5897       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5898           !isa<ConstantSDNode>(V1.getOperand(0))) {
5899         bool IsScalarToVector = true;
5900         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5901           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5902             IsScalarToVector = false;
5903             break;
5904           }
5905         if (IsScalarToVector)
5906           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5907       }
5908       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5909                          DAG.getConstant(Lane, dl, MVT::i32));
5910     }
5911
5912     bool ReverseVEXT;
5913     unsigned Imm;
5914     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5915       if (ReverseVEXT)
5916         std::swap(V1, V2);
5917       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5918                          DAG.getConstant(Imm, dl, MVT::i32));
5919     }
5920
5921     if (isVREVMask(ShuffleMask, VT, 64))
5922       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5923     if (isVREVMask(ShuffleMask, VT, 32))
5924       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5925     if (isVREVMask(ShuffleMask, VT, 16))
5926       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5927
5928     if (V2->getOpcode() == ISD::UNDEF &&
5929         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5930       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5931                          DAG.getConstant(Imm, dl, MVT::i32));
5932     }
5933
5934     // Check for Neon shuffles that modify both input vectors in place.
5935     // If both results are used, i.e., if there are two shuffles with the same
5936     // source operands and with masks corresponding to both results of one of
5937     // these operations, DAG memoization will ensure that a single node is
5938     // used for both shuffles.
5939     unsigned WhichResult;
5940     bool isV_UNDEF;
5941     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5942             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5943       if (isV_UNDEF)
5944         V2 = V1;
5945       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5946           .getValue(WhichResult);
5947     }
5948
5949     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5950     // shuffles that produce a result larger than their operands with:
5951     //   shuffle(concat(v1, undef), concat(v2, undef))
5952     // ->
5953     //   shuffle(concat(v1, v2), undef)
5954     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5955     //
5956     // This is useful in the general case, but there are special cases where
5957     // native shuffles produce larger results: the two-result ops.
5958     //
5959     // Look through the concat when lowering them:
5960     //   shuffle(concat(v1, v2), undef)
5961     // ->
5962     //   concat(VZIP(v1, v2):0, :1)
5963     //
5964     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5965         V2->getOpcode() == ISD::UNDEF) {
5966       SDValue SubV1 = V1->getOperand(0);
5967       SDValue SubV2 = V1->getOperand(1);
5968       EVT SubVT = SubV1.getValueType();
5969
5970       // We expect these to have been canonicalized to -1.
5971       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5972         return i < (int)VT.getVectorNumElements();
5973       }) && "Unexpected shuffle index into UNDEF operand!");
5974
5975       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5976               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5977         if (isV_UNDEF)
5978           SubV2 = SubV1;
5979         assert((WhichResult == 0) &&
5980                "In-place shuffle of concat can only have one result!");
5981         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5982                                   SubV1, SubV2);
5983         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5984                            Res.getValue(1));
5985       }
5986     }
5987   }
5988
5989   // If the shuffle is not directly supported and it has 4 elements, use
5990   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5991   unsigned NumElts = VT.getVectorNumElements();
5992   if (NumElts == 4) {
5993     unsigned PFIndexes[4];
5994     for (unsigned i = 0; i != 4; ++i) {
5995       if (ShuffleMask[i] < 0)
5996         PFIndexes[i] = 8;
5997       else
5998         PFIndexes[i] = ShuffleMask[i];
5999     }
6000
6001     // Compute the index in the perfect shuffle table.
6002     unsigned PFTableIndex =
6003       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6004     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6005     unsigned Cost = (PFEntry >> 30);
6006
6007     if (Cost <= 4)
6008       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6009   }
6010
6011   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6012   if (EltSize >= 32) {
6013     // Do the expansion with floating-point types, since that is what the VFP
6014     // registers are defined to use, and since i64 is not legal.
6015     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6016     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6017     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6018     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6019     SmallVector<SDValue, 8> Ops;
6020     for (unsigned i = 0; i < NumElts; ++i) {
6021       if (ShuffleMask[i] < 0)
6022         Ops.push_back(DAG.getUNDEF(EltVT));
6023       else
6024         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6025                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6026                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6027                                                   dl, MVT::i32)));
6028     }
6029     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6030     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6031   }
6032
6033   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6034     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6035
6036   if (VT == MVT::v8i8) {
6037     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6038     if (NewOp.getNode())
6039       return NewOp;
6040   }
6041
6042   return SDValue();
6043 }
6044
6045 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6046   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6047   SDValue Lane = Op.getOperand(2);
6048   if (!isa<ConstantSDNode>(Lane))
6049     return SDValue();
6050
6051   return Op;
6052 }
6053
6054 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6055   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6056   SDValue Lane = Op.getOperand(1);
6057   if (!isa<ConstantSDNode>(Lane))
6058     return SDValue();
6059
6060   SDValue Vec = Op.getOperand(0);
6061   if (Op.getValueType() == MVT::i32 &&
6062       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6063     SDLoc dl(Op);
6064     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6065   }
6066
6067   return Op;
6068 }
6069
6070 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6071   // The only time a CONCAT_VECTORS operation can have legal types is when
6072   // two 64-bit vectors are concatenated to a 128-bit vector.
6073   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6074          "unexpected CONCAT_VECTORS");
6075   SDLoc dl(Op);
6076   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6077   SDValue Op0 = Op.getOperand(0);
6078   SDValue Op1 = Op.getOperand(1);
6079   if (Op0.getOpcode() != ISD::UNDEF)
6080     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6081                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6082                       DAG.getIntPtrConstant(0, dl));
6083   if (Op1.getOpcode() != ISD::UNDEF)
6084     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6085                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6086                       DAG.getIntPtrConstant(1, dl));
6087   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6088 }
6089
6090 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6091 /// element has been zero/sign-extended, depending on the isSigned parameter,
6092 /// from an integer type half its size.
6093 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6094                                    bool isSigned) {
6095   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6096   EVT VT = N->getValueType(0);
6097   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6098     SDNode *BVN = N->getOperand(0).getNode();
6099     if (BVN->getValueType(0) != MVT::v4i32 ||
6100         BVN->getOpcode() != ISD::BUILD_VECTOR)
6101       return false;
6102     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6103     unsigned HiElt = 1 - LoElt;
6104     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6105     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6106     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6107     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6108     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6109       return false;
6110     if (isSigned) {
6111       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6112           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6113         return true;
6114     } else {
6115       if (Hi0->isNullValue() && Hi1->isNullValue())
6116         return true;
6117     }
6118     return false;
6119   }
6120
6121   if (N->getOpcode() != ISD::BUILD_VECTOR)
6122     return false;
6123
6124   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6125     SDNode *Elt = N->getOperand(i).getNode();
6126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6127       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6128       unsigned HalfSize = EltSize / 2;
6129       if (isSigned) {
6130         if (!isIntN(HalfSize, C->getSExtValue()))
6131           return false;
6132       } else {
6133         if (!isUIntN(HalfSize, C->getZExtValue()))
6134           return false;
6135       }
6136       continue;
6137     }
6138     return false;
6139   }
6140
6141   return true;
6142 }
6143
6144 /// isSignExtended - Check if a node is a vector value that is sign-extended
6145 /// or a constant BUILD_VECTOR with sign-extended elements.
6146 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6147   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6148     return true;
6149   if (isExtendedBUILD_VECTOR(N, DAG, true))
6150     return true;
6151   return false;
6152 }
6153
6154 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6155 /// or a constant BUILD_VECTOR with zero-extended elements.
6156 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6157   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6158     return true;
6159   if (isExtendedBUILD_VECTOR(N, DAG, false))
6160     return true;
6161   return false;
6162 }
6163
6164 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6165   if (OrigVT.getSizeInBits() >= 64)
6166     return OrigVT;
6167
6168   assert(OrigVT.isSimple() && "Expecting a simple value type");
6169
6170   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6171   switch (OrigSimpleTy) {
6172   default: llvm_unreachable("Unexpected Vector Type");
6173   case MVT::v2i8:
6174   case MVT::v2i16:
6175      return MVT::v2i32;
6176   case MVT::v4i8:
6177     return  MVT::v4i16;
6178   }
6179 }
6180
6181 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6182 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6183 /// We insert the required extension here to get the vector to fill a D register.
6184 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6185                                             const EVT &OrigTy,
6186                                             const EVT &ExtTy,
6187                                             unsigned ExtOpcode) {
6188   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6189   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6190   // 64-bits we need to insert a new extension so that it will be 64-bits.
6191   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6192   if (OrigTy.getSizeInBits() >= 64)
6193     return N;
6194
6195   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6196   EVT NewVT = getExtensionTo64Bits(OrigTy);
6197
6198   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6199 }
6200
6201 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6202 /// does not do any sign/zero extension. If the original vector is less
6203 /// than 64 bits, an appropriate extension will be added after the load to
6204 /// reach a total size of 64 bits. We have to add the extension separately
6205 /// because ARM does not have a sign/zero extending load for vectors.
6206 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6207   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6208
6209   // The load already has the right type.
6210   if (ExtendedTy == LD->getMemoryVT())
6211     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6212                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6213                 LD->isNonTemporal(), LD->isInvariant(),
6214                 LD->getAlignment());
6215
6216   // We need to create a zextload/sextload. We cannot just create a load
6217   // followed by a zext/zext node because LowerMUL is also run during normal
6218   // operation legalization where we can't create illegal types.
6219   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6220                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6221                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6222                         LD->isNonTemporal(), LD->getAlignment());
6223 }
6224
6225 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6226 /// extending load, or BUILD_VECTOR with extended elements, return the
6227 /// unextended value. The unextended vector should be 64 bits so that it can
6228 /// be used as an operand to a VMULL instruction. If the original vector size
6229 /// before extension is less than 64 bits we add a an extension to resize
6230 /// the vector to 64 bits.
6231 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6232   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6233     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6234                                         N->getOperand(0)->getValueType(0),
6235                                         N->getValueType(0),
6236                                         N->getOpcode());
6237
6238   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6239     return SkipLoadExtensionForVMULL(LD, DAG);
6240
6241   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6242   // have been legalized as a BITCAST from v4i32.
6243   if (N->getOpcode() == ISD::BITCAST) {
6244     SDNode *BVN = N->getOperand(0).getNode();
6245     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6246            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6247     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6248     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6249                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6250   }
6251   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6252   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6253   EVT VT = N->getValueType(0);
6254   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6255   unsigned NumElts = VT.getVectorNumElements();
6256   MVT TruncVT = MVT::getIntegerVT(EltSize);
6257   SmallVector<SDValue, 8> Ops;
6258   SDLoc dl(N);
6259   for (unsigned i = 0; i != NumElts; ++i) {
6260     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6261     const APInt &CInt = C->getAPIntValue();
6262     // Element types smaller than 32 bits are not legal, so use i32 elements.
6263     // The values are implicitly truncated so sext vs. zext doesn't matter.
6264     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6265   }
6266   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6267                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6268 }
6269
6270 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6271   unsigned Opcode = N->getOpcode();
6272   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6273     SDNode *N0 = N->getOperand(0).getNode();
6274     SDNode *N1 = N->getOperand(1).getNode();
6275     return N0->hasOneUse() && N1->hasOneUse() &&
6276       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6277   }
6278   return false;
6279 }
6280
6281 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6282   unsigned Opcode = N->getOpcode();
6283   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6284     SDNode *N0 = N->getOperand(0).getNode();
6285     SDNode *N1 = N->getOperand(1).getNode();
6286     return N0->hasOneUse() && N1->hasOneUse() &&
6287       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6288   }
6289   return false;
6290 }
6291
6292 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6293   // Multiplications are only custom-lowered for 128-bit vectors so that
6294   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6295   EVT VT = Op.getValueType();
6296   assert(VT.is128BitVector() && VT.isInteger() &&
6297          "unexpected type for custom-lowering ISD::MUL");
6298   SDNode *N0 = Op.getOperand(0).getNode();
6299   SDNode *N1 = Op.getOperand(1).getNode();
6300   unsigned NewOpc = 0;
6301   bool isMLA = false;
6302   bool isN0SExt = isSignExtended(N0, DAG);
6303   bool isN1SExt = isSignExtended(N1, DAG);
6304   if (isN0SExt && isN1SExt)
6305     NewOpc = ARMISD::VMULLs;
6306   else {
6307     bool isN0ZExt = isZeroExtended(N0, DAG);
6308     bool isN1ZExt = isZeroExtended(N1, DAG);
6309     if (isN0ZExt && isN1ZExt)
6310       NewOpc = ARMISD::VMULLu;
6311     else if (isN1SExt || isN1ZExt) {
6312       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6313       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6314       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6315         NewOpc = ARMISD::VMULLs;
6316         isMLA = true;
6317       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6318         NewOpc = ARMISD::VMULLu;
6319         isMLA = true;
6320       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6321         std::swap(N0, N1);
6322         NewOpc = ARMISD::VMULLu;
6323         isMLA = true;
6324       }
6325     }
6326
6327     if (!NewOpc) {
6328       if (VT == MVT::v2i64)
6329         // Fall through to expand this.  It is not legal.
6330         return SDValue();
6331       else
6332         // Other vector multiplications are legal.
6333         return Op;
6334     }
6335   }
6336
6337   // Legalize to a VMULL instruction.
6338   SDLoc DL(Op);
6339   SDValue Op0;
6340   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6341   if (!isMLA) {
6342     Op0 = SkipExtensionForVMULL(N0, DAG);
6343     assert(Op0.getValueType().is64BitVector() &&
6344            Op1.getValueType().is64BitVector() &&
6345            "unexpected types for extended operands to VMULL");
6346     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6347   }
6348
6349   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6350   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6351   //   vmull q0, d4, d6
6352   //   vmlal q0, d5, d6
6353   // is faster than
6354   //   vaddl q0, d4, d5
6355   //   vmovl q1, d6
6356   //   vmul  q0, q0, q1
6357   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6358   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6359   EVT Op1VT = Op1.getValueType();
6360   return DAG.getNode(N0->getOpcode(), DL, VT,
6361                      DAG.getNode(NewOpc, DL, VT,
6362                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6363                      DAG.getNode(NewOpc, DL, VT,
6364                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6365 }
6366
6367 static SDValue
6368 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6369   // TODO: Should this propagate fast-math-flags?
6370
6371   // Convert to float
6372   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6373   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6374   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6375   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6376   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6377   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6378   // Get reciprocal estimate.
6379   // float4 recip = vrecpeq_f32(yf);
6380   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6381                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6382                    Y);
6383   // Because char has a smaller range than uchar, we can actually get away
6384   // without any newton steps.  This requires that we use a weird bias
6385   // of 0xb000, however (again, this has been exhaustively tested).
6386   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6387   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6388   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6389   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6390   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6391   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6392   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6393   // Convert back to short.
6394   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6395   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6396   return X;
6397 }
6398
6399 static SDValue
6400 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6401   // TODO: Should this propagate fast-math-flags?
6402
6403   SDValue N2;
6404   // Convert to float.
6405   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6406   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6407   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6408   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6409   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6410   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6411
6412   // Use reciprocal estimate and one refinement step.
6413   // float4 recip = vrecpeq_f32(yf);
6414   // recip *= vrecpsq_f32(yf, recip);
6415   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6416                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6417                    N1);
6418   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6419                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6420                    N1, N2);
6421   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6422   // Because short has a smaller range than ushort, we can actually get away
6423   // with only a single newton step.  This requires that we use a weird bias
6424   // of 89, however (again, this has been exhaustively tested).
6425   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6426   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6427   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6428   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6429   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6430   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6431   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6432   // Convert back to integer and return.
6433   // return vmovn_s32(vcvt_s32_f32(result));
6434   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6435   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6436   return N0;
6437 }
6438
6439 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6440   EVT VT = Op.getValueType();
6441   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6442          "unexpected type for custom-lowering ISD::SDIV");
6443
6444   SDLoc dl(Op);
6445   SDValue N0 = Op.getOperand(0);
6446   SDValue N1 = Op.getOperand(1);
6447   SDValue N2, N3;
6448
6449   if (VT == MVT::v8i8) {
6450     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6451     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6452
6453     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6454                      DAG.getIntPtrConstant(4, dl));
6455     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6456                      DAG.getIntPtrConstant(4, dl));
6457     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6458                      DAG.getIntPtrConstant(0, dl));
6459     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6460                      DAG.getIntPtrConstant(0, dl));
6461
6462     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6463     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6464
6465     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6466     N0 = LowerCONCAT_VECTORS(N0, DAG);
6467
6468     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6469     return N0;
6470   }
6471   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6472 }
6473
6474 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6475   // TODO: Should this propagate fast-math-flags?
6476   EVT VT = Op.getValueType();
6477   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6478          "unexpected type for custom-lowering ISD::UDIV");
6479
6480   SDLoc dl(Op);
6481   SDValue N0 = Op.getOperand(0);
6482   SDValue N1 = Op.getOperand(1);
6483   SDValue N2, N3;
6484
6485   if (VT == MVT::v8i8) {
6486     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6487     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6488
6489     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6490                      DAG.getIntPtrConstant(4, dl));
6491     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6492                      DAG.getIntPtrConstant(4, dl));
6493     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6494                      DAG.getIntPtrConstant(0, dl));
6495     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6496                      DAG.getIntPtrConstant(0, dl));
6497
6498     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6499     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6500
6501     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6502     N0 = LowerCONCAT_VECTORS(N0, DAG);
6503
6504     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6505                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6506                                      MVT::i32),
6507                      N0);
6508     return N0;
6509   }
6510
6511   // v4i16 sdiv ... Convert to float.
6512   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6513   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6514   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6515   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6516   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6517   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6518
6519   // Use reciprocal estimate and two refinement steps.
6520   // float4 recip = vrecpeq_f32(yf);
6521   // recip *= vrecpsq_f32(yf, recip);
6522   // recip *= vrecpsq_f32(yf, recip);
6523   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6524                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6525                    BN1);
6526   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6527                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6528                    BN1, N2);
6529   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6530   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6531                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6532                    BN1, N2);
6533   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6534   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6535   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6536   // and that it will never cause us to return an answer too large).
6537   // float4 result = as_float4(as_int4(xf*recip) + 2);
6538   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6539   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6540   N1 = DAG.getConstant(2, dl, MVT::i32);
6541   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6542   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6543   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6544   // Convert back to integer and return.
6545   // return vmovn_u32(vcvt_s32_f32(result));
6546   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6547   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6548   return N0;
6549 }
6550
6551 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6552   EVT VT = Op.getNode()->getValueType(0);
6553   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6554
6555   unsigned Opc;
6556   bool ExtraOp = false;
6557   switch (Op.getOpcode()) {
6558   default: llvm_unreachable("Invalid code");
6559   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6560   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6561   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6562   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6563   }
6564
6565   if (!ExtraOp)
6566     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6567                        Op.getOperand(1));
6568   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6569                      Op.getOperand(1), Op.getOperand(2));
6570 }
6571
6572 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6573   assert(Subtarget->isTargetDarwin());
6574
6575   // For iOS, we want to call an alternative entry point: __sincos_stret,
6576   // return values are passed via sret.
6577   SDLoc dl(Op);
6578   SDValue Arg = Op.getOperand(0);
6579   EVT ArgVT = Arg.getValueType();
6580   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6581   auto PtrVT = getPointerTy(DAG.getDataLayout());
6582
6583   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6585
6586   // Pair of floats / doubles used to pass the result.
6587   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6588   auto &DL = DAG.getDataLayout();
6589
6590   ArgListTy Args;
6591   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
6592   SDValue SRet;
6593   if (ShouldUseSRet) {
6594     // Create stack object for sret.
6595     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6596     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6597     int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6598     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
6599
6600     ArgListEntry Entry;
6601     Entry.Node = SRet;
6602     Entry.Ty = RetTy->getPointerTo();
6603     Entry.isSExt = false;
6604     Entry.isZExt = false;
6605     Entry.isSRet = true;
6606     Args.push_back(Entry);
6607     RetTy = Type::getVoidTy(*DAG.getContext());
6608   }
6609
6610   ArgListEntry Entry;
6611   Entry.Node = Arg;
6612   Entry.Ty = ArgTy;
6613   Entry.isSExt = false;
6614   Entry.isZExt = false;
6615   Args.push_back(Entry);
6616
6617   const char *LibcallName =
6618       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
6619   RTLIB::Libcall LC =
6620       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
6621   CallingConv::ID CC = getLibcallCallingConv(LC);
6622   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6623
6624   TargetLowering::CallLoweringInfo CLI(DAG);
6625   CLI.setDebugLoc(dl)
6626       .setChain(DAG.getEntryNode())
6627       .setCallee(CC, RetTy, Callee, std::move(Args), 0)
6628       .setDiscardResult(ShouldUseSRet);
6629   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6630
6631   if (!ShouldUseSRet)
6632     return CallResult.first;
6633
6634   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6635                                 MachinePointerInfo(), false, false, false, 0);
6636
6637   // Address of cos field.
6638   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6639                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6640   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6641                                 MachinePointerInfo(), false, false, false, 0);
6642
6643   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6644   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6645                      LoadSin.getValue(0), LoadCos.getValue(0));
6646 }
6647
6648 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
6649                                                   bool Signed,
6650                                                   SDValue &Chain) const {
6651   EVT VT = Op.getValueType();
6652   assert((VT == MVT::i32 || VT == MVT::i64) &&
6653          "unexpected type for custom lowering DIV");
6654   SDLoc dl(Op);
6655
6656   const auto &DL = DAG.getDataLayout();
6657   const auto &TLI = DAG.getTargetLoweringInfo();
6658
6659   const char *Name = nullptr;
6660   if (Signed)
6661     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
6662   else
6663     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
6664
6665   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
6666
6667   ARMTargetLowering::ArgListTy Args;
6668
6669   for (auto AI : {1, 0}) {
6670     ArgListEntry Arg;
6671     Arg.Node = Op.getOperand(AI);
6672     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
6673     Args.push_back(Arg);
6674   }
6675
6676   CallLoweringInfo CLI(DAG);
6677   CLI.setDebugLoc(dl)
6678     .setChain(Chain)
6679     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
6680                ES, std::move(Args), 0);
6681
6682   return LowerCallTo(CLI).first;
6683 }
6684
6685 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
6686                                             bool Signed) const {
6687   assert(Op.getValueType() == MVT::i32 &&
6688          "unexpected type for custom lowering DIV");
6689   SDLoc dl(Op);
6690
6691   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
6692                                DAG.getEntryNode(), Op.getOperand(1));
6693
6694   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6695 }
6696
6697 void ARMTargetLowering::ExpandDIV_Windows(
6698     SDValue Op, SelectionDAG &DAG, bool Signed,
6699     SmallVectorImpl<SDValue> &Results) const {
6700   const auto &DL = DAG.getDataLayout();
6701   const auto &TLI = DAG.getTargetLoweringInfo();
6702
6703   assert(Op.getValueType() == MVT::i64 &&
6704          "unexpected type for custom lowering DIV");
6705   SDLoc dl(Op);
6706
6707   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6708                            DAG.getConstant(0, dl, MVT::i32));
6709   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op.getOperand(1),
6710                            DAG.getConstant(1, dl, MVT::i32));
6711   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i32, Lo, Hi);
6712
6713   SDValue DBZCHK =
6714       DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other, DAG.getEntryNode(), Or);
6715
6716   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
6717
6718   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
6719   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
6720                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
6721   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
6722
6723   Results.push_back(Lower);
6724   Results.push_back(Upper);
6725 }
6726
6727 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6728   // Monotonic load/store is legal for all targets
6729   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6730     return Op;
6731
6732   // Acquire/Release load/store is not legal for targets without a
6733   // dmb or equivalent available.
6734   return SDValue();
6735 }
6736
6737 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6738                                     SmallVectorImpl<SDValue> &Results,
6739                                     SelectionDAG &DAG,
6740                                     const ARMSubtarget *Subtarget) {
6741   SDLoc DL(N);
6742   // Under Power Management extensions, the cycle-count is:
6743   //    mrc p15, #0, <Rt>, c9, c13, #0
6744   SDValue Ops[] = { N->getOperand(0), // Chain
6745                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6746                     DAG.getConstant(15, DL, MVT::i32),
6747                     DAG.getConstant(0, DL, MVT::i32),
6748                     DAG.getConstant(9, DL, MVT::i32),
6749                     DAG.getConstant(13, DL, MVT::i32),
6750                     DAG.getConstant(0, DL, MVT::i32)
6751   };
6752
6753   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6754                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
6755   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
6756                                 DAG.getConstant(0, DL, MVT::i32)));
6757   Results.push_back(Cycles32.getValue(1));
6758 }
6759
6760 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6761   switch (Op.getOpcode()) {
6762   default: llvm_unreachable("Don't know how to custom lower this!");
6763   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6764   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6765   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6766   case ISD::GlobalAddress:
6767     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6768     default: llvm_unreachable("unknown object format");
6769     case Triple::COFF:
6770       return LowerGlobalAddressWindows(Op, DAG);
6771     case Triple::ELF:
6772       return LowerGlobalAddressELF(Op, DAG);
6773     case Triple::MachO:
6774       return LowerGlobalAddressDarwin(Op, DAG);
6775     }
6776   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6777   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6778   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6779   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6780   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6781   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6782   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6783   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6784   case ISD::SINT_TO_FP:
6785   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6786   case ISD::FP_TO_SINT:
6787   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6788   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6789   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6790   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6791   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6792   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6793   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6794   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6795                                                                Subtarget);
6796   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6797   case ISD::SHL:
6798   case ISD::SRL:
6799   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6800   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
6801   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
6802   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6803   case ISD::SRL_PARTS:
6804   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6805   case ISD::CTTZ:
6806   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6807   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6808   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6809   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6810   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6811   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6812   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6813   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6814   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6815   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6816   case ISD::MUL:           return LowerMUL(Op, DAG);
6817   case ISD::SDIV:
6818     if (Subtarget->isTargetWindows())
6819       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
6820     return LowerSDIV(Op, DAG);
6821   case ISD::UDIV:
6822     if (Subtarget->isTargetWindows())
6823       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
6824     return LowerUDIV(Op, DAG);
6825   case ISD::ADDC:
6826   case ISD::ADDE:
6827   case ISD::SUBC:
6828   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6829   case ISD::SADDO:
6830   case ISD::UADDO:
6831   case ISD::SSUBO:
6832   case ISD::USUBO:
6833     return LowerXALUO(Op, DAG);
6834   case ISD::ATOMIC_LOAD:
6835   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6836   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6837   case ISD::SDIVREM:
6838   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6839   case ISD::DYNAMIC_STACKALLOC:
6840     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6841       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6842     llvm_unreachable("Don't know how to custom lower this!");
6843   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6844   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6845   case ARMISD::WIN__DBZCHK: return SDValue();
6846   }
6847 }
6848
6849 /// ReplaceNodeResults - Replace the results of node with an illegal result
6850 /// type with new values built out of custom code.
6851 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6852                                            SmallVectorImpl<SDValue> &Results,
6853                                            SelectionDAG &DAG) const {
6854   SDValue Res;
6855   switch (N->getOpcode()) {
6856   default:
6857     llvm_unreachable("Don't know how to custom expand this!");
6858   case ISD::READ_REGISTER:
6859     ExpandREAD_REGISTER(N, Results, DAG);
6860     break;
6861   case ISD::BITCAST:
6862     Res = ExpandBITCAST(N, DAG);
6863     break;
6864   case ISD::SRL:
6865   case ISD::SRA:
6866     Res = Expand64BitShift(N, DAG, Subtarget);
6867     break;
6868   case ISD::SREM:
6869   case ISD::UREM:
6870     Res = LowerREM(N, DAG);
6871     break;
6872   case ISD::READCYCLECOUNTER:
6873     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6874     return;
6875   case ISD::UDIV:
6876   case ISD::SDIV:
6877     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
6878     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
6879                              Results);
6880   }
6881   if (Res.getNode())
6882     Results.push_back(Res);
6883 }
6884
6885 //===----------------------------------------------------------------------===//
6886 //                           ARM Scheduler Hooks
6887 //===----------------------------------------------------------------------===//
6888
6889 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6890 /// registers the function context.
6891 void ARMTargetLowering::
6892 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6893                        MachineBasicBlock *DispatchBB, int FI) const {
6894   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6895   DebugLoc dl = MI->getDebugLoc();
6896   MachineFunction *MF = MBB->getParent();
6897   MachineRegisterInfo *MRI = &MF->getRegInfo();
6898   MachineConstantPool *MCP = MF->getConstantPool();
6899   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6900   const Function *F = MF->getFunction();
6901
6902   bool isThumb = Subtarget->isThumb();
6903   bool isThumb2 = Subtarget->isThumb2();
6904
6905   unsigned PCLabelId = AFI->createPICLabelUId();
6906   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6907   ARMConstantPoolValue *CPV =
6908     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6909   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6910
6911   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6912                                            : &ARM::GPRRegClass;
6913
6914   // Grab constant pool and fixed stack memory operands.
6915   MachineMemOperand *CPMMO =
6916       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
6917                                MachineMemOperand::MOLoad, 4, 4);
6918
6919   MachineMemOperand *FIMMOSt =
6920       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
6921                                MachineMemOperand::MOStore, 4, 4);
6922
6923   // Load the address of the dispatch MBB into the jump buffer.
6924   if (isThumb2) {
6925     // Incoming value: jbuf
6926     //   ldr.n  r5, LCPI1_1
6927     //   orr    r5, r5, #1
6928     //   add    r5, pc
6929     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6930     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6931     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6932                    .addConstantPoolIndex(CPI)
6933                    .addMemOperand(CPMMO));
6934     // Set the low bit because of thumb mode.
6935     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6936     AddDefaultCC(
6937       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6938                      .addReg(NewVReg1, RegState::Kill)
6939                      .addImm(0x01)));
6940     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6941     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6942       .addReg(NewVReg2, RegState::Kill)
6943       .addImm(PCLabelId);
6944     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6945                    .addReg(NewVReg3, RegState::Kill)
6946                    .addFrameIndex(FI)
6947                    .addImm(36)  // &jbuf[1] :: pc
6948                    .addMemOperand(FIMMOSt));
6949   } else if (isThumb) {
6950     // Incoming value: jbuf
6951     //   ldr.n  r1, LCPI1_4
6952     //   add    r1, pc
6953     //   mov    r2, #1
6954     //   orrs   r1, r2
6955     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6956     //   str    r1, [r2]
6957     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6958     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6959                    .addConstantPoolIndex(CPI)
6960                    .addMemOperand(CPMMO));
6961     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6962     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6963       .addReg(NewVReg1, RegState::Kill)
6964       .addImm(PCLabelId);
6965     // Set the low bit because of thumb mode.
6966     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6967     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6968                    .addReg(ARM::CPSR, RegState::Define)
6969                    .addImm(1));
6970     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6971     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6972                    .addReg(ARM::CPSR, RegState::Define)
6973                    .addReg(NewVReg2, RegState::Kill)
6974                    .addReg(NewVReg3, RegState::Kill));
6975     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6976     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6977             .addFrameIndex(FI)
6978             .addImm(36); // &jbuf[1] :: pc
6979     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6980                    .addReg(NewVReg4, RegState::Kill)
6981                    .addReg(NewVReg5, RegState::Kill)
6982                    .addImm(0)
6983                    .addMemOperand(FIMMOSt));
6984   } else {
6985     // Incoming value: jbuf
6986     //   ldr  r1, LCPI1_1
6987     //   add  r1, pc, r1
6988     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6989     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6990     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6991                    .addConstantPoolIndex(CPI)
6992                    .addImm(0)
6993                    .addMemOperand(CPMMO));
6994     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6995     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6996                    .addReg(NewVReg1, RegState::Kill)
6997                    .addImm(PCLabelId));
6998     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6999                    .addReg(NewVReg2, RegState::Kill)
7000                    .addFrameIndex(FI)
7001                    .addImm(36)  // &jbuf[1] :: pc
7002                    .addMemOperand(FIMMOSt));
7003   }
7004 }
7005
7006 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
7007                                               MachineBasicBlock *MBB) const {
7008   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7009   DebugLoc dl = MI->getDebugLoc();
7010   MachineFunction *MF = MBB->getParent();
7011   MachineRegisterInfo *MRI = &MF->getRegInfo();
7012   MachineFrameInfo *MFI = MF->getFrameInfo();
7013   int FI = MFI->getFunctionContextIndex();
7014
7015   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7016                                                         : &ARM::GPRnopcRegClass;
7017
7018   // Get a mapping of the call site numbers to all of the landing pads they're
7019   // associated with.
7020   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7021   unsigned MaxCSNum = 0;
7022   MachineModuleInfo &MMI = MF->getMMI();
7023   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7024        ++BB) {
7025     if (!BB->isEHPad()) continue;
7026
7027     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7028     // pad.
7029     for (MachineBasicBlock::iterator
7030            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7031       if (!II->isEHLabel()) continue;
7032
7033       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7034       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7035
7036       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7037       for (SmallVectorImpl<unsigned>::iterator
7038              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7039            CSI != CSE; ++CSI) {
7040         CallSiteNumToLPad[*CSI].push_back(&*BB);
7041         MaxCSNum = std::max(MaxCSNum, *CSI);
7042       }
7043       break;
7044     }
7045   }
7046
7047   // Get an ordered list of the machine basic blocks for the jump table.
7048   std::vector<MachineBasicBlock*> LPadList;
7049   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7050   LPadList.reserve(CallSiteNumToLPad.size());
7051   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7052     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7053     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7054            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7055       LPadList.push_back(*II);
7056       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7057     }
7058   }
7059
7060   assert(!LPadList.empty() &&
7061          "No landing pad destinations for the dispatch jump table!");
7062
7063   // Create the jump table and associated information.
7064   MachineJumpTableInfo *JTI =
7065     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7066   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7067   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7068
7069   // Create the MBBs for the dispatch code.
7070
7071   // Shove the dispatch's address into the return slot in the function context.
7072   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7073   DispatchBB->setIsEHPad();
7074
7075   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7076   unsigned trap_opcode;
7077   if (Subtarget->isThumb())
7078     trap_opcode = ARM::tTRAP;
7079   else
7080     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7081
7082   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7083   DispatchBB->addSuccessor(TrapBB);
7084
7085   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7086   DispatchBB->addSuccessor(DispContBB);
7087
7088   // Insert and MBBs.
7089   MF->insert(MF->end(), DispatchBB);
7090   MF->insert(MF->end(), DispContBB);
7091   MF->insert(MF->end(), TrapBB);
7092
7093   // Insert code into the entry block that creates and registers the function
7094   // context.
7095   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7096
7097   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7098       MachinePointerInfo::getFixedStack(*MF, FI),
7099       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7100
7101   MachineInstrBuilder MIB;
7102   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7103
7104   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7105   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7106
7107   // Add a register mask with no preserved registers.  This results in all
7108   // registers being marked as clobbered.
7109   MIB.addRegMask(RI.getNoPreservedMask());
7110
7111   unsigned NumLPads = LPadList.size();
7112   if (Subtarget->isThumb2()) {
7113     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7114     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7115                    .addFrameIndex(FI)
7116                    .addImm(4)
7117                    .addMemOperand(FIMMOLd));
7118
7119     if (NumLPads < 256) {
7120       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7121                      .addReg(NewVReg1)
7122                      .addImm(LPadList.size()));
7123     } else {
7124       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7125       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7126                      .addImm(NumLPads & 0xFFFF));
7127
7128       unsigned VReg2 = VReg1;
7129       if ((NumLPads & 0xFFFF0000) != 0) {
7130         VReg2 = MRI->createVirtualRegister(TRC);
7131         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7132                        .addReg(VReg1)
7133                        .addImm(NumLPads >> 16));
7134       }
7135
7136       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7137                      .addReg(NewVReg1)
7138                      .addReg(VReg2));
7139     }
7140
7141     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7142       .addMBB(TrapBB)
7143       .addImm(ARMCC::HI)
7144       .addReg(ARM::CPSR);
7145
7146     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7147     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7148                    .addJumpTableIndex(MJTI));
7149
7150     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7151     AddDefaultCC(
7152       AddDefaultPred(
7153         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7154         .addReg(NewVReg3, RegState::Kill)
7155         .addReg(NewVReg1)
7156         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7157
7158     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7159       .addReg(NewVReg4, RegState::Kill)
7160       .addReg(NewVReg1)
7161       .addJumpTableIndex(MJTI);
7162   } else if (Subtarget->isThumb()) {
7163     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7164     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7165                    .addFrameIndex(FI)
7166                    .addImm(1)
7167                    .addMemOperand(FIMMOLd));
7168
7169     if (NumLPads < 256) {
7170       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7171                      .addReg(NewVReg1)
7172                      .addImm(NumLPads));
7173     } else {
7174       MachineConstantPool *ConstantPool = MF->getConstantPool();
7175       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7176       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7177
7178       // MachineConstantPool wants an explicit alignment.
7179       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7180       if (Align == 0)
7181         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7182       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7183
7184       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7185       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7186                      .addReg(VReg1, RegState::Define)
7187                      .addConstantPoolIndex(Idx));
7188       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7189                      .addReg(NewVReg1)
7190                      .addReg(VReg1));
7191     }
7192
7193     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7194       .addMBB(TrapBB)
7195       .addImm(ARMCC::HI)
7196       .addReg(ARM::CPSR);
7197
7198     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7199     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7200                    .addReg(ARM::CPSR, RegState::Define)
7201                    .addReg(NewVReg1)
7202                    .addImm(2));
7203
7204     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7205     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7206                    .addJumpTableIndex(MJTI));
7207
7208     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7209     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7210                    .addReg(ARM::CPSR, RegState::Define)
7211                    .addReg(NewVReg2, RegState::Kill)
7212                    .addReg(NewVReg3));
7213
7214     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7215         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7216
7217     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7218     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7219                    .addReg(NewVReg4, RegState::Kill)
7220                    .addImm(0)
7221                    .addMemOperand(JTMMOLd));
7222
7223     unsigned NewVReg6 = NewVReg5;
7224     if (RelocM == Reloc::PIC_) {
7225       NewVReg6 = MRI->createVirtualRegister(TRC);
7226       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7227                      .addReg(ARM::CPSR, RegState::Define)
7228                      .addReg(NewVReg5, RegState::Kill)
7229                      .addReg(NewVReg3));
7230     }
7231
7232     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7233       .addReg(NewVReg6, RegState::Kill)
7234       .addJumpTableIndex(MJTI);
7235   } else {
7236     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7237     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7238                    .addFrameIndex(FI)
7239                    .addImm(4)
7240                    .addMemOperand(FIMMOLd));
7241
7242     if (NumLPads < 256) {
7243       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7244                      .addReg(NewVReg1)
7245                      .addImm(NumLPads));
7246     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7247       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7248       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7249                      .addImm(NumLPads & 0xFFFF));
7250
7251       unsigned VReg2 = VReg1;
7252       if ((NumLPads & 0xFFFF0000) != 0) {
7253         VReg2 = MRI->createVirtualRegister(TRC);
7254         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7255                        .addReg(VReg1)
7256                        .addImm(NumLPads >> 16));
7257       }
7258
7259       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7260                      .addReg(NewVReg1)
7261                      .addReg(VReg2));
7262     } else {
7263       MachineConstantPool *ConstantPool = MF->getConstantPool();
7264       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7265       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7266
7267       // MachineConstantPool wants an explicit alignment.
7268       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7269       if (Align == 0)
7270         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7271       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7272
7273       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7274       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7275                      .addReg(VReg1, RegState::Define)
7276                      .addConstantPoolIndex(Idx)
7277                      .addImm(0));
7278       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7279                      .addReg(NewVReg1)
7280                      .addReg(VReg1, RegState::Kill));
7281     }
7282
7283     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7284       .addMBB(TrapBB)
7285       .addImm(ARMCC::HI)
7286       .addReg(ARM::CPSR);
7287
7288     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7289     AddDefaultCC(
7290       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7291                      .addReg(NewVReg1)
7292                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7293     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7294     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7295                    .addJumpTableIndex(MJTI));
7296
7297     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7298         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7299     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7300     AddDefaultPred(
7301       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7302       .addReg(NewVReg3, RegState::Kill)
7303       .addReg(NewVReg4)
7304       .addImm(0)
7305       .addMemOperand(JTMMOLd));
7306
7307     if (RelocM == Reloc::PIC_) {
7308       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7309         .addReg(NewVReg5, RegState::Kill)
7310         .addReg(NewVReg4)
7311         .addJumpTableIndex(MJTI);
7312     } else {
7313       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7314         .addReg(NewVReg5, RegState::Kill)
7315         .addJumpTableIndex(MJTI);
7316     }
7317   }
7318
7319   // Add the jump table entries as successors to the MBB.
7320   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7321   for (std::vector<MachineBasicBlock*>::iterator
7322          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7323     MachineBasicBlock *CurMBB = *I;
7324     if (SeenMBBs.insert(CurMBB).second)
7325       DispContBB->addSuccessor(CurMBB);
7326   }
7327
7328   // N.B. the order the invoke BBs are processed in doesn't matter here.
7329   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7330   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7331   for (MachineBasicBlock *BB : InvokeBBs) {
7332
7333     // Remove the landing pad successor from the invoke block and replace it
7334     // with the new dispatch block.
7335     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7336                                                   BB->succ_end());
7337     while (!Successors.empty()) {
7338       MachineBasicBlock *SMBB = Successors.pop_back_val();
7339       if (SMBB->isEHPad()) {
7340         BB->removeSuccessor(SMBB);
7341         MBBLPads.push_back(SMBB);
7342       }
7343     }
7344
7345     BB->addSuccessor(DispatchBB);
7346
7347     // Find the invoke call and mark all of the callee-saved registers as
7348     // 'implicit defined' so that they're spilled. This prevents code from
7349     // moving instructions to before the EH block, where they will never be
7350     // executed.
7351     for (MachineBasicBlock::reverse_iterator
7352            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7353       if (!II->isCall()) continue;
7354
7355       DenseMap<unsigned, bool> DefRegs;
7356       for (MachineInstr::mop_iterator
7357              OI = II->operands_begin(), OE = II->operands_end();
7358            OI != OE; ++OI) {
7359         if (!OI->isReg()) continue;
7360         DefRegs[OI->getReg()] = true;
7361       }
7362
7363       MachineInstrBuilder MIB(*MF, &*II);
7364
7365       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7366         unsigned Reg = SavedRegs[i];
7367         if (Subtarget->isThumb2() &&
7368             !ARM::tGPRRegClass.contains(Reg) &&
7369             !ARM::hGPRRegClass.contains(Reg))
7370           continue;
7371         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7372           continue;
7373         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7374           continue;
7375         if (!DefRegs[Reg])
7376           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7377       }
7378
7379       break;
7380     }
7381   }
7382
7383   // Mark all former landing pads as non-landing pads. The dispatch is the only
7384   // landing pad now.
7385   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7386          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7387     (*I)->setIsEHPad(false);
7388
7389   // The instruction is gone now.
7390   MI->eraseFromParent();
7391 }
7392
7393 static
7394 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7395   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7396        E = MBB->succ_end(); I != E; ++I)
7397     if (*I != Succ)
7398       return *I;
7399   llvm_unreachable("Expecting a BB with two successors!");
7400 }
7401
7402 /// Return the load opcode for a given load size. If load size >= 8,
7403 /// neon opcode will be returned.
7404 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7405   if (LdSize >= 8)
7406     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7407                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7408   if (IsThumb1)
7409     return LdSize == 4 ? ARM::tLDRi
7410                        : LdSize == 2 ? ARM::tLDRHi
7411                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7412   if (IsThumb2)
7413     return LdSize == 4 ? ARM::t2LDR_POST
7414                        : LdSize == 2 ? ARM::t2LDRH_POST
7415                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7416   return LdSize == 4 ? ARM::LDR_POST_IMM
7417                      : LdSize == 2 ? ARM::LDRH_POST
7418                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7419 }
7420
7421 /// Return the store opcode for a given store size. If store size >= 8,
7422 /// neon opcode will be returned.
7423 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7424   if (StSize >= 8)
7425     return StSize == 16 ? ARM::VST1q32wb_fixed
7426                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7427   if (IsThumb1)
7428     return StSize == 4 ? ARM::tSTRi
7429                        : StSize == 2 ? ARM::tSTRHi
7430                                      : StSize == 1 ? ARM::tSTRBi : 0;
7431   if (IsThumb2)
7432     return StSize == 4 ? ARM::t2STR_POST
7433                        : StSize == 2 ? ARM::t2STRH_POST
7434                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7435   return StSize == 4 ? ARM::STR_POST_IMM
7436                      : StSize == 2 ? ARM::STRH_POST
7437                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7438 }
7439
7440 /// Emit a post-increment load operation with given size. The instructions
7441 /// will be added to BB at Pos.
7442 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7443                        const TargetInstrInfo *TII, DebugLoc dl,
7444                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7445                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7446   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7447   assert(LdOpc != 0 && "Should have a load opcode");
7448   if (LdSize >= 8) {
7449     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7450                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7451                        .addImm(0));
7452   } else if (IsThumb1) {
7453     // load + update AddrIn
7454     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7455                        .addReg(AddrIn).addImm(0));
7456     MachineInstrBuilder MIB =
7457         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7458     MIB = AddDefaultT1CC(MIB);
7459     MIB.addReg(AddrIn).addImm(LdSize);
7460     AddDefaultPred(MIB);
7461   } else if (IsThumb2) {
7462     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7463                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7464                        .addImm(LdSize));
7465   } else { // arm
7466     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7467                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7468                        .addReg(0).addImm(LdSize));
7469   }
7470 }
7471
7472 /// Emit a post-increment store operation with given size. The instructions
7473 /// will be added to BB at Pos.
7474 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7475                        const TargetInstrInfo *TII, DebugLoc dl,
7476                        unsigned StSize, unsigned Data, unsigned AddrIn,
7477                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7478   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7479   assert(StOpc != 0 && "Should have a store opcode");
7480   if (StSize >= 8) {
7481     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7482                        .addReg(AddrIn).addImm(0).addReg(Data));
7483   } else if (IsThumb1) {
7484     // store + update AddrIn
7485     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7486                        .addReg(AddrIn).addImm(0));
7487     MachineInstrBuilder MIB =
7488         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7489     MIB = AddDefaultT1CC(MIB);
7490     MIB.addReg(AddrIn).addImm(StSize);
7491     AddDefaultPred(MIB);
7492   } else if (IsThumb2) {
7493     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7494                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7495   } else { // arm
7496     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7497                        .addReg(Data).addReg(AddrIn).addReg(0)
7498                        .addImm(StSize));
7499   }
7500 }
7501
7502 MachineBasicBlock *
7503 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7504                                    MachineBasicBlock *BB) const {
7505   // This pseudo instruction has 3 operands: dst, src, size
7506   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7507   // Otherwise, we will generate unrolled scalar copies.
7508   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7509   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7510   MachineFunction::iterator It = ++BB->getIterator();
7511
7512   unsigned dest = MI->getOperand(0).getReg();
7513   unsigned src = MI->getOperand(1).getReg();
7514   unsigned SizeVal = MI->getOperand(2).getImm();
7515   unsigned Align = MI->getOperand(3).getImm();
7516   DebugLoc dl = MI->getDebugLoc();
7517
7518   MachineFunction *MF = BB->getParent();
7519   MachineRegisterInfo &MRI = MF->getRegInfo();
7520   unsigned UnitSize = 0;
7521   const TargetRegisterClass *TRC = nullptr;
7522   const TargetRegisterClass *VecTRC = nullptr;
7523
7524   bool IsThumb1 = Subtarget->isThumb1Only();
7525   bool IsThumb2 = Subtarget->isThumb2();
7526
7527   if (Align & 1) {
7528     UnitSize = 1;
7529   } else if (Align & 2) {
7530     UnitSize = 2;
7531   } else {
7532     // Check whether we can use NEON instructions.
7533     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7534         Subtarget->hasNEON()) {
7535       if ((Align % 16 == 0) && SizeVal >= 16)
7536         UnitSize = 16;
7537       else if ((Align % 8 == 0) && SizeVal >= 8)
7538         UnitSize = 8;
7539     }
7540     // Can't use NEON instructions.
7541     if (UnitSize == 0)
7542       UnitSize = 4;
7543   }
7544
7545   // Select the correct opcode and register class for unit size load/store
7546   bool IsNeon = UnitSize >= 8;
7547   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7548   if (IsNeon)
7549     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7550                             : UnitSize == 8 ? &ARM::DPRRegClass
7551                                             : nullptr;
7552
7553   unsigned BytesLeft = SizeVal % UnitSize;
7554   unsigned LoopSize = SizeVal - BytesLeft;
7555
7556   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7557     // Use LDR and STR to copy.
7558     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7559     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7560     unsigned srcIn = src;
7561     unsigned destIn = dest;
7562     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7563       unsigned srcOut = MRI.createVirtualRegister(TRC);
7564       unsigned destOut = MRI.createVirtualRegister(TRC);
7565       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7566       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7567                  IsThumb1, IsThumb2);
7568       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7569                  IsThumb1, IsThumb2);
7570       srcIn = srcOut;
7571       destIn = destOut;
7572     }
7573
7574     // Handle the leftover bytes with LDRB and STRB.
7575     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7576     // [destOut] = STRB_POST(scratch, destIn, 1)
7577     for (unsigned i = 0; i < BytesLeft; i++) {
7578       unsigned srcOut = MRI.createVirtualRegister(TRC);
7579       unsigned destOut = MRI.createVirtualRegister(TRC);
7580       unsigned scratch = MRI.createVirtualRegister(TRC);
7581       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7582                  IsThumb1, IsThumb2);
7583       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7584                  IsThumb1, IsThumb2);
7585       srcIn = srcOut;
7586       destIn = destOut;
7587     }
7588     MI->eraseFromParent();   // The instruction is gone now.
7589     return BB;
7590   }
7591
7592   // Expand the pseudo op to a loop.
7593   // thisMBB:
7594   //   ...
7595   //   movw varEnd, # --> with thumb2
7596   //   movt varEnd, #
7597   //   ldrcp varEnd, idx --> without thumb2
7598   //   fallthrough --> loopMBB
7599   // loopMBB:
7600   //   PHI varPhi, varEnd, varLoop
7601   //   PHI srcPhi, src, srcLoop
7602   //   PHI destPhi, dst, destLoop
7603   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7604   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7605   //   subs varLoop, varPhi, #UnitSize
7606   //   bne loopMBB
7607   //   fallthrough --> exitMBB
7608   // exitMBB:
7609   //   epilogue to handle left-over bytes
7610   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7611   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7612   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7613   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7614   MF->insert(It, loopMBB);
7615   MF->insert(It, exitMBB);
7616
7617   // Transfer the remainder of BB and its successor edges to exitMBB.
7618   exitMBB->splice(exitMBB->begin(), BB,
7619                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7620   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7621
7622   // Load an immediate to varEnd.
7623   unsigned varEnd = MRI.createVirtualRegister(TRC);
7624   if (Subtarget->useMovt(*MF)) {
7625     unsigned Vtmp = varEnd;
7626     if ((LoopSize & 0xFFFF0000) != 0)
7627       Vtmp = MRI.createVirtualRegister(TRC);
7628     AddDefaultPred(BuildMI(BB, dl,
7629                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7630                            Vtmp).addImm(LoopSize & 0xFFFF));
7631
7632     if ((LoopSize & 0xFFFF0000) != 0)
7633       AddDefaultPred(BuildMI(BB, dl,
7634                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7635                              varEnd)
7636                          .addReg(Vtmp)
7637                          .addImm(LoopSize >> 16));
7638   } else {
7639     MachineConstantPool *ConstantPool = MF->getConstantPool();
7640     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7641     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7642
7643     // MachineConstantPool wants an explicit alignment.
7644     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7645     if (Align == 0)
7646       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7647     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7648
7649     if (IsThumb1)
7650       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7651           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7652     else
7653       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7654           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7655   }
7656   BB->addSuccessor(loopMBB);
7657
7658   // Generate the loop body:
7659   //   varPhi = PHI(varLoop, varEnd)
7660   //   srcPhi = PHI(srcLoop, src)
7661   //   destPhi = PHI(destLoop, dst)
7662   MachineBasicBlock *entryBB = BB;
7663   BB = loopMBB;
7664   unsigned varLoop = MRI.createVirtualRegister(TRC);
7665   unsigned varPhi = MRI.createVirtualRegister(TRC);
7666   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7667   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7668   unsigned destLoop = MRI.createVirtualRegister(TRC);
7669   unsigned destPhi = MRI.createVirtualRegister(TRC);
7670
7671   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7672     .addReg(varLoop).addMBB(loopMBB)
7673     .addReg(varEnd).addMBB(entryBB);
7674   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7675     .addReg(srcLoop).addMBB(loopMBB)
7676     .addReg(src).addMBB(entryBB);
7677   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7678     .addReg(destLoop).addMBB(loopMBB)
7679     .addReg(dest).addMBB(entryBB);
7680
7681   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7682   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7683   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7684   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7685              IsThumb1, IsThumb2);
7686   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7687              IsThumb1, IsThumb2);
7688
7689   // Decrement loop variable by UnitSize.
7690   if (IsThumb1) {
7691     MachineInstrBuilder MIB =
7692         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7693     MIB = AddDefaultT1CC(MIB);
7694     MIB.addReg(varPhi).addImm(UnitSize);
7695     AddDefaultPred(MIB);
7696   } else {
7697     MachineInstrBuilder MIB =
7698         BuildMI(*BB, BB->end(), dl,
7699                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7700     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7701     MIB->getOperand(5).setReg(ARM::CPSR);
7702     MIB->getOperand(5).setIsDef(true);
7703   }
7704   BuildMI(*BB, BB->end(), dl,
7705           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7706       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7707
7708   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7709   BB->addSuccessor(loopMBB);
7710   BB->addSuccessor(exitMBB);
7711
7712   // Add epilogue to handle BytesLeft.
7713   BB = exitMBB;
7714   MachineInstr *StartOfExit = exitMBB->begin();
7715
7716   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7717   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7718   unsigned srcIn = srcLoop;
7719   unsigned destIn = destLoop;
7720   for (unsigned i = 0; i < BytesLeft; i++) {
7721     unsigned srcOut = MRI.createVirtualRegister(TRC);
7722     unsigned destOut = MRI.createVirtualRegister(TRC);
7723     unsigned scratch = MRI.createVirtualRegister(TRC);
7724     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7725                IsThumb1, IsThumb2);
7726     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7727                IsThumb1, IsThumb2);
7728     srcIn = srcOut;
7729     destIn = destOut;
7730   }
7731
7732   MI->eraseFromParent();   // The instruction is gone now.
7733   return BB;
7734 }
7735
7736 MachineBasicBlock *
7737 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7738                                        MachineBasicBlock *MBB) const {
7739   const TargetMachine &TM = getTargetMachine();
7740   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7741   DebugLoc DL = MI->getDebugLoc();
7742
7743   assert(Subtarget->isTargetWindows() &&
7744          "__chkstk is only supported on Windows");
7745   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7746
7747   // __chkstk takes the number of words to allocate on the stack in R4, and
7748   // returns the stack adjustment in number of bytes in R4.  This will not
7749   // clober any other registers (other than the obvious lr).
7750   //
7751   // Although, technically, IP should be considered a register which may be
7752   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7753   // thumb-2 environment, so there is no interworking required.  As a result, we
7754   // do not expect a veneer to be emitted by the linker, clobbering IP.
7755   //
7756   // Each module receives its own copy of __chkstk, so no import thunk is
7757   // required, again, ensuring that IP is not clobbered.
7758   //
7759   // Finally, although some linkers may theoretically provide a trampoline for
7760   // out of range calls (which is quite common due to a 32M range limitation of
7761   // branches for Thumb), we can generate the long-call version via
7762   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7763   // IP.
7764
7765   switch (TM.getCodeModel()) {
7766   case CodeModel::Small:
7767   case CodeModel::Medium:
7768   case CodeModel::Default:
7769   case CodeModel::Kernel:
7770     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7771       .addImm((unsigned)ARMCC::AL).addReg(0)
7772       .addExternalSymbol("__chkstk")
7773       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7774       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7775       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7776     break;
7777   case CodeModel::Large:
7778   case CodeModel::JITDefault: {
7779     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7780     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7781
7782     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7783       .addExternalSymbol("__chkstk");
7784     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7785       .addImm((unsigned)ARMCC::AL).addReg(0)
7786       .addReg(Reg, RegState::Kill)
7787       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7788       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7789       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7790     break;
7791   }
7792   }
7793
7794   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7795                                       ARM::SP)
7796                               .addReg(ARM::SP).addReg(ARM::R4)));
7797
7798   MI->eraseFromParent();
7799   return MBB;
7800 }
7801
7802 MachineBasicBlock *
7803 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr *MI,
7804                                        MachineBasicBlock *MBB) const {
7805   DebugLoc DL = MI->getDebugLoc();
7806   MachineFunction *MF = MBB->getParent();
7807   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7808
7809   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
7810   MF->push_back(ContBB);
7811   ContBB->splice(ContBB->begin(), MBB,
7812                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7813   MBB->addSuccessor(ContBB);
7814
7815   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7816   MF->push_back(TrapBB);
7817   BuildMI(TrapBB, DL, TII->get(ARM::t2UDF)).addImm(249);
7818   MBB->addSuccessor(TrapBB);
7819
7820   BuildMI(*MBB, MI, DL, TII->get(ARM::tCBZ))
7821       .addReg(MI->getOperand(0).getReg())
7822       .addMBB(TrapBB);
7823
7824   MI->eraseFromParent();
7825   return ContBB;
7826 }
7827
7828 MachineBasicBlock *
7829 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7830                                                MachineBasicBlock *BB) const {
7831   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7832   DebugLoc dl = MI->getDebugLoc();
7833   bool isThumb2 = Subtarget->isThumb2();
7834   switch (MI->getOpcode()) {
7835   default: {
7836     MI->dump();
7837     llvm_unreachable("Unexpected instr type to insert");
7838   }
7839   // The Thumb2 pre-indexed stores have the same MI operands, they just
7840   // define them differently in the .td files from the isel patterns, so
7841   // they need pseudos.
7842   case ARM::t2STR_preidx:
7843     MI->setDesc(TII->get(ARM::t2STR_PRE));
7844     return BB;
7845   case ARM::t2STRB_preidx:
7846     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7847     return BB;
7848   case ARM::t2STRH_preidx:
7849     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7850     return BB;
7851
7852   case ARM::STRi_preidx:
7853   case ARM::STRBi_preidx: {
7854     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7855       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7856     // Decode the offset.
7857     unsigned Offset = MI->getOperand(4).getImm();
7858     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7859     Offset = ARM_AM::getAM2Offset(Offset);
7860     if (isSub)
7861       Offset = -Offset;
7862
7863     MachineMemOperand *MMO = *MI->memoperands_begin();
7864     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7865       .addOperand(MI->getOperand(0))  // Rn_wb
7866       .addOperand(MI->getOperand(1))  // Rt
7867       .addOperand(MI->getOperand(2))  // Rn
7868       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7869       .addOperand(MI->getOperand(5))  // pred
7870       .addOperand(MI->getOperand(6))
7871       .addMemOperand(MMO);
7872     MI->eraseFromParent();
7873     return BB;
7874   }
7875   case ARM::STRr_preidx:
7876   case ARM::STRBr_preidx:
7877   case ARM::STRH_preidx: {
7878     unsigned NewOpc;
7879     switch (MI->getOpcode()) {
7880     default: llvm_unreachable("unexpected opcode!");
7881     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7882     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7883     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7884     }
7885     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7886     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7887       MIB.addOperand(MI->getOperand(i));
7888     MI->eraseFromParent();
7889     return BB;
7890   }
7891
7892   case ARM::tMOVCCr_pseudo: {
7893     // To "insert" a SELECT_CC instruction, we actually have to insert the
7894     // diamond control-flow pattern.  The incoming instruction knows the
7895     // destination vreg to set, the condition code register to branch on, the
7896     // true/false values to select between, and a branch opcode to use.
7897     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7898     MachineFunction::iterator It = ++BB->getIterator();
7899
7900     //  thisMBB:
7901     //  ...
7902     //   TrueVal = ...
7903     //   cmpTY ccX, r1, r2
7904     //   bCC copy1MBB
7905     //   fallthrough --> copy0MBB
7906     MachineBasicBlock *thisMBB  = BB;
7907     MachineFunction *F = BB->getParent();
7908     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7909     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7910     F->insert(It, copy0MBB);
7911     F->insert(It, sinkMBB);
7912
7913     // Transfer the remainder of BB and its successor edges to sinkMBB.
7914     sinkMBB->splice(sinkMBB->begin(), BB,
7915                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7916     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7917
7918     BB->addSuccessor(copy0MBB);
7919     BB->addSuccessor(sinkMBB);
7920
7921     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7922       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7923
7924     //  copy0MBB:
7925     //   %FalseValue = ...
7926     //   # fallthrough to sinkMBB
7927     BB = copy0MBB;
7928
7929     // Update machine-CFG edges
7930     BB->addSuccessor(sinkMBB);
7931
7932     //  sinkMBB:
7933     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7934     //  ...
7935     BB = sinkMBB;
7936     BuildMI(*BB, BB->begin(), dl,
7937             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7938       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7939       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7940
7941     MI->eraseFromParent();   // The pseudo instruction is gone now.
7942     return BB;
7943   }
7944
7945   case ARM::BCCi64:
7946   case ARM::BCCZi64: {
7947     // If there is an unconditional branch to the other successor, remove it.
7948     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7949
7950     // Compare both parts that make up the double comparison separately for
7951     // equality.
7952     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7953
7954     unsigned LHS1 = MI->getOperand(1).getReg();
7955     unsigned LHS2 = MI->getOperand(2).getReg();
7956     if (RHSisZero) {
7957       AddDefaultPred(BuildMI(BB, dl,
7958                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7959                      .addReg(LHS1).addImm(0));
7960       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7961         .addReg(LHS2).addImm(0)
7962         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7963     } else {
7964       unsigned RHS1 = MI->getOperand(3).getReg();
7965       unsigned RHS2 = MI->getOperand(4).getReg();
7966       AddDefaultPred(BuildMI(BB, dl,
7967                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7968                      .addReg(LHS1).addReg(RHS1));
7969       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7970         .addReg(LHS2).addReg(RHS2)
7971         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7972     }
7973
7974     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7975     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7976     if (MI->getOperand(0).getImm() == ARMCC::NE)
7977       std::swap(destMBB, exitMBB);
7978
7979     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7980       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7981     if (isThumb2)
7982       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7983     else
7984       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7985
7986     MI->eraseFromParent();   // The pseudo instruction is gone now.
7987     return BB;
7988   }
7989
7990   case ARM::Int_eh_sjlj_setjmp:
7991   case ARM::Int_eh_sjlj_setjmp_nofp:
7992   case ARM::tInt_eh_sjlj_setjmp:
7993   case ARM::t2Int_eh_sjlj_setjmp:
7994   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7995     return BB;
7996
7997   case ARM::Int_eh_sjlj_setup_dispatch:
7998     EmitSjLjDispatchBlock(MI, BB);
7999     return BB;
8000
8001   case ARM::ABS:
8002   case ARM::t2ABS: {
8003     // To insert an ABS instruction, we have to insert the
8004     // diamond control-flow pattern.  The incoming instruction knows the
8005     // source vreg to test against 0, the destination vreg to set,
8006     // the condition code register to branch on, the
8007     // true/false values to select between, and a branch opcode to use.
8008     // It transforms
8009     //     V1 = ABS V0
8010     // into
8011     //     V2 = MOVS V0
8012     //     BCC                      (branch to SinkBB if V0 >= 0)
8013     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8014     //     SinkBB: V1 = PHI(V2, V3)
8015     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8016     MachineFunction::iterator BBI = ++BB->getIterator();
8017     MachineFunction *Fn = BB->getParent();
8018     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8019     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8020     Fn->insert(BBI, RSBBB);
8021     Fn->insert(BBI, SinkBB);
8022
8023     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8024     unsigned int ABSDstReg = MI->getOperand(0).getReg();
8025     bool ABSSrcKIll = MI->getOperand(1).isKill();
8026     bool isThumb2 = Subtarget->isThumb2();
8027     MachineRegisterInfo &MRI = Fn->getRegInfo();
8028     // In Thumb mode S must not be specified if source register is the SP or
8029     // PC and if destination register is the SP, so restrict register class
8030     unsigned NewRsbDstReg =
8031       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8032
8033     // Transfer the remainder of BB and its successor edges to sinkMBB.
8034     SinkBB->splice(SinkBB->begin(), BB,
8035                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8036     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8037
8038     BB->addSuccessor(RSBBB);
8039     BB->addSuccessor(SinkBB);
8040
8041     // fall through to SinkMBB
8042     RSBBB->addSuccessor(SinkBB);
8043
8044     // insert a cmp at the end of BB
8045     AddDefaultPred(BuildMI(BB, dl,
8046                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8047                    .addReg(ABSSrcReg).addImm(0));
8048
8049     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8050     BuildMI(BB, dl,
8051       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8052       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8053
8054     // insert rsbri in RSBBB
8055     // Note: BCC and rsbri will be converted into predicated rsbmi
8056     // by if-conversion pass
8057     BuildMI(*RSBBB, RSBBB->begin(), dl,
8058       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8059       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8060       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8061
8062     // insert PHI in SinkBB,
8063     // reuse ABSDstReg to not change uses of ABS instruction
8064     BuildMI(*SinkBB, SinkBB->begin(), dl,
8065       TII->get(ARM::PHI), ABSDstReg)
8066       .addReg(NewRsbDstReg).addMBB(RSBBB)
8067       .addReg(ABSSrcReg).addMBB(BB);
8068
8069     // remove ABS instruction
8070     MI->eraseFromParent();
8071
8072     // return last added BB
8073     return SinkBB;
8074   }
8075   case ARM::COPY_STRUCT_BYVAL_I32:
8076     ++NumLoopByVals;
8077     return EmitStructByval(MI, BB);
8078   case ARM::WIN__CHKSTK:
8079     return EmitLowered__chkstk(MI, BB);
8080   case ARM::WIN__DBZCHK:
8081     return EmitLowered__dbzchk(MI, BB);
8082   }
8083 }
8084
8085 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8086 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8087 /// instead of as a custom inserter because we need the use list from the SDNode.
8088 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8089                                    MachineInstr *MI, const SDNode *Node) {
8090   bool isThumb1 = Subtarget->isThumb1Only();
8091
8092   DebugLoc DL = MI->getDebugLoc();
8093   MachineFunction *MF = MI->getParent()->getParent();
8094   MachineRegisterInfo &MRI = MF->getRegInfo();
8095   MachineInstrBuilder MIB(*MF, MI);
8096
8097   // If the new dst/src is unused mark it as dead.
8098   if (!Node->hasAnyUseOfValue(0)) {
8099     MI->getOperand(0).setIsDead(true);
8100   }
8101   if (!Node->hasAnyUseOfValue(1)) {
8102     MI->getOperand(1).setIsDead(true);
8103   }
8104
8105   // The MEMCPY both defines and kills the scratch registers.
8106   for (unsigned I = 0; I != MI->getOperand(4).getImm(); ++I) {
8107     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8108                                                          : &ARM::GPRRegClass);
8109     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8110   }
8111 }
8112
8113 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8114                                                       SDNode *Node) const {
8115   if (MI->getOpcode() == ARM::MEMCPY) {
8116     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8117     return;
8118   }
8119
8120   const MCInstrDesc *MCID = &MI->getDesc();
8121   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8122   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8123   // operand is still set to noreg. If needed, set the optional operand's
8124   // register to CPSR, and remove the redundant implicit def.
8125   //
8126   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8127
8128   // Rename pseudo opcodes.
8129   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8130   if (NewOpc) {
8131     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8132     MCID = &TII->get(NewOpc);
8133
8134     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8135            "converted opcode should be the same except for cc_out");
8136
8137     MI->setDesc(*MCID);
8138
8139     // Add the optional cc_out operand
8140     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8141   }
8142   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8143
8144   // Any ARM instruction that sets the 's' bit should specify an optional
8145   // "cc_out" operand in the last operand position.
8146   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8147     assert(!NewOpc && "Optional cc_out operand required");
8148     return;
8149   }
8150   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8151   // since we already have an optional CPSR def.
8152   bool definesCPSR = false;
8153   bool deadCPSR = false;
8154   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8155        i != e; ++i) {
8156     const MachineOperand &MO = MI->getOperand(i);
8157     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8158       definesCPSR = true;
8159       if (MO.isDead())
8160         deadCPSR = true;
8161       MI->RemoveOperand(i);
8162       break;
8163     }
8164   }
8165   if (!definesCPSR) {
8166     assert(!NewOpc && "Optional cc_out operand required");
8167     return;
8168   }
8169   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8170   if (deadCPSR) {
8171     assert(!MI->getOperand(ccOutIdx).getReg() &&
8172            "expect uninitialized optional cc_out operand");
8173     return;
8174   }
8175
8176   // If this instruction was defined with an optional CPSR def and its dag node
8177   // had a live implicit CPSR def, then activate the optional CPSR def.
8178   MachineOperand &MO = MI->getOperand(ccOutIdx);
8179   MO.setReg(ARM::CPSR);
8180   MO.setIsDef(true);
8181 }
8182
8183 //===----------------------------------------------------------------------===//
8184 //                           ARM Optimization Hooks
8185 //===----------------------------------------------------------------------===//
8186
8187 // Helper function that checks if N is a null or all ones constant.
8188 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8189   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8190   if (!C)
8191     return false;
8192   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8193 }
8194
8195 // Return true if N is conditionally 0 or all ones.
8196 // Detects these expressions where cc is an i1 value:
8197 //
8198 //   (select cc 0, y)   [AllOnes=0]
8199 //   (select cc y, 0)   [AllOnes=0]
8200 //   (zext cc)          [AllOnes=0]
8201 //   (sext cc)          [AllOnes=0/1]
8202 //   (select cc -1, y)  [AllOnes=1]
8203 //   (select cc y, -1)  [AllOnes=1]
8204 //
8205 // Invert is set when N is the null/all ones constant when CC is false.
8206 // OtherOp is set to the alternative value of N.
8207 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8208                                        SDValue &CC, bool &Invert,
8209                                        SDValue &OtherOp,
8210                                        SelectionDAG &DAG) {
8211   switch (N->getOpcode()) {
8212   default: return false;
8213   case ISD::SELECT: {
8214     CC = N->getOperand(0);
8215     SDValue N1 = N->getOperand(1);
8216     SDValue N2 = N->getOperand(2);
8217     if (isZeroOrAllOnes(N1, AllOnes)) {
8218       Invert = false;
8219       OtherOp = N2;
8220       return true;
8221     }
8222     if (isZeroOrAllOnes(N2, AllOnes)) {
8223       Invert = true;
8224       OtherOp = N1;
8225       return true;
8226     }
8227     return false;
8228   }
8229   case ISD::ZERO_EXTEND:
8230     // (zext cc) can never be the all ones value.
8231     if (AllOnes)
8232       return false;
8233     // Fall through.
8234   case ISD::SIGN_EXTEND: {
8235     SDLoc dl(N);
8236     EVT VT = N->getValueType(0);
8237     CC = N->getOperand(0);
8238     if (CC.getValueType() != MVT::i1)
8239       return false;
8240     Invert = !AllOnes;
8241     if (AllOnes)
8242       // When looking for an AllOnes constant, N is an sext, and the 'other'
8243       // value is 0.
8244       OtherOp = DAG.getConstant(0, dl, VT);
8245     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8246       // When looking for a 0 constant, N can be zext or sext.
8247       OtherOp = DAG.getConstant(1, dl, VT);
8248     else
8249       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8250                                 VT);
8251     return true;
8252   }
8253   }
8254 }
8255
8256 // Combine a constant select operand into its use:
8257 //
8258 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8259 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8260 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8261 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8262 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8263 //
8264 // The transform is rejected if the select doesn't have a constant operand that
8265 // is null, or all ones when AllOnes is set.
8266 //
8267 // Also recognize sext/zext from i1:
8268 //
8269 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8270 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8271 //
8272 // These transformations eventually create predicated instructions.
8273 //
8274 // @param N       The node to transform.
8275 // @param Slct    The N operand that is a select.
8276 // @param OtherOp The other N operand (x above).
8277 // @param DCI     Context.
8278 // @param AllOnes Require the select constant to be all ones instead of null.
8279 // @returns The new node, or SDValue() on failure.
8280 static
8281 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8282                             TargetLowering::DAGCombinerInfo &DCI,
8283                             bool AllOnes = false) {
8284   SelectionDAG &DAG = DCI.DAG;
8285   EVT VT = N->getValueType(0);
8286   SDValue NonConstantVal;
8287   SDValue CCOp;
8288   bool SwapSelectOps;
8289   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8290                                   NonConstantVal, DAG))
8291     return SDValue();
8292
8293   // Slct is now know to be the desired identity constant when CC is true.
8294   SDValue TrueVal = OtherOp;
8295   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8296                                  OtherOp, NonConstantVal);
8297   // Unless SwapSelectOps says CC should be false.
8298   if (SwapSelectOps)
8299     std::swap(TrueVal, FalseVal);
8300
8301   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8302                      CCOp, TrueVal, FalseVal);
8303 }
8304
8305 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8306 static
8307 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8308                                        TargetLowering::DAGCombinerInfo &DCI) {
8309   SDValue N0 = N->getOperand(0);
8310   SDValue N1 = N->getOperand(1);
8311   if (N0.getNode()->hasOneUse()) {
8312     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8313     if (Result.getNode())
8314       return Result;
8315   }
8316   if (N1.getNode()->hasOneUse()) {
8317     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8318     if (Result.getNode())
8319       return Result;
8320   }
8321   return SDValue();
8322 }
8323
8324 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8325 // (only after legalization).
8326 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8327                                  TargetLowering::DAGCombinerInfo &DCI,
8328                                  const ARMSubtarget *Subtarget) {
8329
8330   // Only perform optimization if after legalize, and if NEON is available. We
8331   // also expected both operands to be BUILD_VECTORs.
8332   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8333       || N0.getOpcode() != ISD::BUILD_VECTOR
8334       || N1.getOpcode() != ISD::BUILD_VECTOR)
8335     return SDValue();
8336
8337   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8338   EVT VT = N->getValueType(0);
8339   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8340     return SDValue();
8341
8342   // Check that the vector operands are of the right form.
8343   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8344   // operands, where N is the size of the formed vector.
8345   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8346   // index such that we have a pair wise add pattern.
8347
8348   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8349   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8350     return SDValue();
8351   SDValue Vec = N0->getOperand(0)->getOperand(0);
8352   SDNode *V = Vec.getNode();
8353   unsigned nextIndex = 0;
8354
8355   // For each operands to the ADD which are BUILD_VECTORs,
8356   // check to see if each of their operands are an EXTRACT_VECTOR with
8357   // the same vector and appropriate index.
8358   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8359     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8360         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8361
8362       SDValue ExtVec0 = N0->getOperand(i);
8363       SDValue ExtVec1 = N1->getOperand(i);
8364
8365       // First operand is the vector, verify its the same.
8366       if (V != ExtVec0->getOperand(0).getNode() ||
8367           V != ExtVec1->getOperand(0).getNode())
8368         return SDValue();
8369
8370       // Second is the constant, verify its correct.
8371       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8372       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8373
8374       // For the constant, we want to see all the even or all the odd.
8375       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8376           || C1->getZExtValue() != nextIndex+1)
8377         return SDValue();
8378
8379       // Increment index.
8380       nextIndex+=2;
8381     } else
8382       return SDValue();
8383   }
8384
8385   // Create VPADDL node.
8386   SelectionDAG &DAG = DCI.DAG;
8387   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8388
8389   SDLoc dl(N);
8390
8391   // Build operand list.
8392   SmallVector<SDValue, 8> Ops;
8393   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8394                                 TLI.getPointerTy(DAG.getDataLayout())));
8395
8396   // Input is the vector.
8397   Ops.push_back(Vec);
8398
8399   // Get widened type and narrowed type.
8400   MVT widenType;
8401   unsigned numElem = VT.getVectorNumElements();
8402   
8403   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8404   switch (inputLaneType.getSimpleVT().SimpleTy) {
8405     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8406     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8407     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8408     default:
8409       llvm_unreachable("Invalid vector element type for padd optimization.");
8410   }
8411
8412   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8413   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8414   return DAG.getNode(ExtOp, dl, VT, tmp);
8415 }
8416
8417 static SDValue findMUL_LOHI(SDValue V) {
8418   if (V->getOpcode() == ISD::UMUL_LOHI ||
8419       V->getOpcode() == ISD::SMUL_LOHI)
8420     return V;
8421   return SDValue();
8422 }
8423
8424 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8425                                      TargetLowering::DAGCombinerInfo &DCI,
8426                                      const ARMSubtarget *Subtarget) {
8427
8428   if (Subtarget->isThumb1Only()) return SDValue();
8429
8430   // Only perform the checks after legalize when the pattern is available.
8431   if (DCI.isBeforeLegalize()) return SDValue();
8432
8433   // Look for multiply add opportunities.
8434   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8435   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8436   // a glue link from the first add to the second add.
8437   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8438   // a S/UMLAL instruction.
8439   //                  UMUL_LOHI
8440   //                 / :lo    \ :hi
8441   //                /          \          [no multiline comment]
8442   //    loAdd ->  ADDE         |
8443   //                 \ :glue  /
8444   //                  \      /
8445   //                    ADDC   <- hiAdd
8446   //
8447   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8448   SDValue AddcOp0 = AddcNode->getOperand(0);
8449   SDValue AddcOp1 = AddcNode->getOperand(1);
8450
8451   // Check if the two operands are from the same mul_lohi node.
8452   if (AddcOp0.getNode() == AddcOp1.getNode())
8453     return SDValue();
8454
8455   assert(AddcNode->getNumValues() == 2 &&
8456          AddcNode->getValueType(0) == MVT::i32 &&
8457          "Expect ADDC with two result values. First: i32");
8458
8459   // Check that we have a glued ADDC node.
8460   if (AddcNode->getValueType(1) != MVT::Glue)
8461     return SDValue();
8462
8463   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8464   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8465       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8466       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8467       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8468     return SDValue();
8469
8470   // Look for the glued ADDE.
8471   SDNode* AddeNode = AddcNode->getGluedUser();
8472   if (!AddeNode)
8473     return SDValue();
8474
8475   // Make sure it is really an ADDE.
8476   if (AddeNode->getOpcode() != ISD::ADDE)
8477     return SDValue();
8478
8479   assert(AddeNode->getNumOperands() == 3 &&
8480          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8481          "ADDE node has the wrong inputs");
8482
8483   // Check for the triangle shape.
8484   SDValue AddeOp0 = AddeNode->getOperand(0);
8485   SDValue AddeOp1 = AddeNode->getOperand(1);
8486
8487   // Make sure that the ADDE operands are not coming from the same node.
8488   if (AddeOp0.getNode() == AddeOp1.getNode())
8489     return SDValue();
8490
8491   // Find the MUL_LOHI node walking up ADDE's operands.
8492   bool IsLeftOperandMUL = false;
8493   SDValue MULOp = findMUL_LOHI(AddeOp0);
8494   if (MULOp == SDValue())
8495    MULOp = findMUL_LOHI(AddeOp1);
8496   else
8497     IsLeftOperandMUL = true;
8498   if (MULOp == SDValue())
8499     return SDValue();
8500
8501   // Figure out the right opcode.
8502   unsigned Opc = MULOp->getOpcode();
8503   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8504
8505   // Figure out the high and low input values to the MLAL node.
8506   SDValue* HiAdd = nullptr;
8507   SDValue* LoMul = nullptr;
8508   SDValue* LowAdd = nullptr;
8509
8510   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8511   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8512     return SDValue();
8513
8514   if (IsLeftOperandMUL)
8515     HiAdd = &AddeOp1;
8516   else
8517     HiAdd = &AddeOp0;
8518
8519
8520   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8521   // whose low result is fed to the ADDC we are checking.
8522
8523   if (AddcOp0 == MULOp.getValue(0)) {
8524     LoMul = &AddcOp0;
8525     LowAdd = &AddcOp1;
8526   }
8527   if (AddcOp1 == MULOp.getValue(0)) {
8528     LoMul = &AddcOp1;
8529     LowAdd = &AddcOp0;
8530   }
8531
8532   if (!LoMul)
8533     return SDValue();
8534
8535   // Create the merged node.
8536   SelectionDAG &DAG = DCI.DAG;
8537
8538   // Build operand list.
8539   SmallVector<SDValue, 8> Ops;
8540   Ops.push_back(LoMul->getOperand(0));
8541   Ops.push_back(LoMul->getOperand(1));
8542   Ops.push_back(*LowAdd);
8543   Ops.push_back(*HiAdd);
8544
8545   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8546                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8547
8548   // Replace the ADDs' nodes uses by the MLA node's values.
8549   SDValue HiMLALResult(MLALNode.getNode(), 1);
8550   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8551
8552   SDValue LoMLALResult(MLALNode.getNode(), 0);
8553   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8554
8555   // Return original node to notify the driver to stop replacing.
8556   SDValue resNode(AddcNode, 0);
8557   return resNode;
8558 }
8559
8560 /// PerformADDCCombine - Target-specific dag combine transform from
8561 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8562 static SDValue PerformADDCCombine(SDNode *N,
8563                                  TargetLowering::DAGCombinerInfo &DCI,
8564                                  const ARMSubtarget *Subtarget) {
8565
8566   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8567
8568 }
8569
8570 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8571 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8572 /// called with the default operands, and if that fails, with commuted
8573 /// operands.
8574 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8575                                           TargetLowering::DAGCombinerInfo &DCI,
8576                                           const ARMSubtarget *Subtarget){
8577
8578   // Attempt to create vpaddl for this add.
8579   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8580   if (Result.getNode())
8581     return Result;
8582
8583   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8584   if (N0.getNode()->hasOneUse()) {
8585     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8586     if (Result.getNode()) return Result;
8587   }
8588   return SDValue();
8589 }
8590
8591 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8592 ///
8593 static SDValue PerformADDCombine(SDNode *N,
8594                                  TargetLowering::DAGCombinerInfo &DCI,
8595                                  const ARMSubtarget *Subtarget) {
8596   SDValue N0 = N->getOperand(0);
8597   SDValue N1 = N->getOperand(1);
8598
8599   // First try with the default operand order.
8600   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8601   if (Result.getNode())
8602     return Result;
8603
8604   // If that didn't work, try again with the operands commuted.
8605   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8606 }
8607
8608 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8609 ///
8610 static SDValue PerformSUBCombine(SDNode *N,
8611                                  TargetLowering::DAGCombinerInfo &DCI) {
8612   SDValue N0 = N->getOperand(0);
8613   SDValue N1 = N->getOperand(1);
8614
8615   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8616   if (N1.getNode()->hasOneUse()) {
8617     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8618     if (Result.getNode()) return Result;
8619   }
8620
8621   return SDValue();
8622 }
8623
8624 /// PerformVMULCombine
8625 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8626 /// special multiplier accumulator forwarding.
8627 ///   vmul d3, d0, d2
8628 ///   vmla d3, d1, d2
8629 /// is faster than
8630 ///   vadd d3, d0, d1
8631 ///   vmul d3, d3, d2
8632 //  However, for (A + B) * (A + B),
8633 //    vadd d2, d0, d1
8634 //    vmul d3, d0, d2
8635 //    vmla d3, d1, d2
8636 //  is slower than
8637 //    vadd d2, d0, d1
8638 //    vmul d3, d2, d2
8639 static SDValue PerformVMULCombine(SDNode *N,
8640                                   TargetLowering::DAGCombinerInfo &DCI,
8641                                   const ARMSubtarget *Subtarget) {
8642   if (!Subtarget->hasVMLxForwarding())
8643     return SDValue();
8644
8645   SelectionDAG &DAG = DCI.DAG;
8646   SDValue N0 = N->getOperand(0);
8647   SDValue N1 = N->getOperand(1);
8648   unsigned Opcode = N0.getOpcode();
8649   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8650       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8651     Opcode = N1.getOpcode();
8652     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8653         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8654       return SDValue();
8655     std::swap(N0, N1);
8656   }
8657
8658   if (N0 == N1)
8659     return SDValue();
8660
8661   EVT VT = N->getValueType(0);
8662   SDLoc DL(N);
8663   SDValue N00 = N0->getOperand(0);
8664   SDValue N01 = N0->getOperand(1);
8665   return DAG.getNode(Opcode, DL, VT,
8666                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8667                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8668 }
8669
8670 static SDValue PerformMULCombine(SDNode *N,
8671                                  TargetLowering::DAGCombinerInfo &DCI,
8672                                  const ARMSubtarget *Subtarget) {
8673   SelectionDAG &DAG = DCI.DAG;
8674
8675   if (Subtarget->isThumb1Only())
8676     return SDValue();
8677
8678   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8679     return SDValue();
8680
8681   EVT VT = N->getValueType(0);
8682   if (VT.is64BitVector() || VT.is128BitVector())
8683     return PerformVMULCombine(N, DCI, Subtarget);
8684   if (VT != MVT::i32)
8685     return SDValue();
8686
8687   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8688   if (!C)
8689     return SDValue();
8690
8691   int64_t MulAmt = C->getSExtValue();
8692   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8693
8694   ShiftAmt = ShiftAmt & (32 - 1);
8695   SDValue V = N->getOperand(0);
8696   SDLoc DL(N);
8697
8698   SDValue Res;
8699   MulAmt >>= ShiftAmt;
8700
8701   if (MulAmt >= 0) {
8702     if (isPowerOf2_32(MulAmt - 1)) {
8703       // (mul x, 2^N + 1) => (add (shl x, N), x)
8704       Res = DAG.getNode(ISD::ADD, DL, VT,
8705                         V,
8706                         DAG.getNode(ISD::SHL, DL, VT,
8707                                     V,
8708                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8709                                                     MVT::i32)));
8710     } else if (isPowerOf2_32(MulAmt + 1)) {
8711       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8712       Res = DAG.getNode(ISD::SUB, DL, VT,
8713                         DAG.getNode(ISD::SHL, DL, VT,
8714                                     V,
8715                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8716                                                     MVT::i32)),
8717                         V);
8718     } else
8719       return SDValue();
8720   } else {
8721     uint64_t MulAmtAbs = -MulAmt;
8722     if (isPowerOf2_32(MulAmtAbs + 1)) {
8723       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8724       Res = DAG.getNode(ISD::SUB, DL, VT,
8725                         V,
8726                         DAG.getNode(ISD::SHL, DL, VT,
8727                                     V,
8728                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8729                                                     MVT::i32)));
8730     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8731       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8732       Res = DAG.getNode(ISD::ADD, DL, VT,
8733                         V,
8734                         DAG.getNode(ISD::SHL, DL, VT,
8735                                     V,
8736                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8737                                                     MVT::i32)));
8738       Res = DAG.getNode(ISD::SUB, DL, VT,
8739                         DAG.getConstant(0, DL, MVT::i32), Res);
8740
8741     } else
8742       return SDValue();
8743   }
8744
8745   if (ShiftAmt != 0)
8746     Res = DAG.getNode(ISD::SHL, DL, VT,
8747                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8748
8749   // Do not add new nodes to DAG combiner worklist.
8750   DCI.CombineTo(N, Res, false);
8751   return SDValue();
8752 }
8753
8754 static SDValue PerformANDCombine(SDNode *N,
8755                                  TargetLowering::DAGCombinerInfo &DCI,
8756                                  const ARMSubtarget *Subtarget) {
8757
8758   // Attempt to use immediate-form VBIC
8759   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8760   SDLoc dl(N);
8761   EVT VT = N->getValueType(0);
8762   SelectionDAG &DAG = DCI.DAG;
8763
8764   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8765     return SDValue();
8766
8767   APInt SplatBits, SplatUndef;
8768   unsigned SplatBitSize;
8769   bool HasAnyUndefs;
8770   if (BVN &&
8771       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8772     if (SplatBitSize <= 64) {
8773       EVT VbicVT;
8774       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8775                                       SplatUndef.getZExtValue(), SplatBitSize,
8776                                       DAG, dl, VbicVT, VT.is128BitVector(),
8777                                       OtherModImm);
8778       if (Val.getNode()) {
8779         SDValue Input =
8780           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8781         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8782         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8783       }
8784     }
8785   }
8786
8787   if (!Subtarget->isThumb1Only()) {
8788     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8789     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8790     if (Result.getNode())
8791       return Result;
8792   }
8793
8794   return SDValue();
8795 }
8796
8797 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8798 static SDValue PerformORCombine(SDNode *N,
8799                                 TargetLowering::DAGCombinerInfo &DCI,
8800                                 const ARMSubtarget *Subtarget) {
8801   // Attempt to use immediate-form VORR
8802   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8803   SDLoc dl(N);
8804   EVT VT = N->getValueType(0);
8805   SelectionDAG &DAG = DCI.DAG;
8806
8807   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8808     return SDValue();
8809
8810   APInt SplatBits, SplatUndef;
8811   unsigned SplatBitSize;
8812   bool HasAnyUndefs;
8813   if (BVN && Subtarget->hasNEON() &&
8814       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8815     if (SplatBitSize <= 64) {
8816       EVT VorrVT;
8817       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8818                                       SplatUndef.getZExtValue(), SplatBitSize,
8819                                       DAG, dl, VorrVT, VT.is128BitVector(),
8820                                       OtherModImm);
8821       if (Val.getNode()) {
8822         SDValue Input =
8823           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8824         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8825         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8826       }
8827     }
8828   }
8829
8830   if (!Subtarget->isThumb1Only()) {
8831     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8832     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8833     if (Result.getNode())
8834       return Result;
8835   }
8836
8837   // The code below optimizes (or (and X, Y), Z).
8838   // The AND operand needs to have a single user to make these optimizations
8839   // profitable.
8840   SDValue N0 = N->getOperand(0);
8841   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8842     return SDValue();
8843   SDValue N1 = N->getOperand(1);
8844
8845   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8846   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8847       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8848     APInt SplatUndef;
8849     unsigned SplatBitSize;
8850     bool HasAnyUndefs;
8851
8852     APInt SplatBits0, SplatBits1;
8853     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8854     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8855     // Ensure that the second operand of both ands are constants
8856     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8857                                       HasAnyUndefs) && !HasAnyUndefs) {
8858         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8859                                           HasAnyUndefs) && !HasAnyUndefs) {
8860             // Ensure that the bit width of the constants are the same and that
8861             // the splat arguments are logical inverses as per the pattern we
8862             // are trying to simplify.
8863             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8864                 SplatBits0 == ~SplatBits1) {
8865                 // Canonicalize the vector type to make instruction selection
8866                 // simpler.
8867                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8868                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8869                                              N0->getOperand(1),
8870                                              N0->getOperand(0),
8871                                              N1->getOperand(0));
8872                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8873             }
8874         }
8875     }
8876   }
8877
8878   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8879   // reasonable.
8880
8881   // BFI is only available on V6T2+
8882   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8883     return SDValue();
8884
8885   SDLoc DL(N);
8886   // 1) or (and A, mask), val => ARMbfi A, val, mask
8887   //      iff (val & mask) == val
8888   //
8889   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8890   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8891   //          && mask == ~mask2
8892   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8893   //          && ~mask == mask2
8894   //  (i.e., copy a bitfield value into another bitfield of the same width)
8895
8896   if (VT != MVT::i32)
8897     return SDValue();
8898
8899   SDValue N00 = N0.getOperand(0);
8900
8901   // The value and the mask need to be constants so we can verify this is
8902   // actually a bitfield set. If the mask is 0xffff, we can do better
8903   // via a movt instruction, so don't use BFI in that case.
8904   SDValue MaskOp = N0.getOperand(1);
8905   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8906   if (!MaskC)
8907     return SDValue();
8908   unsigned Mask = MaskC->getZExtValue();
8909   if (Mask == 0xffff)
8910     return SDValue();
8911   SDValue Res;
8912   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8913   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8914   if (N1C) {
8915     unsigned Val = N1C->getZExtValue();
8916     if ((Val & ~Mask) != Val)
8917       return SDValue();
8918
8919     if (ARM::isBitFieldInvertedMask(Mask)) {
8920       Val >>= countTrailingZeros(~Mask);
8921
8922       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8923                         DAG.getConstant(Val, DL, MVT::i32),
8924                         DAG.getConstant(Mask, DL, MVT::i32));
8925
8926       // Do not add new nodes to DAG combiner worklist.
8927       DCI.CombineTo(N, Res, false);
8928       return SDValue();
8929     }
8930   } else if (N1.getOpcode() == ISD::AND) {
8931     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8932     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8933     if (!N11C)
8934       return SDValue();
8935     unsigned Mask2 = N11C->getZExtValue();
8936
8937     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8938     // as is to match.
8939     if (ARM::isBitFieldInvertedMask(Mask) &&
8940         (Mask == ~Mask2)) {
8941       // The pack halfword instruction works better for masks that fit it,
8942       // so use that when it's available.
8943       if (Subtarget->hasT2ExtractPack() &&
8944           (Mask == 0xffff || Mask == 0xffff0000))
8945         return SDValue();
8946       // 2a
8947       unsigned amt = countTrailingZeros(Mask2);
8948       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8949                         DAG.getConstant(amt, DL, MVT::i32));
8950       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8951                         DAG.getConstant(Mask, DL, MVT::i32));
8952       // Do not add new nodes to DAG combiner worklist.
8953       DCI.CombineTo(N, Res, false);
8954       return SDValue();
8955     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8956                (~Mask == Mask2)) {
8957       // The pack halfword instruction works better for masks that fit it,
8958       // so use that when it's available.
8959       if (Subtarget->hasT2ExtractPack() &&
8960           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8961         return SDValue();
8962       // 2b
8963       unsigned lsb = countTrailingZeros(Mask);
8964       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8965                         DAG.getConstant(lsb, DL, MVT::i32));
8966       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8967                         DAG.getConstant(Mask2, DL, MVT::i32));
8968       // Do not add new nodes to DAG combiner worklist.
8969       DCI.CombineTo(N, Res, false);
8970       return SDValue();
8971     }
8972   }
8973
8974   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8975       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8976       ARM::isBitFieldInvertedMask(~Mask)) {
8977     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8978     // where lsb(mask) == #shamt and masked bits of B are known zero.
8979     SDValue ShAmt = N00.getOperand(1);
8980     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8981     unsigned LSB = countTrailingZeros(Mask);
8982     if (ShAmtC != LSB)
8983       return SDValue();
8984
8985     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8986                       DAG.getConstant(~Mask, DL, MVT::i32));
8987
8988     // Do not add new nodes to DAG combiner worklist.
8989     DCI.CombineTo(N, Res, false);
8990   }
8991
8992   return SDValue();
8993 }
8994
8995 static SDValue PerformXORCombine(SDNode *N,
8996                                  TargetLowering::DAGCombinerInfo &DCI,
8997                                  const ARMSubtarget *Subtarget) {
8998   EVT VT = N->getValueType(0);
8999   SelectionDAG &DAG = DCI.DAG;
9000
9001   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9002     return SDValue();
9003
9004   if (!Subtarget->isThumb1Only()) {
9005     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9006     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9007     if (Result.getNode())
9008       return Result;
9009   }
9010
9011   return SDValue();
9012 }
9013
9014 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9015 /// the bits being cleared by the AND are not demanded by the BFI.
9016 static SDValue PerformBFICombine(SDNode *N,
9017                                  TargetLowering::DAGCombinerInfo &DCI) {
9018   SDValue N1 = N->getOperand(1);
9019   if (N1.getOpcode() == ISD::AND) {
9020     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9021     if (!N11C)
9022       return SDValue();
9023     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9024     unsigned LSB = countTrailingZeros(~InvMask);
9025     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9026     assert(Width <
9027                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9028            "undefined behavior");
9029     unsigned Mask = (1u << Width) - 1;
9030     unsigned Mask2 = N11C->getZExtValue();
9031     if ((Mask & (~Mask2)) == 0)
9032       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9033                              N->getOperand(0), N1.getOperand(0),
9034                              N->getOperand(2));
9035   }
9036   return SDValue();
9037 }
9038
9039 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9040 /// ARMISD::VMOVRRD.
9041 static SDValue PerformVMOVRRDCombine(SDNode *N,
9042                                      TargetLowering::DAGCombinerInfo &DCI,
9043                                      const ARMSubtarget *Subtarget) {
9044   // vmovrrd(vmovdrr x, y) -> x,y
9045   SDValue InDouble = N->getOperand(0);
9046   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
9047     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9048
9049   // vmovrrd(load f64) -> (load i32), (load i32)
9050   SDNode *InNode = InDouble.getNode();
9051   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9052       InNode->getValueType(0) == MVT::f64 &&
9053       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9054       !cast<LoadSDNode>(InNode)->isVolatile()) {
9055     // TODO: Should this be done for non-FrameIndex operands?
9056     LoadSDNode *LD = cast<LoadSDNode>(InNode);
9057
9058     SelectionDAG &DAG = DCI.DAG;
9059     SDLoc DL(LD);
9060     SDValue BasePtr = LD->getBasePtr();
9061     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9062                                  LD->getPointerInfo(), LD->isVolatile(),
9063                                  LD->isNonTemporal(), LD->isInvariant(),
9064                                  LD->getAlignment());
9065
9066     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9067                                     DAG.getConstant(4, DL, MVT::i32));
9068     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9069                                  LD->getPointerInfo(), LD->isVolatile(),
9070                                  LD->isNonTemporal(), LD->isInvariant(),
9071                                  std::min(4U, LD->getAlignment() / 2));
9072
9073     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9074     if (DCI.DAG.getDataLayout().isBigEndian())
9075       std::swap (NewLD1, NewLD2);
9076     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9077     return Result;
9078   }
9079
9080   return SDValue();
9081 }
9082
9083 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9084 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
9085 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9086   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9087   SDValue Op0 = N->getOperand(0);
9088   SDValue Op1 = N->getOperand(1);
9089   if (Op0.getOpcode() == ISD::BITCAST)
9090     Op0 = Op0.getOperand(0);
9091   if (Op1.getOpcode() == ISD::BITCAST)
9092     Op1 = Op1.getOperand(0);
9093   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9094       Op0.getNode() == Op1.getNode() &&
9095       Op0.getResNo() == 0 && Op1.getResNo() == 1)
9096     return DAG.getNode(ISD::BITCAST, SDLoc(N),
9097                        N->getValueType(0), Op0.getOperand(0));
9098   return SDValue();
9099 }
9100
9101 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9102 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9103 /// i64 vector to have f64 elements, since the value can then be loaded
9104 /// directly into a VFP register.
9105 static bool hasNormalLoadOperand(SDNode *N) {
9106   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9107   for (unsigned i = 0; i < NumElts; ++i) {
9108     SDNode *Elt = N->getOperand(i).getNode();
9109     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9110       return true;
9111   }
9112   return false;
9113 }
9114
9115 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9116 /// ISD::BUILD_VECTOR.
9117 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9118                                           TargetLowering::DAGCombinerInfo &DCI,
9119                                           const ARMSubtarget *Subtarget) {
9120   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9121   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9122   // into a pair of GPRs, which is fine when the value is used as a scalar,
9123   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9124   SelectionDAG &DAG = DCI.DAG;
9125   if (N->getNumOperands() == 2) {
9126     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9127     if (RV.getNode())
9128       return RV;
9129   }
9130
9131   // Load i64 elements as f64 values so that type legalization does not split
9132   // them up into i32 values.
9133   EVT VT = N->getValueType(0);
9134   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9135     return SDValue();
9136   SDLoc dl(N);
9137   SmallVector<SDValue, 8> Ops;
9138   unsigned NumElts = VT.getVectorNumElements();
9139   for (unsigned i = 0; i < NumElts; ++i) {
9140     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9141     Ops.push_back(V);
9142     // Make the DAGCombiner fold the bitcast.
9143     DCI.AddToWorklist(V.getNode());
9144   }
9145   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9146   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9147   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9148 }
9149
9150 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9151 static SDValue
9152 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9153   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9154   // At that time, we may have inserted bitcasts from integer to float.
9155   // If these bitcasts have survived DAGCombine, change the lowering of this
9156   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9157   // force to use floating point types.
9158
9159   // Make sure we can change the type of the vector.
9160   // This is possible iff:
9161   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9162   //    1.1. Vector is used only once.
9163   //    1.2. Use is a bit convert to an integer type.
9164   // 2. The size of its operands are 32-bits (64-bits are not legal).
9165   EVT VT = N->getValueType(0);
9166   EVT EltVT = VT.getVectorElementType();
9167
9168   // Check 1.1. and 2.
9169   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9170     return SDValue();
9171
9172   // By construction, the input type must be float.
9173   assert(EltVT == MVT::f32 && "Unexpected type!");
9174
9175   // Check 1.2.
9176   SDNode *Use = *N->use_begin();
9177   if (Use->getOpcode() != ISD::BITCAST ||
9178       Use->getValueType(0).isFloatingPoint())
9179     return SDValue();
9180
9181   // Check profitability.
9182   // Model is, if more than half of the relevant operands are bitcast from
9183   // i32, turn the build_vector into a sequence of insert_vector_elt.
9184   // Relevant operands are everything that is not statically
9185   // (i.e., at compile time) bitcasted.
9186   unsigned NumOfBitCastedElts = 0;
9187   unsigned NumElts = VT.getVectorNumElements();
9188   unsigned NumOfRelevantElts = NumElts;
9189   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9190     SDValue Elt = N->getOperand(Idx);
9191     if (Elt->getOpcode() == ISD::BITCAST) {
9192       // Assume only bit cast to i32 will go away.
9193       if (Elt->getOperand(0).getValueType() == MVT::i32)
9194         ++NumOfBitCastedElts;
9195     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9196       // Constants are statically casted, thus do not count them as
9197       // relevant operands.
9198       --NumOfRelevantElts;
9199   }
9200
9201   // Check if more than half of the elements require a non-free bitcast.
9202   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9203     return SDValue();
9204
9205   SelectionDAG &DAG = DCI.DAG;
9206   // Create the new vector type.
9207   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9208   // Check if the type is legal.
9209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9210   if (!TLI.isTypeLegal(VecVT))
9211     return SDValue();
9212
9213   // Combine:
9214   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9215   // => BITCAST INSERT_VECTOR_ELT
9216   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9217   //                      (BITCAST EN), N.
9218   SDValue Vec = DAG.getUNDEF(VecVT);
9219   SDLoc dl(N);
9220   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9221     SDValue V = N->getOperand(Idx);
9222     if (V.getOpcode() == ISD::UNDEF)
9223       continue;
9224     if (V.getOpcode() == ISD::BITCAST &&
9225         V->getOperand(0).getValueType() == MVT::i32)
9226       // Fold obvious case.
9227       V = V.getOperand(0);
9228     else {
9229       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9230       // Make the DAGCombiner fold the bitcasts.
9231       DCI.AddToWorklist(V.getNode());
9232     }
9233     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9234     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9235   }
9236   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9237   // Make the DAGCombiner fold the bitcasts.
9238   DCI.AddToWorklist(Vec.getNode());
9239   return Vec;
9240 }
9241
9242 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9243 /// ISD::INSERT_VECTOR_ELT.
9244 static SDValue PerformInsertEltCombine(SDNode *N,
9245                                        TargetLowering::DAGCombinerInfo &DCI) {
9246   // Bitcast an i64 load inserted into a vector to f64.
9247   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9248   EVT VT = N->getValueType(0);
9249   SDNode *Elt = N->getOperand(1).getNode();
9250   if (VT.getVectorElementType() != MVT::i64 ||
9251       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9252     return SDValue();
9253
9254   SelectionDAG &DAG = DCI.DAG;
9255   SDLoc dl(N);
9256   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9257                                  VT.getVectorNumElements());
9258   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9259   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9260   // Make the DAGCombiner fold the bitcasts.
9261   DCI.AddToWorklist(Vec.getNode());
9262   DCI.AddToWorklist(V.getNode());
9263   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9264                                Vec, V, N->getOperand(2));
9265   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9266 }
9267
9268 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9269 /// ISD::VECTOR_SHUFFLE.
9270 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9271   // The LLVM shufflevector instruction does not require the shuffle mask
9272   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9273   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9274   // operands do not match the mask length, they are extended by concatenating
9275   // them with undef vectors.  That is probably the right thing for other
9276   // targets, but for NEON it is better to concatenate two double-register
9277   // size vector operands into a single quad-register size vector.  Do that
9278   // transformation here:
9279   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9280   //   shuffle(concat(v1, v2), undef)
9281   SDValue Op0 = N->getOperand(0);
9282   SDValue Op1 = N->getOperand(1);
9283   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9284       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9285       Op0.getNumOperands() != 2 ||
9286       Op1.getNumOperands() != 2)
9287     return SDValue();
9288   SDValue Concat0Op1 = Op0.getOperand(1);
9289   SDValue Concat1Op1 = Op1.getOperand(1);
9290   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9291       Concat1Op1.getOpcode() != ISD::UNDEF)
9292     return SDValue();
9293   // Skip the transformation if any of the types are illegal.
9294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9295   EVT VT = N->getValueType(0);
9296   if (!TLI.isTypeLegal(VT) ||
9297       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9298       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9299     return SDValue();
9300
9301   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9302                                   Op0.getOperand(0), Op1.getOperand(0));
9303   // Translate the shuffle mask.
9304   SmallVector<int, 16> NewMask;
9305   unsigned NumElts = VT.getVectorNumElements();
9306   unsigned HalfElts = NumElts/2;
9307   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9308   for (unsigned n = 0; n < NumElts; ++n) {
9309     int MaskElt = SVN->getMaskElt(n);
9310     int NewElt = -1;
9311     if (MaskElt < (int)HalfElts)
9312       NewElt = MaskElt;
9313     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9314       NewElt = HalfElts + MaskElt - NumElts;
9315     NewMask.push_back(NewElt);
9316   }
9317   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9318                               DAG.getUNDEF(VT), NewMask.data());
9319 }
9320
9321 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9322 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9323 /// base address updates.
9324 /// For generic load/stores, the memory type is assumed to be a vector.
9325 /// The caller is assumed to have checked legality.
9326 static SDValue CombineBaseUpdate(SDNode *N,
9327                                  TargetLowering::DAGCombinerInfo &DCI) {
9328   SelectionDAG &DAG = DCI.DAG;
9329   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9330                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9331   const bool isStore = N->getOpcode() == ISD::STORE;
9332   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9333   SDValue Addr = N->getOperand(AddrOpIdx);
9334   MemSDNode *MemN = cast<MemSDNode>(N);
9335   SDLoc dl(N);
9336
9337   // Search for a use of the address operand that is an increment.
9338   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9339          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9340     SDNode *User = *UI;
9341     if (User->getOpcode() != ISD::ADD ||
9342         UI.getUse().getResNo() != Addr.getResNo())
9343       continue;
9344
9345     // Check that the add is independent of the load/store.  Otherwise, folding
9346     // it would create a cycle.
9347     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9348       continue;
9349
9350     // Find the new opcode for the updating load/store.
9351     bool isLoadOp = true;
9352     bool isLaneOp = false;
9353     unsigned NewOpc = 0;
9354     unsigned NumVecs = 0;
9355     if (isIntrinsic) {
9356       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9357       switch (IntNo) {
9358       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9359       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9360         NumVecs = 1; break;
9361       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9362         NumVecs = 2; break;
9363       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9364         NumVecs = 3; break;
9365       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9366         NumVecs = 4; break;
9367       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9368         NumVecs = 2; isLaneOp = true; break;
9369       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9370         NumVecs = 3; isLaneOp = true; break;
9371       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9372         NumVecs = 4; isLaneOp = true; break;
9373       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9374         NumVecs = 1; isLoadOp = false; break;
9375       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9376         NumVecs = 2; isLoadOp = false; break;
9377       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9378         NumVecs = 3; isLoadOp = false; break;
9379       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9380         NumVecs = 4; isLoadOp = false; break;
9381       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9382         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9383       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9384         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9385       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9386         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9387       }
9388     } else {
9389       isLaneOp = true;
9390       switch (N->getOpcode()) {
9391       default: llvm_unreachable("unexpected opcode for Neon base update");
9392       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9393       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9394       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9395       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9396         NumVecs = 1; isLaneOp = false; break;
9397       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9398         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9399       }
9400     }
9401
9402     // Find the size of memory referenced by the load/store.
9403     EVT VecTy;
9404     if (isLoadOp) {
9405       VecTy = N->getValueType(0);
9406     } else if (isIntrinsic) {
9407       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9408     } else {
9409       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9410       VecTy = N->getOperand(1).getValueType();
9411     }
9412
9413     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9414     if (isLaneOp)
9415       NumBytes /= VecTy.getVectorNumElements();
9416
9417     // If the increment is a constant, it must match the memory ref size.
9418     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9419     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9420       uint64_t IncVal = CInc->getZExtValue();
9421       if (IncVal != NumBytes)
9422         continue;
9423     } else if (NumBytes >= 3 * 16) {
9424       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9425       // separate instructions that make it harder to use a non-constant update.
9426       continue;
9427     }
9428
9429     // OK, we found an ADD we can fold into the base update.
9430     // Now, create a _UPD node, taking care of not breaking alignment.
9431
9432     EVT AlignedVecTy = VecTy;
9433     unsigned Alignment = MemN->getAlignment();
9434
9435     // If this is a less-than-standard-aligned load/store, change the type to
9436     // match the standard alignment.
9437     // The alignment is overlooked when selecting _UPD variants; and it's
9438     // easier to introduce bitcasts here than fix that.
9439     // There are 3 ways to get to this base-update combine:
9440     // - intrinsics: they are assumed to be properly aligned (to the standard
9441     //   alignment of the memory type), so we don't need to do anything.
9442     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9443     //   intrinsics, so, likewise, there's nothing to do.
9444     // - generic load/store instructions: the alignment is specified as an
9445     //   explicit operand, rather than implicitly as the standard alignment
9446     //   of the memory type (like the intrisics).  We need to change the
9447     //   memory type to match the explicit alignment.  That way, we don't
9448     //   generate non-standard-aligned ARMISD::VLDx nodes.
9449     if (isa<LSBaseSDNode>(N)) {
9450       if (Alignment == 0)
9451         Alignment = 1;
9452       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9453         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9454         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9455         assert(!isLaneOp && "Unexpected generic load/store lane.");
9456         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9457         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9458       }
9459       // Don't set an explicit alignment on regular load/stores that we want
9460       // to transform to VLD/VST 1_UPD nodes.
9461       // This matches the behavior of regular load/stores, which only get an
9462       // explicit alignment if the MMO alignment is larger than the standard
9463       // alignment of the memory type.
9464       // Intrinsics, however, always get an explicit alignment, set to the
9465       // alignment of the MMO.
9466       Alignment = 1;
9467     }
9468
9469     // Create the new updating load/store node.
9470     // First, create an SDVTList for the new updating node's results.
9471     EVT Tys[6];
9472     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9473     unsigned n;
9474     for (n = 0; n < NumResultVecs; ++n)
9475       Tys[n] = AlignedVecTy;
9476     Tys[n++] = MVT::i32;
9477     Tys[n] = MVT::Other;
9478     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9479
9480     // Then, gather the new node's operands.
9481     SmallVector<SDValue, 8> Ops;
9482     Ops.push_back(N->getOperand(0)); // incoming chain
9483     Ops.push_back(N->getOperand(AddrOpIdx));
9484     Ops.push_back(Inc);
9485
9486     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9487       // Try to match the intrinsic's signature
9488       Ops.push_back(StN->getValue());
9489     } else {
9490       // Loads (and of course intrinsics) match the intrinsics' signature,
9491       // so just add all but the alignment operand.
9492       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9493         Ops.push_back(N->getOperand(i));
9494     }
9495
9496     // For all node types, the alignment operand is always the last one.
9497     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9498
9499     // If this is a non-standard-aligned STORE, the penultimate operand is the
9500     // stored value.  Bitcast it to the aligned type.
9501     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9502       SDValue &StVal = Ops[Ops.size()-2];
9503       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9504     }
9505
9506     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9507                                            Ops, AlignedVecTy,
9508                                            MemN->getMemOperand());
9509
9510     // Update the uses.
9511     SmallVector<SDValue, 5> NewResults;
9512     for (unsigned i = 0; i < NumResultVecs; ++i)
9513       NewResults.push_back(SDValue(UpdN.getNode(), i));
9514
9515     // If this is an non-standard-aligned LOAD, the first result is the loaded
9516     // value.  Bitcast it to the expected result type.
9517     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9518       SDValue &LdVal = NewResults[0];
9519       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9520     }
9521
9522     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9523     DCI.CombineTo(N, NewResults);
9524     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9525
9526     break;
9527   }
9528   return SDValue();
9529 }
9530
9531 static SDValue PerformVLDCombine(SDNode *N,
9532                                  TargetLowering::DAGCombinerInfo &DCI) {
9533   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9534     return SDValue();
9535
9536   return CombineBaseUpdate(N, DCI);
9537 }
9538
9539 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9540 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9541 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9542 /// return true.
9543 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9544   SelectionDAG &DAG = DCI.DAG;
9545   EVT VT = N->getValueType(0);
9546   // vldN-dup instructions only support 64-bit vectors for N > 1.
9547   if (!VT.is64BitVector())
9548     return false;
9549
9550   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9551   SDNode *VLD = N->getOperand(0).getNode();
9552   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9553     return false;
9554   unsigned NumVecs = 0;
9555   unsigned NewOpc = 0;
9556   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9557   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9558     NumVecs = 2;
9559     NewOpc = ARMISD::VLD2DUP;
9560   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9561     NumVecs = 3;
9562     NewOpc = ARMISD::VLD3DUP;
9563   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9564     NumVecs = 4;
9565     NewOpc = ARMISD::VLD4DUP;
9566   } else {
9567     return false;
9568   }
9569
9570   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9571   // numbers match the load.
9572   unsigned VLDLaneNo =
9573     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9574   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9575        UI != UE; ++UI) {
9576     // Ignore uses of the chain result.
9577     if (UI.getUse().getResNo() == NumVecs)
9578       continue;
9579     SDNode *User = *UI;
9580     if (User->getOpcode() != ARMISD::VDUPLANE ||
9581         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9582       return false;
9583   }
9584
9585   // Create the vldN-dup node.
9586   EVT Tys[5];
9587   unsigned n;
9588   for (n = 0; n < NumVecs; ++n)
9589     Tys[n] = VT;
9590   Tys[n] = MVT::Other;
9591   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9592   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9593   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9594   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9595                                            Ops, VLDMemInt->getMemoryVT(),
9596                                            VLDMemInt->getMemOperand());
9597
9598   // Update the uses.
9599   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9600        UI != UE; ++UI) {
9601     unsigned ResNo = UI.getUse().getResNo();
9602     // Ignore uses of the chain result.
9603     if (ResNo == NumVecs)
9604       continue;
9605     SDNode *User = *UI;
9606     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9607   }
9608
9609   // Now the vldN-lane intrinsic is dead except for its chain result.
9610   // Update uses of the chain.
9611   std::vector<SDValue> VLDDupResults;
9612   for (unsigned n = 0; n < NumVecs; ++n)
9613     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9614   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9615   DCI.CombineTo(VLD, VLDDupResults);
9616
9617   return true;
9618 }
9619
9620 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9621 /// ARMISD::VDUPLANE.
9622 static SDValue PerformVDUPLANECombine(SDNode *N,
9623                                       TargetLowering::DAGCombinerInfo &DCI) {
9624   SDValue Op = N->getOperand(0);
9625
9626   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9627   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9628   if (CombineVLDDUP(N, DCI))
9629     return SDValue(N, 0);
9630
9631   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9632   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9633   while (Op.getOpcode() == ISD::BITCAST)
9634     Op = Op.getOperand(0);
9635   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9636     return SDValue();
9637
9638   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9639   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9640   // The canonical VMOV for a zero vector uses a 32-bit element size.
9641   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9642   unsigned EltBits;
9643   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9644     EltSize = 8;
9645   EVT VT = N->getValueType(0);
9646   if (EltSize > VT.getVectorElementType().getSizeInBits())
9647     return SDValue();
9648
9649   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9650 }
9651
9652 static SDValue PerformLOADCombine(SDNode *N,
9653                                   TargetLowering::DAGCombinerInfo &DCI) {
9654   EVT VT = N->getValueType(0);
9655
9656   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9657   if (ISD::isNormalLoad(N) && VT.isVector() &&
9658       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9659     return CombineBaseUpdate(N, DCI);
9660
9661   return SDValue();
9662 }
9663
9664 /// PerformSTORECombine - Target-specific dag combine xforms for
9665 /// ISD::STORE.
9666 static SDValue PerformSTORECombine(SDNode *N,
9667                                    TargetLowering::DAGCombinerInfo &DCI) {
9668   StoreSDNode *St = cast<StoreSDNode>(N);
9669   if (St->isVolatile())
9670     return SDValue();
9671
9672   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9673   // pack all of the elements in one place.  Next, store to memory in fewer
9674   // chunks.
9675   SDValue StVal = St->getValue();
9676   EVT VT = StVal.getValueType();
9677   if (St->isTruncatingStore() && VT.isVector()) {
9678     SelectionDAG &DAG = DCI.DAG;
9679     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9680     EVT StVT = St->getMemoryVT();
9681     unsigned NumElems = VT.getVectorNumElements();
9682     assert(StVT != VT && "Cannot truncate to the same type");
9683     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9684     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9685
9686     // From, To sizes and ElemCount must be pow of two
9687     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9688
9689     // We are going to use the original vector elt for storing.
9690     // Accumulated smaller vector elements must be a multiple of the store size.
9691     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9692
9693     unsigned SizeRatio  = FromEltSz / ToEltSz;
9694     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9695
9696     // Create a type on which we perform the shuffle.
9697     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9698                                      NumElems*SizeRatio);
9699     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9700
9701     SDLoc DL(St);
9702     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9703     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9704     for (unsigned i = 0; i < NumElems; ++i)
9705       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9706                           ? (i + 1) * SizeRatio - 1
9707                           : i * SizeRatio;
9708
9709     // Can't shuffle using an illegal type.
9710     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9711
9712     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9713                                 DAG.getUNDEF(WideVec.getValueType()),
9714                                 ShuffleVec.data());
9715     // At this point all of the data is stored at the bottom of the
9716     // register. We now need to save it to mem.
9717
9718     // Find the largest store unit
9719     MVT StoreType = MVT::i8;
9720     for (MVT Tp : MVT::integer_valuetypes()) {
9721       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9722         StoreType = Tp;
9723     }
9724     // Didn't find a legal store type.
9725     if (!TLI.isTypeLegal(StoreType))
9726       return SDValue();
9727
9728     // Bitcast the original vector into a vector of store-size units
9729     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9730             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9731     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9732     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9733     SmallVector<SDValue, 8> Chains;
9734     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9735                                         TLI.getPointerTy(DAG.getDataLayout()));
9736     SDValue BasePtr = St->getBasePtr();
9737
9738     // Perform one or more big stores into memory.
9739     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9740     for (unsigned I = 0; I < E; I++) {
9741       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9742                                    StoreType, ShuffWide,
9743                                    DAG.getIntPtrConstant(I, DL));
9744       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9745                                 St->getPointerInfo(), St->isVolatile(),
9746                                 St->isNonTemporal(), St->getAlignment());
9747       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9748                             Increment);
9749       Chains.push_back(Ch);
9750     }
9751     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9752   }
9753
9754   if (!ISD::isNormalStore(St))
9755     return SDValue();
9756
9757   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9758   // ARM stores of arguments in the same cache line.
9759   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9760       StVal.getNode()->hasOneUse()) {
9761     SelectionDAG  &DAG = DCI.DAG;
9762     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9763     SDLoc DL(St);
9764     SDValue BasePtr = St->getBasePtr();
9765     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9766                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9767                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9768                                   St->isNonTemporal(), St->getAlignment());
9769
9770     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9771                                     DAG.getConstant(4, DL, MVT::i32));
9772     return DAG.getStore(NewST1.getValue(0), DL,
9773                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9774                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9775                         St->isNonTemporal(),
9776                         std::min(4U, St->getAlignment() / 2));
9777   }
9778
9779   if (StVal.getValueType() == MVT::i64 &&
9780       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9781
9782     // Bitcast an i64 store extracted from a vector to f64.
9783     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9784     SelectionDAG &DAG = DCI.DAG;
9785     SDLoc dl(StVal);
9786     SDValue IntVec = StVal.getOperand(0);
9787     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9788                                    IntVec.getValueType().getVectorNumElements());
9789     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9790     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9791                                  Vec, StVal.getOperand(1));
9792     dl = SDLoc(N);
9793     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9794     // Make the DAGCombiner fold the bitcasts.
9795     DCI.AddToWorklist(Vec.getNode());
9796     DCI.AddToWorklist(ExtElt.getNode());
9797     DCI.AddToWorklist(V.getNode());
9798     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9799                         St->getPointerInfo(), St->isVolatile(),
9800                         St->isNonTemporal(), St->getAlignment(),
9801                         St->getAAInfo());
9802   }
9803
9804   // If this is a legal vector store, try to combine it into a VST1_UPD.
9805   if (ISD::isNormalStore(N) && VT.isVector() &&
9806       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9807     return CombineBaseUpdate(N, DCI);
9808
9809   return SDValue();
9810 }
9811
9812 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9813 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9814 /// when the VMUL has a constant operand that is a power of 2.
9815 ///
9816 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9817 ///  vmul.f32        d16, d17, d16
9818 ///  vcvt.s32.f32    d16, d16
9819 /// becomes:
9820 ///  vcvt.s32.f32    d16, d16, #3
9821 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
9822                                   const ARMSubtarget *Subtarget) {
9823   if (!Subtarget->hasNEON())
9824     return SDValue();
9825
9826   SDValue Op = N->getOperand(0);
9827   if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
9828     return SDValue();
9829
9830   SDValue ConstVec = Op->getOperand(1);
9831   if (!isa<BuildVectorSDNode>(ConstVec))
9832     return SDValue();
9833
9834   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9835   uint32_t FloatBits = FloatTy.getSizeInBits();
9836   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9837   uint32_t IntBits = IntTy.getSizeInBits();
9838   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9839   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9840     // These instructions only exist converting from f32 to i32. We can handle
9841     // smaller integers by generating an extra truncate, but larger ones would
9842     // be lossy. We also can't handle more then 4 lanes, since these intructions
9843     // only support v2i32/v4i32 types.
9844     return SDValue();
9845   }
9846
9847   BitVector UndefElements;
9848   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9849   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9850   if (C == -1 || C == 0 || C > 32)
9851     return SDValue();
9852
9853   SDLoc dl(N);
9854   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9855   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9856     Intrinsic::arm_neon_vcvtfp2fxu;
9857   SDValue FixConv = DAG.getNode(
9858       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9859       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
9860       DAG.getConstant(C, dl, MVT::i32));
9861
9862   if (IntBits < FloatBits)
9863     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9864
9865   return FixConv;
9866 }
9867
9868 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9869 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9870 /// when the VDIV has a constant operand that is a power of 2.
9871 ///
9872 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9873 ///  vcvt.f32.s32    d16, d16
9874 ///  vdiv.f32        d16, d17, d16
9875 /// becomes:
9876 ///  vcvt.f32.s32    d16, d16, #3
9877 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
9878                                   const ARMSubtarget *Subtarget) {
9879   if (!Subtarget->hasNEON())
9880     return SDValue();
9881
9882   SDValue Op = N->getOperand(0);
9883   unsigned OpOpcode = Op.getNode()->getOpcode();
9884   if (!N->getValueType(0).isVector() ||
9885       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9886     return SDValue();
9887
9888   SDValue ConstVec = N->getOperand(1);
9889   if (!isa<BuildVectorSDNode>(ConstVec))
9890     return SDValue();
9891
9892   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9893   uint32_t FloatBits = FloatTy.getSizeInBits();
9894   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9895   uint32_t IntBits = IntTy.getSizeInBits();
9896   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9897   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
9898     // These instructions only exist converting from i32 to f32. We can handle
9899     // smaller integers by generating an extra extend, but larger ones would
9900     // be lossy. We also can't handle more then 4 lanes, since these intructions
9901     // only support v2i32/v4i32 types.
9902     return SDValue();
9903   }
9904
9905   BitVector UndefElements;
9906   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9907   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
9908   if (C == -1 || C == 0 || C > 32)
9909     return SDValue();
9910
9911   SDLoc dl(N);
9912   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9913   SDValue ConvInput = Op.getOperand(0);
9914   if (IntBits < FloatBits)
9915     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9916                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9917                             ConvInput);
9918
9919   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9920     Intrinsic::arm_neon_vcvtfxu2fp;
9921   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9922                      Op.getValueType(),
9923                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9924                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
9925 }
9926
9927 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9928 /// operand of a vector shift operation, where all the elements of the
9929 /// build_vector must have the same constant integer value.
9930 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9931   // Ignore bit_converts.
9932   while (Op.getOpcode() == ISD::BITCAST)
9933     Op = Op.getOperand(0);
9934   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9935   APInt SplatBits, SplatUndef;
9936   unsigned SplatBitSize;
9937   bool HasAnyUndefs;
9938   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9939                                       HasAnyUndefs, ElementBits) ||
9940       SplatBitSize > ElementBits)
9941     return false;
9942   Cnt = SplatBits.getSExtValue();
9943   return true;
9944 }
9945
9946 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9947 /// operand of a vector shift left operation.  That value must be in the range:
9948 ///   0 <= Value < ElementBits for a left shift; or
9949 ///   0 <= Value <= ElementBits for a long left shift.
9950 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9951   assert(VT.isVector() && "vector shift count is not a vector type");
9952   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9953   if (! getVShiftImm(Op, ElementBits, Cnt))
9954     return false;
9955   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9956 }
9957
9958 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9959 /// operand of a vector shift right operation.  For a shift opcode, the value
9960 /// is positive, but for an intrinsic the value count must be negative. The
9961 /// absolute value must be in the range:
9962 ///   1 <= |Value| <= ElementBits for a right shift; or
9963 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9964 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9965                          int64_t &Cnt) {
9966   assert(VT.isVector() && "vector shift count is not a vector type");
9967   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9968   if (! getVShiftImm(Op, ElementBits, Cnt))
9969     return false;
9970   if (!isIntrinsic)
9971     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9972   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9973     Cnt = -Cnt;
9974     return true;
9975   }
9976   return false;
9977 }
9978
9979 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9980 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9981   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9982   switch (IntNo) {
9983   default:
9984     // Don't do anything for most intrinsics.
9985     break;
9986
9987   case Intrinsic::arm_neon_vabds:
9988     if (!N->getValueType(0).isInteger())
9989       return SDValue();
9990     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9991                        N->getOperand(1), N->getOperand(2));
9992   case Intrinsic::arm_neon_vabdu:
9993     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9994                        N->getOperand(1), N->getOperand(2));
9995
9996   // Vector shifts: check for immediate versions and lower them.
9997   // Note: This is done during DAG combining instead of DAG legalizing because
9998   // the build_vectors for 64-bit vector element shift counts are generally
9999   // not legal, and it is hard to see their values after they get legalized to
10000   // loads from a constant pool.
10001   case Intrinsic::arm_neon_vshifts:
10002   case Intrinsic::arm_neon_vshiftu:
10003   case Intrinsic::arm_neon_vrshifts:
10004   case Intrinsic::arm_neon_vrshiftu:
10005   case Intrinsic::arm_neon_vrshiftn:
10006   case Intrinsic::arm_neon_vqshifts:
10007   case Intrinsic::arm_neon_vqshiftu:
10008   case Intrinsic::arm_neon_vqshiftsu:
10009   case Intrinsic::arm_neon_vqshiftns:
10010   case Intrinsic::arm_neon_vqshiftnu:
10011   case Intrinsic::arm_neon_vqshiftnsu:
10012   case Intrinsic::arm_neon_vqrshiftns:
10013   case Intrinsic::arm_neon_vqrshiftnu:
10014   case Intrinsic::arm_neon_vqrshiftnsu: {
10015     EVT VT = N->getOperand(1).getValueType();
10016     int64_t Cnt;
10017     unsigned VShiftOpc = 0;
10018
10019     switch (IntNo) {
10020     case Intrinsic::arm_neon_vshifts:
10021     case Intrinsic::arm_neon_vshiftu:
10022       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10023         VShiftOpc = ARMISD::VSHL;
10024         break;
10025       }
10026       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10027         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10028                      ARMISD::VSHRs : ARMISD::VSHRu);
10029         break;
10030       }
10031       return SDValue();
10032
10033     case Intrinsic::arm_neon_vrshifts:
10034     case Intrinsic::arm_neon_vrshiftu:
10035       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10036         break;
10037       return SDValue();
10038
10039     case Intrinsic::arm_neon_vqshifts:
10040     case Intrinsic::arm_neon_vqshiftu:
10041       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10042         break;
10043       return SDValue();
10044
10045     case Intrinsic::arm_neon_vqshiftsu:
10046       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10047         break;
10048       llvm_unreachable("invalid shift count for vqshlu intrinsic");
10049
10050     case Intrinsic::arm_neon_vrshiftn:
10051     case Intrinsic::arm_neon_vqshiftns:
10052     case Intrinsic::arm_neon_vqshiftnu:
10053     case Intrinsic::arm_neon_vqshiftnsu:
10054     case Intrinsic::arm_neon_vqrshiftns:
10055     case Intrinsic::arm_neon_vqrshiftnu:
10056     case Intrinsic::arm_neon_vqrshiftnsu:
10057       // Narrowing shifts require an immediate right shift.
10058       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10059         break;
10060       llvm_unreachable("invalid shift count for narrowing vector shift "
10061                        "intrinsic");
10062
10063     default:
10064       llvm_unreachable("unhandled vector shift");
10065     }
10066
10067     switch (IntNo) {
10068     case Intrinsic::arm_neon_vshifts:
10069     case Intrinsic::arm_neon_vshiftu:
10070       // Opcode already set above.
10071       break;
10072     case Intrinsic::arm_neon_vrshifts:
10073       VShiftOpc = ARMISD::VRSHRs; break;
10074     case Intrinsic::arm_neon_vrshiftu:
10075       VShiftOpc = ARMISD::VRSHRu; break;
10076     case Intrinsic::arm_neon_vrshiftn:
10077       VShiftOpc = ARMISD::VRSHRN; break;
10078     case Intrinsic::arm_neon_vqshifts:
10079       VShiftOpc = ARMISD::VQSHLs; break;
10080     case Intrinsic::arm_neon_vqshiftu:
10081       VShiftOpc = ARMISD::VQSHLu; break;
10082     case Intrinsic::arm_neon_vqshiftsu:
10083       VShiftOpc = ARMISD::VQSHLsu; break;
10084     case Intrinsic::arm_neon_vqshiftns:
10085       VShiftOpc = ARMISD::VQSHRNs; break;
10086     case Intrinsic::arm_neon_vqshiftnu:
10087       VShiftOpc = ARMISD::VQSHRNu; break;
10088     case Intrinsic::arm_neon_vqshiftnsu:
10089       VShiftOpc = ARMISD::VQSHRNsu; break;
10090     case Intrinsic::arm_neon_vqrshiftns:
10091       VShiftOpc = ARMISD::VQRSHRNs; break;
10092     case Intrinsic::arm_neon_vqrshiftnu:
10093       VShiftOpc = ARMISD::VQRSHRNu; break;
10094     case Intrinsic::arm_neon_vqrshiftnsu:
10095       VShiftOpc = ARMISD::VQRSHRNsu; break;
10096     }
10097
10098     SDLoc dl(N);
10099     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10100                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10101   }
10102
10103   case Intrinsic::arm_neon_vshiftins: {
10104     EVT VT = N->getOperand(1).getValueType();
10105     int64_t Cnt;
10106     unsigned VShiftOpc = 0;
10107
10108     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10109       VShiftOpc = ARMISD::VSLI;
10110     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10111       VShiftOpc = ARMISD::VSRI;
10112     else {
10113       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10114     }
10115
10116     SDLoc dl(N);
10117     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10118                        N->getOperand(1), N->getOperand(2),
10119                        DAG.getConstant(Cnt, dl, MVT::i32));
10120   }
10121
10122   case Intrinsic::arm_neon_vqrshifts:
10123   case Intrinsic::arm_neon_vqrshiftu:
10124     // No immediate versions of these to check for.
10125     break;
10126   }
10127
10128   return SDValue();
10129 }
10130
10131 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10132 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10133 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10134 /// vector element shift counts are generally not legal, and it is hard to see
10135 /// their values after they get legalized to loads from a constant pool.
10136 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10137                                    const ARMSubtarget *ST) {
10138   EVT VT = N->getValueType(0);
10139   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10140     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10141     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10142     SDValue N1 = N->getOperand(1);
10143     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10144       SDValue N0 = N->getOperand(0);
10145       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10146           DAG.MaskedValueIsZero(N0.getOperand(0),
10147                                 APInt::getHighBitsSet(32, 16)))
10148         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10149     }
10150   }
10151
10152   // Nothing to be done for scalar shifts.
10153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10154   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10155     return SDValue();
10156
10157   assert(ST->hasNEON() && "unexpected vector shift");
10158   int64_t Cnt;
10159
10160   switch (N->getOpcode()) {
10161   default: llvm_unreachable("unexpected shift opcode");
10162
10163   case ISD::SHL:
10164     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10165       SDLoc dl(N);
10166       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10167                          DAG.getConstant(Cnt, dl, MVT::i32));
10168     }
10169     break;
10170
10171   case ISD::SRA:
10172   case ISD::SRL:
10173     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10174       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10175                             ARMISD::VSHRs : ARMISD::VSHRu);
10176       SDLoc dl(N);
10177       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10178                          DAG.getConstant(Cnt, dl, MVT::i32));
10179     }
10180   }
10181   return SDValue();
10182 }
10183
10184 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10185 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10186 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10187                                     const ARMSubtarget *ST) {
10188   SDValue N0 = N->getOperand(0);
10189
10190   // Check for sign- and zero-extensions of vector extract operations of 8-
10191   // and 16-bit vector elements.  NEON supports these directly.  They are
10192   // handled during DAG combining because type legalization will promote them
10193   // to 32-bit types and it is messy to recognize the operations after that.
10194   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10195     SDValue Vec = N0.getOperand(0);
10196     SDValue Lane = N0.getOperand(1);
10197     EVT VT = N->getValueType(0);
10198     EVT EltVT = N0.getValueType();
10199     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10200
10201     if (VT == MVT::i32 &&
10202         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10203         TLI.isTypeLegal(Vec.getValueType()) &&
10204         isa<ConstantSDNode>(Lane)) {
10205
10206       unsigned Opc = 0;
10207       switch (N->getOpcode()) {
10208       default: llvm_unreachable("unexpected opcode");
10209       case ISD::SIGN_EXTEND:
10210         Opc = ARMISD::VGETLANEs;
10211         break;
10212       case ISD::ZERO_EXTEND:
10213       case ISD::ANY_EXTEND:
10214         Opc = ARMISD::VGETLANEu;
10215         break;
10216       }
10217       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10218     }
10219   }
10220
10221   return SDValue();
10222 }
10223
10224 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
10225                              APInt &KnownOne) {
10226   if (Op.getOpcode() == ARMISD::BFI) {
10227     // Conservatively, we can recurse down the first operand
10228     // and just mask out all affected bits.
10229     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
10230
10231     // The operand to BFI is already a mask suitable for removing the bits it
10232     // sets.
10233     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
10234     APInt Mask = CI->getAPIntValue();
10235     KnownZero &= Mask;
10236     KnownOne &= Mask;
10237     return;
10238   }
10239   if (Op.getOpcode() == ARMISD::CMOV) {
10240     APInt KZ2(KnownZero.getBitWidth(), 0);
10241     APInt KO2(KnownOne.getBitWidth(), 0);
10242     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
10243     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
10244
10245     KnownZero &= KZ2;
10246     KnownOne &= KO2;
10247     return;
10248   }
10249   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
10250 }
10251
10252 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
10253   // If we have a CMOV, OR and AND combination such as:
10254   //   if (x & CN)
10255   //     y |= CM;
10256   //
10257   // And:
10258   //   * CN is a single bit;
10259   //   * All bits covered by CM are known zero in y
10260   //
10261   // Then we can convert this into a sequence of BFI instructions. This will
10262   // always be a win if CM is a single bit, will always be no worse than the
10263   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
10264   // three bits (due to the extra IT instruction).
10265
10266   SDValue Op0 = CMOV->getOperand(0);
10267   SDValue Op1 = CMOV->getOperand(1);
10268   SDValue CmpZ = CMOV->getOperand(4);
10269
10270   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
10271   SDValue And = CmpZ->getOperand(0);
10272   if (And->getOpcode() != ISD::AND)
10273     return SDValue();
10274   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
10275   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
10276     return SDValue();
10277   SDValue X = And->getOperand(0);
10278
10279   // Canonicalize so that the OR is on the left.
10280   if (Op1->getOpcode() == ISD::OR)
10281     std::swap(Op0, Op1);
10282   if (Op0->getOpcode() != ISD::OR)
10283     return SDValue();
10284
10285   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op0->getOperand(1));
10286   if (!OrC)
10287     return SDValue();
10288   SDValue Y = Op0->getOperand(0);
10289
10290   if (Op1 != Y)
10291     return SDValue();
10292
10293   // Now, is it profitable to continue?
10294   APInt OrCI = OrC->getAPIntValue();
10295   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
10296   if (OrCI.countPopulation() > Heuristic)
10297     return SDValue();
10298
10299   // Lastly, can we determine that the bits defined by OrCI
10300   // are zero in Y?
10301   APInt KnownZero, KnownOne;
10302   computeKnownBits(DAG, Y, KnownZero, KnownOne);
10303   if ((OrCI & KnownZero) != OrCI)
10304     return SDValue();
10305
10306   // OK, we can do the combine.
10307   SDValue V = Y;
10308   SDLoc dl(X);
10309   EVT VT = X.getValueType();
10310   unsigned BitInX = AndC->getAPIntValue().logBase2();
10311   
10312   if (BitInX != 0) {
10313     // We must shift X first.
10314     X = DAG.getNode(ISD::SRL, dl, VT, X,
10315                     DAG.getConstant(BitInX, dl, VT));
10316   }
10317
10318   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
10319        BitInY < NumActiveBits; ++BitInY) {
10320     if (OrCI[BitInY] == 0)
10321       continue;
10322     APInt Mask(VT.getSizeInBits(), 0);
10323     Mask.setBit(BitInY);
10324     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
10325                     // Confusingly, the operand is an *inverted* mask.
10326                     DAG.getConstant(~Mask, dl, VT));
10327   }
10328
10329   return V;
10330 }
10331
10332 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10333 SDValue
10334 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10335   SDValue Cmp = N->getOperand(4);
10336   if (Cmp.getOpcode() != ARMISD::CMPZ)
10337     // Only looking at EQ and NE cases.
10338     return SDValue();
10339
10340   EVT VT = N->getValueType(0);
10341   SDLoc dl(N);
10342   SDValue LHS = Cmp.getOperand(0);
10343   SDValue RHS = Cmp.getOperand(1);
10344   SDValue FalseVal = N->getOperand(0);
10345   SDValue TrueVal = N->getOperand(1);
10346   SDValue ARMcc = N->getOperand(2);
10347   ARMCC::CondCodes CC =
10348     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10349
10350   // BFI is only available on V6T2+.
10351   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
10352     SDValue R = PerformCMOVToBFICombine(N, DAG);
10353     if (R)
10354       return R;
10355   }
10356
10357   // Simplify
10358   //   mov     r1, r0
10359   //   cmp     r1, x
10360   //   mov     r0, y
10361   //   moveq   r0, x
10362   // to
10363   //   cmp     r0, x
10364   //   movne   r0, y
10365   //
10366   //   mov     r1, r0
10367   //   cmp     r1, x
10368   //   mov     r0, x
10369   //   movne   r0, y
10370   // to
10371   //   cmp     r0, x
10372   //   movne   r0, y
10373   /// FIXME: Turn this into a target neutral optimization?
10374   SDValue Res;
10375   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10376     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10377                       N->getOperand(3), Cmp);
10378   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10379     SDValue ARMcc;
10380     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10381     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10382                       N->getOperand(3), NewCmp);
10383   }
10384
10385   if (Res.getNode()) {
10386     APInt KnownZero, KnownOne;
10387     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10388     // Capture demanded bits information that would be otherwise lost.
10389     if (KnownZero == 0xfffffffe)
10390       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10391                         DAG.getValueType(MVT::i1));
10392     else if (KnownZero == 0xffffff00)
10393       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10394                         DAG.getValueType(MVT::i8));
10395     else if (KnownZero == 0xffff0000)
10396       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10397                         DAG.getValueType(MVT::i16));
10398   }
10399
10400   return Res;
10401 }
10402
10403 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10404                                              DAGCombinerInfo &DCI) const {
10405   switch (N->getOpcode()) {
10406   default: break;
10407   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10408   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10409   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10410   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10411   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10412   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10413   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10414   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10415   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10416   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10417   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10418   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10419   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10420   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10421   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10422   case ISD::FP_TO_SINT:
10423   case ISD::FP_TO_UINT:
10424     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
10425   case ISD::FDIV:
10426     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
10427   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10428   case ISD::SHL:
10429   case ISD::SRA:
10430   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10431   case ISD::SIGN_EXTEND:
10432   case ISD::ZERO_EXTEND:
10433   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10434   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10435   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10436   case ARMISD::VLD2DUP:
10437   case ARMISD::VLD3DUP:
10438   case ARMISD::VLD4DUP:
10439     return PerformVLDCombine(N, DCI);
10440   case ARMISD::BUILD_VECTOR:
10441     return PerformARMBUILD_VECTORCombine(N, DCI);
10442   case ISD::INTRINSIC_VOID:
10443   case ISD::INTRINSIC_W_CHAIN:
10444     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10445     case Intrinsic::arm_neon_vld1:
10446     case Intrinsic::arm_neon_vld2:
10447     case Intrinsic::arm_neon_vld3:
10448     case Intrinsic::arm_neon_vld4:
10449     case Intrinsic::arm_neon_vld2lane:
10450     case Intrinsic::arm_neon_vld3lane:
10451     case Intrinsic::arm_neon_vld4lane:
10452     case Intrinsic::arm_neon_vst1:
10453     case Intrinsic::arm_neon_vst2:
10454     case Intrinsic::arm_neon_vst3:
10455     case Intrinsic::arm_neon_vst4:
10456     case Intrinsic::arm_neon_vst2lane:
10457     case Intrinsic::arm_neon_vst3lane:
10458     case Intrinsic::arm_neon_vst4lane:
10459       return PerformVLDCombine(N, DCI);
10460     default: break;
10461     }
10462     break;
10463   }
10464   return SDValue();
10465 }
10466
10467 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10468                                                           EVT VT) const {
10469   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10470 }
10471
10472 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10473                                                        unsigned,
10474                                                        unsigned,
10475                                                        bool *Fast) const {
10476   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10477   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10478
10479   switch (VT.getSimpleVT().SimpleTy) {
10480   default:
10481     return false;
10482   case MVT::i8:
10483   case MVT::i16:
10484   case MVT::i32: {
10485     // Unaligned access can use (for example) LRDB, LRDH, LDR
10486     if (AllowsUnaligned) {
10487       if (Fast)
10488         *Fast = Subtarget->hasV7Ops();
10489       return true;
10490     }
10491     return false;
10492   }
10493   case MVT::f64:
10494   case MVT::v2f64: {
10495     // For any little-endian targets with neon, we can support unaligned ld/st
10496     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10497     // A big-endian target may also explicitly support unaligned accesses
10498     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10499       if (Fast)
10500         *Fast = true;
10501       return true;
10502     }
10503     return false;
10504   }
10505   }
10506 }
10507
10508 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10509                        unsigned AlignCheck) {
10510   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10511           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10512 }
10513
10514 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10515                                            unsigned DstAlign, unsigned SrcAlign,
10516                                            bool IsMemset, bool ZeroMemset,
10517                                            bool MemcpyStrSrc,
10518                                            MachineFunction &MF) const {
10519   const Function *F = MF.getFunction();
10520
10521   // See if we can use NEON instructions for this...
10522   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10523       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10524     bool Fast;
10525     if (Size >= 16 &&
10526         (memOpAlign(SrcAlign, DstAlign, 16) ||
10527          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10528       return MVT::v2f64;
10529     } else if (Size >= 8 &&
10530                (memOpAlign(SrcAlign, DstAlign, 8) ||
10531                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10532                  Fast))) {
10533       return MVT::f64;
10534     }
10535   }
10536
10537   // Lowering to i32/i16 if the size permits.
10538   if (Size >= 4)
10539     return MVT::i32;
10540   else if (Size >= 2)
10541     return MVT::i16;
10542
10543   // Let the target-independent logic figure it out.
10544   return MVT::Other;
10545 }
10546
10547 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10548   if (Val.getOpcode() != ISD::LOAD)
10549     return false;
10550
10551   EVT VT1 = Val.getValueType();
10552   if (!VT1.isSimple() || !VT1.isInteger() ||
10553       !VT2.isSimple() || !VT2.isInteger())
10554     return false;
10555
10556   switch (VT1.getSimpleVT().SimpleTy) {
10557   default: break;
10558   case MVT::i1:
10559   case MVT::i8:
10560   case MVT::i16:
10561     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10562     return true;
10563   }
10564
10565   return false;
10566 }
10567
10568 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10569   EVT VT = ExtVal.getValueType();
10570
10571   if (!isTypeLegal(VT))
10572     return false;
10573
10574   // Don't create a loadext if we can fold the extension into a wide/long
10575   // instruction.
10576   // If there's more than one user instruction, the loadext is desirable no
10577   // matter what.  There can be two uses by the same instruction.
10578   if (ExtVal->use_empty() ||
10579       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10580     return true;
10581
10582   SDNode *U = *ExtVal->use_begin();
10583   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10584        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10585     return false;
10586
10587   return true;
10588 }
10589
10590 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10591   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10592     return false;
10593
10594   if (!isTypeLegal(EVT::getEVT(Ty1)))
10595     return false;
10596
10597   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10598
10599   // Assuming the caller doesn't have a zeroext or signext return parameter,
10600   // truncation all the way down to i1 is valid.
10601   return true;
10602 }
10603
10604
10605 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10606   if (V < 0)
10607     return false;
10608
10609   unsigned Scale = 1;
10610   switch (VT.getSimpleVT().SimpleTy) {
10611   default: return false;
10612   case MVT::i1:
10613   case MVT::i8:
10614     // Scale == 1;
10615     break;
10616   case MVT::i16:
10617     // Scale == 2;
10618     Scale = 2;
10619     break;
10620   case MVT::i32:
10621     // Scale == 4;
10622     Scale = 4;
10623     break;
10624   }
10625
10626   if ((V & (Scale - 1)) != 0)
10627     return false;
10628   V /= Scale;
10629   return V == (V & ((1LL << 5) - 1));
10630 }
10631
10632 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10633                                       const ARMSubtarget *Subtarget) {
10634   bool isNeg = false;
10635   if (V < 0) {
10636     isNeg = true;
10637     V = - V;
10638   }
10639
10640   switch (VT.getSimpleVT().SimpleTy) {
10641   default: return false;
10642   case MVT::i1:
10643   case MVT::i8:
10644   case MVT::i16:
10645   case MVT::i32:
10646     // + imm12 or - imm8
10647     if (isNeg)
10648       return V == (V & ((1LL << 8) - 1));
10649     return V == (V & ((1LL << 12) - 1));
10650   case MVT::f32:
10651   case MVT::f64:
10652     // Same as ARM mode. FIXME: NEON?
10653     if (!Subtarget->hasVFP2())
10654       return false;
10655     if ((V & 3) != 0)
10656       return false;
10657     V >>= 2;
10658     return V == (V & ((1LL << 8) - 1));
10659   }
10660 }
10661
10662 /// isLegalAddressImmediate - Return true if the integer value can be used
10663 /// as the offset of the target addressing mode for load / store of the
10664 /// given type.
10665 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10666                                     const ARMSubtarget *Subtarget) {
10667   if (V == 0)
10668     return true;
10669
10670   if (!VT.isSimple())
10671     return false;
10672
10673   if (Subtarget->isThumb1Only())
10674     return isLegalT1AddressImmediate(V, VT);
10675   else if (Subtarget->isThumb2())
10676     return isLegalT2AddressImmediate(V, VT, Subtarget);
10677
10678   // ARM mode.
10679   if (V < 0)
10680     V = - V;
10681   switch (VT.getSimpleVT().SimpleTy) {
10682   default: return false;
10683   case MVT::i1:
10684   case MVT::i8:
10685   case MVT::i32:
10686     // +- imm12
10687     return V == (V & ((1LL << 12) - 1));
10688   case MVT::i16:
10689     // +- imm8
10690     return V == (V & ((1LL << 8) - 1));
10691   case MVT::f32:
10692   case MVT::f64:
10693     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10694       return false;
10695     if ((V & 3) != 0)
10696       return false;
10697     V >>= 2;
10698     return V == (V & ((1LL << 8) - 1));
10699   }
10700 }
10701
10702 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10703                                                       EVT VT) const {
10704   int Scale = AM.Scale;
10705   if (Scale < 0)
10706     return false;
10707
10708   switch (VT.getSimpleVT().SimpleTy) {
10709   default: return false;
10710   case MVT::i1:
10711   case MVT::i8:
10712   case MVT::i16:
10713   case MVT::i32:
10714     if (Scale == 1)
10715       return true;
10716     // r + r << imm
10717     Scale = Scale & ~1;
10718     return Scale == 2 || Scale == 4 || Scale == 8;
10719   case MVT::i64:
10720     // r + r
10721     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10722       return true;
10723     return false;
10724   case MVT::isVoid:
10725     // Note, we allow "void" uses (basically, uses that aren't loads or
10726     // stores), because arm allows folding a scale into many arithmetic
10727     // operations.  This should be made more precise and revisited later.
10728
10729     // Allow r << imm, but the imm has to be a multiple of two.
10730     if (Scale & 1) return false;
10731     return isPowerOf2_32(Scale);
10732   }
10733 }
10734
10735 /// isLegalAddressingMode - Return true if the addressing mode represented
10736 /// by AM is legal for this target, for a load/store of the specified type.
10737 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10738                                               const AddrMode &AM, Type *Ty,
10739                                               unsigned AS) const {
10740   EVT VT = getValueType(DL, Ty, true);
10741   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10742     return false;
10743
10744   // Can never fold addr of global into load/store.
10745   if (AM.BaseGV)
10746     return false;
10747
10748   switch (AM.Scale) {
10749   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10750     break;
10751   case 1:
10752     if (Subtarget->isThumb1Only())
10753       return false;
10754     // FALL THROUGH.
10755   default:
10756     // ARM doesn't support any R+R*scale+imm addr modes.
10757     if (AM.BaseOffs)
10758       return false;
10759
10760     if (!VT.isSimple())
10761       return false;
10762
10763     if (Subtarget->isThumb2())
10764       return isLegalT2ScaledAddressingMode(AM, VT);
10765
10766     int Scale = AM.Scale;
10767     switch (VT.getSimpleVT().SimpleTy) {
10768     default: return false;
10769     case MVT::i1:
10770     case MVT::i8:
10771     case MVT::i32:
10772       if (Scale < 0) Scale = -Scale;
10773       if (Scale == 1)
10774         return true;
10775       // r + r << imm
10776       return isPowerOf2_32(Scale & ~1);
10777     case MVT::i16:
10778     case MVT::i64:
10779       // r + r
10780       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10781         return true;
10782       return false;
10783
10784     case MVT::isVoid:
10785       // Note, we allow "void" uses (basically, uses that aren't loads or
10786       // stores), because arm allows folding a scale into many arithmetic
10787       // operations.  This should be made more precise and revisited later.
10788
10789       // Allow r << imm, but the imm has to be a multiple of two.
10790       if (Scale & 1) return false;
10791       return isPowerOf2_32(Scale);
10792     }
10793   }
10794   return true;
10795 }
10796
10797 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10798 /// icmp immediate, that is the target has icmp instructions which can compare
10799 /// a register against the immediate without having to materialize the
10800 /// immediate into a register.
10801 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10802   // Thumb2 and ARM modes can use cmn for negative immediates.
10803   if (!Subtarget->isThumb())
10804     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10805   if (Subtarget->isThumb2())
10806     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10807   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10808   return Imm >= 0 && Imm <= 255;
10809 }
10810
10811 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10812 /// *or sub* immediate, that is the target has add or sub instructions which can
10813 /// add a register with the immediate without having to materialize the
10814 /// immediate into a register.
10815 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10816   // Same encoding for add/sub, just flip the sign.
10817   int64_t AbsImm = std::abs(Imm);
10818   if (!Subtarget->isThumb())
10819     return ARM_AM::getSOImmVal(AbsImm) != -1;
10820   if (Subtarget->isThumb2())
10821     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10822   // Thumb1 only has 8-bit unsigned immediate.
10823   return AbsImm >= 0 && AbsImm <= 255;
10824 }
10825
10826 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10827                                       bool isSEXTLoad, SDValue &Base,
10828                                       SDValue &Offset, bool &isInc,
10829                                       SelectionDAG &DAG) {
10830   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10831     return false;
10832
10833   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10834     // AddressingMode 3
10835     Base = Ptr->getOperand(0);
10836     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10837       int RHSC = (int)RHS->getZExtValue();
10838       if (RHSC < 0 && RHSC > -256) {
10839         assert(Ptr->getOpcode() == ISD::ADD);
10840         isInc = false;
10841         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10842         return true;
10843       }
10844     }
10845     isInc = (Ptr->getOpcode() == ISD::ADD);
10846     Offset = Ptr->getOperand(1);
10847     return true;
10848   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10849     // AddressingMode 2
10850     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10851       int RHSC = (int)RHS->getZExtValue();
10852       if (RHSC < 0 && RHSC > -0x1000) {
10853         assert(Ptr->getOpcode() == ISD::ADD);
10854         isInc = false;
10855         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10856         Base = Ptr->getOperand(0);
10857         return true;
10858       }
10859     }
10860
10861     if (Ptr->getOpcode() == ISD::ADD) {
10862       isInc = true;
10863       ARM_AM::ShiftOpc ShOpcVal=
10864         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10865       if (ShOpcVal != ARM_AM::no_shift) {
10866         Base = Ptr->getOperand(1);
10867         Offset = Ptr->getOperand(0);
10868       } else {
10869         Base = Ptr->getOperand(0);
10870         Offset = Ptr->getOperand(1);
10871       }
10872       return true;
10873     }
10874
10875     isInc = (Ptr->getOpcode() == ISD::ADD);
10876     Base = Ptr->getOperand(0);
10877     Offset = Ptr->getOperand(1);
10878     return true;
10879   }
10880
10881   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10882   return false;
10883 }
10884
10885 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10886                                      bool isSEXTLoad, SDValue &Base,
10887                                      SDValue &Offset, bool &isInc,
10888                                      SelectionDAG &DAG) {
10889   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10890     return false;
10891
10892   Base = Ptr->getOperand(0);
10893   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10894     int RHSC = (int)RHS->getZExtValue();
10895     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10896       assert(Ptr->getOpcode() == ISD::ADD);
10897       isInc = false;
10898       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10899       return true;
10900     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10901       isInc = Ptr->getOpcode() == ISD::ADD;
10902       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10903       return true;
10904     }
10905   }
10906
10907   return false;
10908 }
10909
10910 /// getPreIndexedAddressParts - returns true by value, base pointer and
10911 /// offset pointer and addressing mode by reference if the node's address
10912 /// can be legally represented as pre-indexed load / store address.
10913 bool
10914 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10915                                              SDValue &Offset,
10916                                              ISD::MemIndexedMode &AM,
10917                                              SelectionDAG &DAG) const {
10918   if (Subtarget->isThumb1Only())
10919     return false;
10920
10921   EVT VT;
10922   SDValue Ptr;
10923   bool isSEXTLoad = false;
10924   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10925     Ptr = LD->getBasePtr();
10926     VT  = LD->getMemoryVT();
10927     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10928   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10929     Ptr = ST->getBasePtr();
10930     VT  = ST->getMemoryVT();
10931   } else
10932     return false;
10933
10934   bool isInc;
10935   bool isLegal = false;
10936   if (Subtarget->isThumb2())
10937     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10938                                        Offset, isInc, DAG);
10939   else
10940     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10941                                         Offset, isInc, DAG);
10942   if (!isLegal)
10943     return false;
10944
10945   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10946   return true;
10947 }
10948
10949 /// getPostIndexedAddressParts - returns true by value, base pointer and
10950 /// offset pointer and addressing mode by reference if this node can be
10951 /// combined with a load / store to form a post-indexed load / store.
10952 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10953                                                    SDValue &Base,
10954                                                    SDValue &Offset,
10955                                                    ISD::MemIndexedMode &AM,
10956                                                    SelectionDAG &DAG) const {
10957   if (Subtarget->isThumb1Only())
10958     return false;
10959
10960   EVT VT;
10961   SDValue Ptr;
10962   bool isSEXTLoad = false;
10963   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10964     VT  = LD->getMemoryVT();
10965     Ptr = LD->getBasePtr();
10966     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10967   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10968     VT  = ST->getMemoryVT();
10969     Ptr = ST->getBasePtr();
10970   } else
10971     return false;
10972
10973   bool isInc;
10974   bool isLegal = false;
10975   if (Subtarget->isThumb2())
10976     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10977                                        isInc, DAG);
10978   else
10979     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10980                                         isInc, DAG);
10981   if (!isLegal)
10982     return false;
10983
10984   if (Ptr != Base) {
10985     // Swap base ptr and offset to catch more post-index load / store when
10986     // it's legal. In Thumb2 mode, offset must be an immediate.
10987     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10988         !Subtarget->isThumb2())
10989       std::swap(Base, Offset);
10990
10991     // Post-indexed load / store update the base pointer.
10992     if (Ptr != Base)
10993       return false;
10994   }
10995
10996   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10997   return true;
10998 }
10999
11000 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11001                                                       APInt &KnownZero,
11002                                                       APInt &KnownOne,
11003                                                       const SelectionDAG &DAG,
11004                                                       unsigned Depth) const {
11005   unsigned BitWidth = KnownOne.getBitWidth();
11006   KnownZero = KnownOne = APInt(BitWidth, 0);
11007   switch (Op.getOpcode()) {
11008   default: break;
11009   case ARMISD::ADDC:
11010   case ARMISD::ADDE:
11011   case ARMISD::SUBC:
11012   case ARMISD::SUBE:
11013     // These nodes' second result is a boolean
11014     if (Op.getResNo() == 0)
11015       break;
11016     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11017     break;
11018   case ARMISD::CMOV: {
11019     // Bits are known zero/one if known on the LHS and RHS.
11020     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11021     if (KnownZero == 0 && KnownOne == 0) return;
11022
11023     APInt KnownZeroRHS, KnownOneRHS;
11024     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11025     KnownZero &= KnownZeroRHS;
11026     KnownOne  &= KnownOneRHS;
11027     return;
11028   }
11029   case ISD::INTRINSIC_W_CHAIN: {
11030     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
11031     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
11032     switch (IntID) {
11033     default: return;
11034     case Intrinsic::arm_ldaex:
11035     case Intrinsic::arm_ldrex: {
11036       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
11037       unsigned MemBits = VT.getScalarType().getSizeInBits();
11038       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
11039       return;
11040     }
11041     }
11042   }
11043   }
11044 }
11045
11046 //===----------------------------------------------------------------------===//
11047 //                           ARM Inline Assembly Support
11048 //===----------------------------------------------------------------------===//
11049
11050 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11051   // Looking for "rev" which is V6+.
11052   if (!Subtarget->hasV6Ops())
11053     return false;
11054
11055   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11056   std::string AsmStr = IA->getAsmString();
11057   SmallVector<StringRef, 4> AsmPieces;
11058   SplitString(AsmStr, AsmPieces, ";\n");
11059
11060   switch (AsmPieces.size()) {
11061   default: return false;
11062   case 1:
11063     AsmStr = AsmPieces[0];
11064     AsmPieces.clear();
11065     SplitString(AsmStr, AsmPieces, " \t,");
11066
11067     // rev $0, $1
11068     if (AsmPieces.size() == 3 &&
11069         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11070         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11071       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11072       if (Ty && Ty->getBitWidth() == 32)
11073         return IntrinsicLowering::LowerToByteSwap(CI);
11074     }
11075     break;
11076   }
11077
11078   return false;
11079 }
11080
11081 /// getConstraintType - Given a constraint letter, return the type of
11082 /// constraint it is for this target.
11083 ARMTargetLowering::ConstraintType
11084 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
11085   if (Constraint.size() == 1) {
11086     switch (Constraint[0]) {
11087     default:  break;
11088     case 'l': return C_RegisterClass;
11089     case 'w': return C_RegisterClass;
11090     case 'h': return C_RegisterClass;
11091     case 'x': return C_RegisterClass;
11092     case 't': return C_RegisterClass;
11093     case 'j': return C_Other; // Constant for movw.
11094       // An address with a single base register. Due to the way we
11095       // currently handle addresses it is the same as an 'r' memory constraint.
11096     case 'Q': return C_Memory;
11097     }
11098   } else if (Constraint.size() == 2) {
11099     switch (Constraint[0]) {
11100     default: break;
11101     // All 'U+' constraints are addresses.
11102     case 'U': return C_Memory;
11103     }
11104   }
11105   return TargetLowering::getConstraintType(Constraint);
11106 }
11107
11108 /// Examine constraint type and operand type and determine a weight value.
11109 /// This object must already have been set up with the operand type
11110 /// and the current alternative constraint selected.
11111 TargetLowering::ConstraintWeight
11112 ARMTargetLowering::getSingleConstraintMatchWeight(
11113     AsmOperandInfo &info, const char *constraint) const {
11114   ConstraintWeight weight = CW_Invalid;
11115   Value *CallOperandVal = info.CallOperandVal;
11116     // If we don't have a value, we can't do a match,
11117     // but allow it at the lowest weight.
11118   if (!CallOperandVal)
11119     return CW_Default;
11120   Type *type = CallOperandVal->getType();
11121   // Look at the constraint type.
11122   switch (*constraint) {
11123   default:
11124     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11125     break;
11126   case 'l':
11127     if (type->isIntegerTy()) {
11128       if (Subtarget->isThumb())
11129         weight = CW_SpecificReg;
11130       else
11131         weight = CW_Register;
11132     }
11133     break;
11134   case 'w':
11135     if (type->isFloatingPointTy())
11136       weight = CW_Register;
11137     break;
11138   }
11139   return weight;
11140 }
11141
11142 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11143 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11144     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11145   if (Constraint.size() == 1) {
11146     // GCC ARM Constraint Letters
11147     switch (Constraint[0]) {
11148     case 'l': // Low regs or general regs.
11149       if (Subtarget->isThumb())
11150         return RCPair(0U, &ARM::tGPRRegClass);
11151       return RCPair(0U, &ARM::GPRRegClass);
11152     case 'h': // High regs or no regs.
11153       if (Subtarget->isThumb())
11154         return RCPair(0U, &ARM::hGPRRegClass);
11155       break;
11156     case 'r':
11157       if (Subtarget->isThumb1Only())
11158         return RCPair(0U, &ARM::tGPRRegClass);
11159       return RCPair(0U, &ARM::GPRRegClass);
11160     case 'w':
11161       if (VT == MVT::Other)
11162         break;
11163       if (VT == MVT::f32)
11164         return RCPair(0U, &ARM::SPRRegClass);
11165       if (VT.getSizeInBits() == 64)
11166         return RCPair(0U, &ARM::DPRRegClass);
11167       if (VT.getSizeInBits() == 128)
11168         return RCPair(0U, &ARM::QPRRegClass);
11169       break;
11170     case 'x':
11171       if (VT == MVT::Other)
11172         break;
11173       if (VT == MVT::f32)
11174         return RCPair(0U, &ARM::SPR_8RegClass);
11175       if (VT.getSizeInBits() == 64)
11176         return RCPair(0U, &ARM::DPR_8RegClass);
11177       if (VT.getSizeInBits() == 128)
11178         return RCPair(0U, &ARM::QPR_8RegClass);
11179       break;
11180     case 't':
11181       if (VT == MVT::f32)
11182         return RCPair(0U, &ARM::SPRRegClass);
11183       break;
11184     }
11185   }
11186   if (StringRef("{cc}").equals_lower(Constraint))
11187     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11188
11189   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11190 }
11191
11192 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11193 /// vector.  If it is invalid, don't add anything to Ops.
11194 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11195                                                      std::string &Constraint,
11196                                                      std::vector<SDValue>&Ops,
11197                                                      SelectionDAG &DAG) const {
11198   SDValue Result;
11199
11200   // Currently only support length 1 constraints.
11201   if (Constraint.length() != 1) return;
11202
11203   char ConstraintLetter = Constraint[0];
11204   switch (ConstraintLetter) {
11205   default: break;
11206   case 'j':
11207   case 'I': case 'J': case 'K': case 'L':
11208   case 'M': case 'N': case 'O':
11209     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11210     if (!C)
11211       return;
11212
11213     int64_t CVal64 = C->getSExtValue();
11214     int CVal = (int) CVal64;
11215     // None of these constraints allow values larger than 32 bits.  Check
11216     // that the value fits in an int.
11217     if (CVal != CVal64)
11218       return;
11219
11220     switch (ConstraintLetter) {
11221       case 'j':
11222         // Constant suitable for movw, must be between 0 and
11223         // 65535.
11224         if (Subtarget->hasV6T2Ops())
11225           if (CVal >= 0 && CVal <= 65535)
11226             break;
11227         return;
11228       case 'I':
11229         if (Subtarget->isThumb1Only()) {
11230           // This must be a constant between 0 and 255, for ADD
11231           // immediates.
11232           if (CVal >= 0 && CVal <= 255)
11233             break;
11234         } else if (Subtarget->isThumb2()) {
11235           // A constant that can be used as an immediate value in a
11236           // data-processing instruction.
11237           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11238             break;
11239         } else {
11240           // A constant that can be used as an immediate value in a
11241           // data-processing instruction.
11242           if (ARM_AM::getSOImmVal(CVal) != -1)
11243             break;
11244         }
11245         return;
11246
11247       case 'J':
11248         if (Subtarget->isThumb()) {  // FIXME thumb2
11249           // This must be a constant between -255 and -1, for negated ADD
11250           // immediates. This can be used in GCC with an "n" modifier that
11251           // prints the negated value, for use with SUB instructions. It is
11252           // not useful otherwise but is implemented for compatibility.
11253           if (CVal >= -255 && CVal <= -1)
11254             break;
11255         } else {
11256           // This must be a constant between -4095 and 4095. It is not clear
11257           // what this constraint is intended for. Implemented for
11258           // compatibility with GCC.
11259           if (CVal >= -4095 && CVal <= 4095)
11260             break;
11261         }
11262         return;
11263
11264       case 'K':
11265         if (Subtarget->isThumb1Only()) {
11266           // A 32-bit value where only one byte has a nonzero value. Exclude
11267           // zero to match GCC. This constraint is used by GCC internally for
11268           // constants that can be loaded with a move/shift combination.
11269           // It is not useful otherwise but is implemented for compatibility.
11270           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11271             break;
11272         } else if (Subtarget->isThumb2()) {
11273           // A constant whose bitwise inverse can be used as an immediate
11274           // value in a data-processing instruction. This can be used in GCC
11275           // with a "B" modifier that prints the inverted value, for use with
11276           // BIC and MVN instructions. It is not useful otherwise but is
11277           // implemented for compatibility.
11278           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11279             break;
11280         } else {
11281           // A constant whose bitwise inverse can be used as an immediate
11282           // value in a data-processing instruction. This can be used in GCC
11283           // with a "B" modifier that prints the inverted value, for use with
11284           // BIC and MVN instructions. It is not useful otherwise but is
11285           // implemented for compatibility.
11286           if (ARM_AM::getSOImmVal(~CVal) != -1)
11287             break;
11288         }
11289         return;
11290
11291       case 'L':
11292         if (Subtarget->isThumb1Only()) {
11293           // This must be a constant between -7 and 7,
11294           // for 3-operand ADD/SUB immediate instructions.
11295           if (CVal >= -7 && CVal < 7)
11296             break;
11297         } else if (Subtarget->isThumb2()) {
11298           // A constant whose negation can be used as an immediate value in a
11299           // data-processing instruction. This can be used in GCC with an "n"
11300           // modifier that prints the negated value, for use with SUB
11301           // instructions. It is not useful otherwise but is implemented for
11302           // compatibility.
11303           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11304             break;
11305         } else {
11306           // A constant whose negation can be used as an immediate value in a
11307           // data-processing instruction. This can be used in GCC with an "n"
11308           // modifier that prints the negated value, for use with SUB
11309           // instructions. It is not useful otherwise but is implemented for
11310           // compatibility.
11311           if (ARM_AM::getSOImmVal(-CVal) != -1)
11312             break;
11313         }
11314         return;
11315
11316       case 'M':
11317         if (Subtarget->isThumb()) { // FIXME thumb2
11318           // This must be a multiple of 4 between 0 and 1020, for
11319           // ADD sp + immediate.
11320           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11321             break;
11322         } else {
11323           // A power of two or a constant between 0 and 32.  This is used in
11324           // GCC for the shift amount on shifted register operands, but it is
11325           // useful in general for any shift amounts.
11326           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11327             break;
11328         }
11329         return;
11330
11331       case 'N':
11332         if (Subtarget->isThumb()) {  // FIXME thumb2
11333           // This must be a constant between 0 and 31, for shift amounts.
11334           if (CVal >= 0 && CVal <= 31)
11335             break;
11336         }
11337         return;
11338
11339       case 'O':
11340         if (Subtarget->isThumb()) {  // FIXME thumb2
11341           // This must be a multiple of 4 between -508 and 508, for
11342           // ADD/SUB sp = sp + immediate.
11343           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11344             break;
11345         }
11346         return;
11347     }
11348     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11349     break;
11350   }
11351
11352   if (Result.getNode()) {
11353     Ops.push_back(Result);
11354     return;
11355   }
11356   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11357 }
11358
11359 static RTLIB::Libcall getDivRemLibcall(
11360     const SDNode *N, MVT::SimpleValueType SVT) {
11361   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11362           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11363          "Unhandled Opcode in getDivRemLibcall");
11364   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11365                   N->getOpcode() == ISD::SREM;
11366   RTLIB::Libcall LC;
11367   switch (SVT) {
11368   default: llvm_unreachable("Unexpected request for libcall!");
11369   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11370   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11371   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11372   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11373   }
11374   return LC;
11375 }
11376
11377 static TargetLowering::ArgListTy getDivRemArgList(
11378     const SDNode *N, LLVMContext *Context) {
11379   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
11380           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
11381          "Unhandled Opcode in getDivRemArgList");
11382   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
11383                   N->getOpcode() == ISD::SREM;
11384   TargetLowering::ArgListTy Args;
11385   TargetLowering::ArgListEntry Entry;
11386   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11387     EVT ArgVT = N->getOperand(i).getValueType();
11388     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
11389     Entry.Node = N->getOperand(i);
11390     Entry.Ty = ArgTy;
11391     Entry.isSExt = isSigned;
11392     Entry.isZExt = !isSigned;
11393     Args.push_back(Entry);
11394   }
11395   return Args;
11396 }
11397
11398 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11399   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11400          "Register-based DivRem lowering only");
11401   unsigned Opcode = Op->getOpcode();
11402   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11403          "Invalid opcode for Div/Rem lowering");
11404   bool isSigned = (Opcode == ISD::SDIVREM);
11405   EVT VT = Op->getValueType(0);
11406   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11407
11408   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
11409                                        VT.getSimpleVT().SimpleTy);
11410   SDValue InChain = DAG.getEntryNode();
11411
11412   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
11413                                                     DAG.getContext());
11414
11415   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11416                                          getPointerTy(DAG.getDataLayout()));
11417
11418   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11419
11420   SDLoc dl(Op);
11421   TargetLowering::CallLoweringInfo CLI(DAG);
11422   CLI.setDebugLoc(dl).setChain(InChain)
11423     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11424     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11425
11426   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11427   return CallInfo.first;
11428 }
11429
11430 // Lowers REM using divmod helpers
11431 // see RTABI section 4.2/4.3
11432 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
11433   // Build return types (div and rem)
11434   std::vector<Type*> RetTyParams;
11435   Type *RetTyElement;
11436
11437   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
11438   default: llvm_unreachable("Unexpected request for libcall!");
11439   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
11440   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
11441   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
11442   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
11443   }
11444
11445   RetTyParams.push_back(RetTyElement);
11446   RetTyParams.push_back(RetTyElement);
11447   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
11448   Type *RetTy = StructType::get(*DAG.getContext(), ret);
11449
11450   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
11451                                                              SimpleTy);
11452   SDValue InChain = DAG.getEntryNode();
11453   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext());
11454   bool isSigned = N->getOpcode() == ISD::SREM;
11455   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11456                                          getPointerTy(DAG.getDataLayout()));
11457
11458   // Lower call
11459   CallLoweringInfo CLI(DAG);
11460   CLI.setChain(InChain)
11461      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args), 0)
11462      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
11463   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
11464
11465   // Return second (rem) result operand (first contains div)
11466   SDNode *ResNode = CallResult.first.getNode();
11467   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
11468   return ResNode->getOperand(1);
11469 }
11470
11471 SDValue
11472 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11473   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11474   SDLoc DL(Op);
11475
11476   // Get the inputs.
11477   SDValue Chain = Op.getOperand(0);
11478   SDValue Size  = Op.getOperand(1);
11479
11480   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11481                               DAG.getConstant(2, DL, MVT::i32));
11482
11483   SDValue Flag;
11484   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11485   Flag = Chain.getValue(1);
11486
11487   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11488   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11489
11490   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11491   Chain = NewSP.getValue(1);
11492
11493   SDValue Ops[2] = { NewSP, Chain };
11494   return DAG.getMergeValues(Ops, DL);
11495 }
11496
11497 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11498   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11499          "Unexpected type for custom-lowering FP_EXTEND");
11500
11501   RTLIB::Libcall LC;
11502   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11503
11504   SDValue SrcVal = Op.getOperand(0);
11505   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11506                      SDLoc(Op)).first;
11507 }
11508
11509 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11510   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11511          Subtarget->isFPOnlySP() &&
11512          "Unexpected type for custom-lowering FP_ROUND");
11513
11514   RTLIB::Libcall LC;
11515   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11516
11517   SDValue SrcVal = Op.getOperand(0);
11518   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
11519                      SDLoc(Op)).first;
11520 }
11521
11522 bool
11523 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11524   // The ARM target isn't yet aware of offsets.
11525   return false;
11526 }
11527
11528 bool ARM::isBitFieldInvertedMask(unsigned v) {
11529   if (v == 0xffffffff)
11530     return false;
11531
11532   // there can be 1's on either or both "outsides", all the "inside"
11533   // bits must be 0's
11534   return isShiftedMask_32(~v);
11535 }
11536
11537 /// isFPImmLegal - Returns true if the target can instruction select the
11538 /// specified FP immediate natively. If false, the legalizer will
11539 /// materialize the FP immediate as a load from a constant pool.
11540 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11541   if (!Subtarget->hasVFP3())
11542     return false;
11543   if (VT == MVT::f32)
11544     return ARM_AM::getFP32Imm(Imm) != -1;
11545   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11546     return ARM_AM::getFP64Imm(Imm) != -1;
11547   return false;
11548 }
11549
11550 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11551 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11552 /// specified in the intrinsic calls.
11553 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11554                                            const CallInst &I,
11555                                            unsigned Intrinsic) const {
11556   switch (Intrinsic) {
11557   case Intrinsic::arm_neon_vld1:
11558   case Intrinsic::arm_neon_vld2:
11559   case Intrinsic::arm_neon_vld3:
11560   case Intrinsic::arm_neon_vld4:
11561   case Intrinsic::arm_neon_vld2lane:
11562   case Intrinsic::arm_neon_vld3lane:
11563   case Intrinsic::arm_neon_vld4lane: {
11564     Info.opc = ISD::INTRINSIC_W_CHAIN;
11565     // Conservatively set memVT to the entire set of vectors loaded.
11566     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11567     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11568     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11569     Info.ptrVal = I.getArgOperand(0);
11570     Info.offset = 0;
11571     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11572     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11573     Info.vol = false; // volatile loads with NEON intrinsics not supported
11574     Info.readMem = true;
11575     Info.writeMem = false;
11576     return true;
11577   }
11578   case Intrinsic::arm_neon_vst1:
11579   case Intrinsic::arm_neon_vst2:
11580   case Intrinsic::arm_neon_vst3:
11581   case Intrinsic::arm_neon_vst4:
11582   case Intrinsic::arm_neon_vst2lane:
11583   case Intrinsic::arm_neon_vst3lane:
11584   case Intrinsic::arm_neon_vst4lane: {
11585     Info.opc = ISD::INTRINSIC_VOID;
11586     // Conservatively set memVT to the entire set of vectors stored.
11587     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11588     unsigned NumElts = 0;
11589     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11590       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11591       if (!ArgTy->isVectorTy())
11592         break;
11593       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11594     }
11595     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11596     Info.ptrVal = I.getArgOperand(0);
11597     Info.offset = 0;
11598     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11599     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11600     Info.vol = false; // volatile stores with NEON intrinsics not supported
11601     Info.readMem = false;
11602     Info.writeMem = true;
11603     return true;
11604   }
11605   case Intrinsic::arm_ldaex:
11606   case Intrinsic::arm_ldrex: {
11607     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11608     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11609     Info.opc = ISD::INTRINSIC_W_CHAIN;
11610     Info.memVT = MVT::getVT(PtrTy->getElementType());
11611     Info.ptrVal = I.getArgOperand(0);
11612     Info.offset = 0;
11613     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11614     Info.vol = true;
11615     Info.readMem = true;
11616     Info.writeMem = false;
11617     return true;
11618   }
11619   case Intrinsic::arm_stlex:
11620   case Intrinsic::arm_strex: {
11621     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11622     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11623     Info.opc = ISD::INTRINSIC_W_CHAIN;
11624     Info.memVT = MVT::getVT(PtrTy->getElementType());
11625     Info.ptrVal = I.getArgOperand(1);
11626     Info.offset = 0;
11627     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11628     Info.vol = true;
11629     Info.readMem = false;
11630     Info.writeMem = true;
11631     return true;
11632   }
11633   case Intrinsic::arm_stlexd:
11634   case Intrinsic::arm_strexd: {
11635     Info.opc = ISD::INTRINSIC_W_CHAIN;
11636     Info.memVT = MVT::i64;
11637     Info.ptrVal = I.getArgOperand(2);
11638     Info.offset = 0;
11639     Info.align = 8;
11640     Info.vol = true;
11641     Info.readMem = false;
11642     Info.writeMem = true;
11643     return true;
11644   }
11645   case Intrinsic::arm_ldaexd:
11646   case Intrinsic::arm_ldrexd: {
11647     Info.opc = ISD::INTRINSIC_W_CHAIN;
11648     Info.memVT = MVT::i64;
11649     Info.ptrVal = I.getArgOperand(0);
11650     Info.offset = 0;
11651     Info.align = 8;
11652     Info.vol = true;
11653     Info.readMem = true;
11654     Info.writeMem = false;
11655     return true;
11656   }
11657   default:
11658     break;
11659   }
11660
11661   return false;
11662 }
11663
11664 /// \brief Returns true if it is beneficial to convert a load of a constant
11665 /// to just the constant itself.
11666 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11667                                                           Type *Ty) const {
11668   assert(Ty->isIntegerTy());
11669
11670   unsigned Bits = Ty->getPrimitiveSizeInBits();
11671   if (Bits == 0 || Bits > 32)
11672     return false;
11673   return true;
11674 }
11675
11676 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11677                                         ARM_MB::MemBOpt Domain) const {
11678   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11679
11680   // First, if the target has no DMB, see what fallback we can use.
11681   if (!Subtarget->hasDataBarrier()) {
11682     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11683     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11684     // here.
11685     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11686       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11687       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11688                         Builder.getInt32(0), Builder.getInt32(7),
11689                         Builder.getInt32(10), Builder.getInt32(5)};
11690       return Builder.CreateCall(MCR, args);
11691     } else {
11692       // Instead of using barriers, atomic accesses on these subtargets use
11693       // libcalls.
11694       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11695     }
11696   } else {
11697     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11698     // Only a full system barrier exists in the M-class architectures.
11699     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11700     Constant *CDomain = Builder.getInt32(Domain);
11701     return Builder.CreateCall(DMB, CDomain);
11702   }
11703 }
11704
11705 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11706 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11707                                          AtomicOrdering Ord, bool IsStore,
11708                                          bool IsLoad) const {
11709   if (!getInsertFencesForAtomic())
11710     return nullptr;
11711
11712   switch (Ord) {
11713   case NotAtomic:
11714   case Unordered:
11715     llvm_unreachable("Invalid fence: unordered/non-atomic");
11716   case Monotonic:
11717   case Acquire:
11718     return nullptr; // Nothing to do
11719   case SequentiallyConsistent:
11720     if (!IsStore)
11721       return nullptr; // Nothing to do
11722     /*FALLTHROUGH*/
11723   case Release:
11724   case AcquireRelease:
11725     if (Subtarget->isSwift())
11726       return makeDMB(Builder, ARM_MB::ISHST);
11727     // FIXME: add a comment with a link to documentation justifying this.
11728     else
11729       return makeDMB(Builder, ARM_MB::ISH);
11730   }
11731   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11732 }
11733
11734 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11735                                           AtomicOrdering Ord, bool IsStore,
11736                                           bool IsLoad) const {
11737   if (!getInsertFencesForAtomic())
11738     return nullptr;
11739
11740   switch (Ord) {
11741   case NotAtomic:
11742   case Unordered:
11743     llvm_unreachable("Invalid fence: unordered/not-atomic");
11744   case Monotonic:
11745   case Release:
11746     return nullptr; // Nothing to do
11747   case Acquire:
11748   case AcquireRelease:
11749   case SequentiallyConsistent:
11750     return makeDMB(Builder, ARM_MB::ISH);
11751   }
11752   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11753 }
11754
11755 // Loads and stores less than 64-bits are already atomic; ones above that
11756 // are doomed anyway, so defer to the default libcall and blame the OS when
11757 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11758 // anything for those.
11759 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11760   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11761   return (Size == 64) && !Subtarget->isMClass();
11762 }
11763
11764 // Loads and stores less than 64-bits are already atomic; ones above that
11765 // are doomed anyway, so defer to the default libcall and blame the OS when
11766 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11767 // anything for those.
11768 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11769 // guarantee, see DDI0406C ARM architecture reference manual,
11770 // sections A8.8.72-74 LDRD)
11771 TargetLowering::AtomicExpansionKind
11772 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11773   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11774   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLSC
11775                                                   : AtomicExpansionKind::None;
11776 }
11777
11778 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11779 // and up to 64 bits on the non-M profiles
11780 TargetLowering::AtomicExpansionKind
11781 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11782   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11783   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11784              ? AtomicExpansionKind::LLSC
11785              : AtomicExpansionKind::None;
11786 }
11787
11788 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
11789     AtomicCmpXchgInst *AI) const {
11790   return true;
11791 }
11792
11793 // This has so far only been implemented for MachO.
11794 bool ARMTargetLowering::useLoadStackGuardNode() const {
11795   return Subtarget->isTargetMachO();
11796 }
11797
11798 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11799                                                   unsigned &Cost) const {
11800   // If we do not have NEON, vector types are not natively supported.
11801   if (!Subtarget->hasNEON())
11802     return false;
11803
11804   // Floating point values and vector values map to the same register file.
11805   // Therefore, although we could do a store extract of a vector type, this is
11806   // better to leave at float as we have more freedom in the addressing mode for
11807   // those.
11808   if (VectorTy->isFPOrFPVectorTy())
11809     return false;
11810
11811   // If the index is unknown at compile time, this is very expensive to lower
11812   // and it is not possible to combine the store with the extract.
11813   if (!isa<ConstantInt>(Idx))
11814     return false;
11815
11816   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11817   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11818   // We can do a store + vector extract on any vector that fits perfectly in a D
11819   // or Q register.
11820   if (BitWidth == 64 || BitWidth == 128) {
11821     Cost = 0;
11822     return true;
11823   }
11824   return false;
11825 }
11826
11827 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11828                                          AtomicOrdering Ord) const {
11829   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11830   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11831   bool IsAcquire = isAtLeastAcquire(Ord);
11832
11833   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11834   // intrinsic must return {i32, i32} and we have to recombine them into a
11835   // single i64 here.
11836   if (ValTy->getPrimitiveSizeInBits() == 64) {
11837     Intrinsic::ID Int =
11838         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11839     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11840
11841     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11842     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11843
11844     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11845     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11846     if (!Subtarget->isLittle())
11847       std::swap (Lo, Hi);
11848     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11849     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11850     return Builder.CreateOr(
11851         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11852   }
11853
11854   Type *Tys[] = { Addr->getType() };
11855   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11856   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11857
11858   return Builder.CreateTruncOrBitCast(
11859       Builder.CreateCall(Ldrex, Addr),
11860       cast<PointerType>(Addr->getType())->getElementType());
11861 }
11862
11863 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11864     IRBuilder<> &Builder) const {
11865   if (!Subtarget->hasV7Ops())
11866     return;
11867   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11868   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
11869 }
11870
11871 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11872                                                Value *Addr,
11873                                                AtomicOrdering Ord) const {
11874   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11875   bool IsRelease = isAtLeastRelease(Ord);
11876
11877   // Since the intrinsics must have legal type, the i64 intrinsics take two
11878   // parameters: "i32, i32". We must marshal Val into the appropriate form
11879   // before the call.
11880   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11881     Intrinsic::ID Int =
11882         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11883     Function *Strex = Intrinsic::getDeclaration(M, Int);
11884     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11885
11886     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11887     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11888     if (!Subtarget->isLittle())
11889       std::swap (Lo, Hi);
11890     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11891     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11892   }
11893
11894   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11895   Type *Tys[] = { Addr->getType() };
11896   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11897
11898   return Builder.CreateCall(
11899       Strex, {Builder.CreateZExtOrBitCast(
11900                   Val, Strex->getFunctionType()->getParamType(0)),
11901               Addr});
11902 }
11903
11904 /// \brief Lower an interleaved load into a vldN intrinsic.
11905 ///
11906 /// E.g. Lower an interleaved load (Factor = 2):
11907 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11908 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11909 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11910 ///
11911 ///      Into:
11912 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11913 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11914 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11915 bool ARMTargetLowering::lowerInterleavedLoad(
11916     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11917     ArrayRef<unsigned> Indices, unsigned Factor) const {
11918   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11919          "Invalid interleave factor");
11920   assert(!Shuffles.empty() && "Empty shufflevector input");
11921   assert(Shuffles.size() == Indices.size() &&
11922          "Unmatched number of shufflevectors and indices");
11923
11924   VectorType *VecTy = Shuffles[0]->getType();
11925   Type *EltTy = VecTy->getVectorElementType();
11926
11927   const DataLayout &DL = LI->getModule()->getDataLayout();
11928   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11929   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11930
11931   // Skip if we do not have NEON and skip illegal vector types and vector types
11932   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
11933   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
11934     return false;
11935
11936   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11937   // load integer vectors first and then convert to pointer vectors.
11938   if (EltTy->isPointerTy())
11939     VecTy =
11940         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11941
11942   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11943                                             Intrinsic::arm_neon_vld3,
11944                                             Intrinsic::arm_neon_vld4};
11945
11946   IRBuilder<> Builder(LI);
11947   SmallVector<Value *, 2> Ops;
11948
11949   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11950   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11951   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11952
11953   Type *Tys[] = { VecTy, Int8Ptr };
11954   Function *VldnFunc =
11955       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
11956   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11957
11958   // Replace uses of each shufflevector with the corresponding vector loaded
11959   // by ldN.
11960   for (unsigned i = 0; i < Shuffles.size(); i++) {
11961     ShuffleVectorInst *SV = Shuffles[i];
11962     unsigned Index = Indices[i];
11963
11964     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11965
11966     // Convert the integer vector to pointer vector if the element is pointer.
11967     if (EltTy->isPointerTy())
11968       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11969
11970     SV->replaceAllUsesWith(SubVec);
11971   }
11972
11973   return true;
11974 }
11975
11976 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11977 ///
11978 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11979 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11980                                    unsigned NumElts) {
11981   SmallVector<Constant *, 16> Mask;
11982   for (unsigned i = 0; i < NumElts; i++)
11983     Mask.push_back(Builder.getInt32(Start + i));
11984
11985   return ConstantVector::get(Mask);
11986 }
11987
11988 /// \brief Lower an interleaved store into a vstN intrinsic.
11989 ///
11990 /// E.g. Lower an interleaved store (Factor = 3):
11991 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11992 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11993 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11994 ///
11995 ///      Into:
11996 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11997 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11998 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11999 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
12000 ///
12001 /// Note that the new shufflevectors will be removed and we'll only generate one
12002 /// vst3 instruction in CodeGen.
12003 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
12004                                               ShuffleVectorInst *SVI,
12005                                               unsigned Factor) const {
12006   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12007          "Invalid interleave factor");
12008
12009   VectorType *VecTy = SVI->getType();
12010   assert(VecTy->getVectorNumElements() % Factor == 0 &&
12011          "Invalid interleaved store");
12012
12013   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
12014   Type *EltTy = VecTy->getVectorElementType();
12015   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
12016
12017   const DataLayout &DL = SI->getModule()->getDataLayout();
12018   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
12019   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
12020
12021   // Skip if we do not have NEON and skip illegal vector types and vector types
12022   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
12023   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
12024       EltIs64Bits)
12025     return false;
12026
12027   Value *Op0 = SVI->getOperand(0);
12028   Value *Op1 = SVI->getOperand(1);
12029   IRBuilder<> Builder(SI);
12030
12031   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12032   // vectors to integer vectors.
12033   if (EltTy->isPointerTy()) {
12034     Type *IntTy = DL.getIntPtrType(EltTy);
12035
12036     // Convert to the corresponding integer vector.
12037     Type *IntVecTy =
12038         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
12039     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12040     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12041
12042     SubVecTy = VectorType::get(IntTy, NumSubElts);
12043   }
12044
12045   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
12046                                              Intrinsic::arm_neon_vst3,
12047                                              Intrinsic::arm_neon_vst4};
12048   SmallVector<Value *, 6> Ops;
12049
12050   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
12051   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
12052
12053   Type *Tys[] = { Int8Ptr, SubVecTy };
12054   Function *VstNFunc = Intrinsic::getDeclaration(
12055       SI->getModule(), StoreInts[Factor - 2], Tys);
12056
12057   // Split the shufflevector operands into sub vectors for the new vstN call.
12058   for (unsigned i = 0; i < Factor; i++)
12059     Ops.push_back(Builder.CreateShuffleVector(
12060         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
12061
12062   Ops.push_back(Builder.getInt32(SI->getAlignment()));
12063   Builder.CreateCall(VstNFunc, Ops);
12064   return true;
12065 }
12066
12067 enum HABaseType {
12068   HA_UNKNOWN = 0,
12069   HA_FLOAT,
12070   HA_DOUBLE,
12071   HA_VECT64,
12072   HA_VECT128
12073 };
12074
12075 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
12076                                    uint64_t &Members) {
12077   if (auto *ST = dyn_cast<StructType>(Ty)) {
12078     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
12079       uint64_t SubMembers = 0;
12080       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
12081         return false;
12082       Members += SubMembers;
12083     }
12084   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
12085     uint64_t SubMembers = 0;
12086     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
12087       return false;
12088     Members += SubMembers * AT->getNumElements();
12089   } else if (Ty->isFloatTy()) {
12090     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
12091       return false;
12092     Members = 1;
12093     Base = HA_FLOAT;
12094   } else if (Ty->isDoubleTy()) {
12095     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
12096       return false;
12097     Members = 1;
12098     Base = HA_DOUBLE;
12099   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
12100     Members = 1;
12101     switch (Base) {
12102     case HA_FLOAT:
12103     case HA_DOUBLE:
12104       return false;
12105     case HA_VECT64:
12106       return VT->getBitWidth() == 64;
12107     case HA_VECT128:
12108       return VT->getBitWidth() == 128;
12109     case HA_UNKNOWN:
12110       switch (VT->getBitWidth()) {
12111       case 64:
12112         Base = HA_VECT64;
12113         return true;
12114       case 128:
12115         Base = HA_VECT128;
12116         return true;
12117       default:
12118         return false;
12119       }
12120     }
12121   }
12122
12123   return (Members > 0 && Members <= 4);
12124 }
12125
12126 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
12127 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
12128 /// passing according to AAPCS rules.
12129 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
12130     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12131   if (getEffectiveCallingConv(CallConv, isVarArg) !=
12132       CallingConv::ARM_AAPCS_VFP)
12133     return false;
12134
12135   HABaseType Base = HA_UNKNOWN;
12136   uint64_t Members = 0;
12137   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
12138   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
12139
12140   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
12141   return IsHA || IsIntArray;
12142 }
12143
12144 unsigned ARMTargetLowering::getExceptionPointerRegister(
12145     const Constant *PersonalityFn) const {
12146   // Platforms which do not use SjLj EH may return values in these registers
12147   // via the personality function.
12148   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
12149 }
12150
12151 unsigned ARMTargetLowering::getExceptionSelectorRegister(
12152     const Constant *PersonalityFn) const {
12153   // Platforms which do not use SjLj EH may return values in these registers
12154   // via the personality function.
12155   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
12156 }